如何将RGB图像转换为numpy数组?
我有一张RGB图片,我想把它转换成numpy数组。我做了以下操作:
im = cv.LoadImage("abc.tiff")
a = numpy.asarray(im)
这样做后,生成了一个没有形状的数组。我猜它是一个iplimage对象。
15 个回答
92
你也可以使用 matplotlib 来实现这个功能。
from matplotlib.image import imread
img = imread('abc.tiff')
print(type(img))
输出结果是:
<class 'numpy.ndarray'>
103
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’这个函数有点麻烦,因为我需要把输入的数据限制在[0,255]这个范围内,然后转换成字节,最后才能创建一个灰度图像。我大多数时候都是在处理灰度图。
如果是RGB图像的话,可能会像这样:
out_img = Image.fromarray( ycc_uint8, "RGB" )
out_img.save( "ycc.tif" )
198
你可以使用更新版的OpenCV Python接口(如果我没记错的话,从OpenCV 2.2开始就有了)。它直接使用numpy数组:
import cv2
im = cv2.imread("abc.tiff",mode='RGB')
print(type(im))
结果:
<type 'numpy.ndarray'>