how to convert an RGB image to numpy array? how to convert an RGB image to numpy array? python python

how to convert an RGB image to numpy array?


You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays:

import cv2im = cv2.imread("abc.tiff",mode='RGB')print type(im)

result:

<type 'numpy.ndarray'>


PIL (Python Imaging Library) and Numpy work well together.

I use the following functions.

from PIL import Imageimport numpy as npdef load_image( infilename ) :    img = Image.open( infilename )    img.load()    data = np.asarray( img, dtype="int32" )    return datadef save_image( npdata, outfilename ) :    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )    img.save( outfilename )

The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.

An RGB image would be something like:

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


You can also use matplotlib for this.

from matplotlib.image import imreadimg = imread('abc.tiff')print(type(img))

output:<class 'numpy.ndarray'>