2011-10-14 57 views
36

我有一個RGB圖像。我想將它轉換爲numpy數組。我做了以下內容如何將RGB圖像轉換爲numpy數組?

im = cv.LoadImage("abc.tiff") 
a = numpy.asarray(im) 

它創建一個沒有形狀的數組。我認爲它是iplimage對象。

怎麼辦?

感謝

+2

如果'cv'是OpenCV的模塊,那麼你應該把它作爲標記等。此鏈接可能有所幫助:http://opencv.willowgarage.com/documentation/python/cookbook.html#numpy-and-opencv – Paul

回答

55

您可以使用較新的OpenCV的Python接口(如果我沒有記錯的話它是可用,因爲OpenCV的2.2)。它本身使用numpy的數組:

import cv2 
im = cv2.imread("abc.tiff") 
print type(im) 

結果:

<type 'numpy.ndarray'> 
+1

cv2是新界面,使用恕我直言更容易。它旨在更密切地代表C++類。 – Neon22

+6

請注意cv2.imread()在BGR中返回一個不是RGB的numpy數組。 – pnd

+0

它可以處理JPG,PNG和GIF圖像嗎? –

6

您需要使用cv.LoadImageM代替cv.LoadImage的:

In [1]: import cv 
In [2]: import numpy as np 
In [3]: x = cv.LoadImageM('im.tif') 
In [4]: im = np.asarray(x) 
In [5]: im.shape 
Out[5]: (487, 650, 3) 
+0

非常感謝...你能否也請幫我找出如果我創建一個圖像使用'cv.CreateImage(寬度,高度,通道)'...它怎麼能轉換成numpy數組? – Shan

+0

我認爲你需要使用cv.CreateMat來代替或使用cv.CreateMat並使用cv.CvtColor或類似的東西從圖像複製到墊子上。看看保羅在上面發佈的鏈接。 –

2
def opencv_image_as_array(im): 
    """Interface image from OpenCV's native format to a numpy array. 

    note: this is a slicing trick, and modifying the output array will also change 
    the OpenCV image data. if you want a copy, use .copy() method on the array! 
    """ 
    import numpy as np 
    w, h, n = im.width, im.height, im.channels 
    modes = {1:"L", 3:"RGB"}#, 4:"RGBA"} 
    if n not in modes: 
    raise StandardError('unsupported number of channels: {0}'.format(n)) 
    out = np.asarray(im) if n == 1 else np.asarray(im)[:,:,::-1] ## BGR -> RGB 
    return out 
32

PIL(Python圖像庫)和numpy的很好地協同工作。

我使用以下功能。

from PIL import Image 
import numpy as np 

def load_image(infilename) : 
    img = Image.open(infilename) 
    img.load() 
    data = np.asarray(img, dtype="int32") 
    return data 

def save_image(npdata, outfilename) : 
    img = Image.fromarray(np.asarray(np.clip(npdata,0,255), dtype="uint8"), "L") 
    img.save(outfilename) 

在「Image.fromarray」是有點難看因爲我剪輯進入的數據爲[0255],轉換爲字節,然後創建的灰度圖像。我主要工作在灰色。

RGB圖像會是這樣的:

outimg = Image.fromarray(ycc_uint8, "RGB") 
outimg.save("ycc.tif") 
+0

這會失敗並出現錯誤,TypeError:long()參數必須是字符串或數字,而不是'PixelAccess',並且查看PIL的'PixelAccess'類的文檔,但它似乎沒有提供方法來啓用' np.array'將其基礎數據轉換爲'ndarray'格式。你需要省略'img.load()'的使用並且只處理'Image.open(...)'的結果。 – ely

+0

img.load()解決了PIL中一個奇怪的緩存問題。只有明確需要時纔會加載數據。這個例子仍然適用於我,除了使用Pillow(PIL fork)時,將「import Image」更改爲「from PIL import Image」。 –

1

當使用從大衛·普爾的答案我與灰階的PNG也許其他文件關於SystemError。我的解決辦法是:

import numpy as np 
from PIL import Image 

img = Image.open(filename) 
try: 
    data = np.asarray(img, dtype='uint8') 
except SystemError: 
    data = np.asarray(img.getdata(), dtype='uint8') 

其實img.getdata()會工作的所有文件,但它的速度較慢,所以我使用它,只有當其他方法失敗。

+0

這根本不起作用 – mskw

5

您也可以使用matplotlib

import matplotlib.image as mpimg 

img = mpimg.imread('abc.tiff') 
print(type(img)) 

輸出: <class 'numpy.ndarray'>

+1

這很簡單。我喜歡 :) –

相關問題