how to convert an RGB image to numpy array?
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'>