The Python Oracle

how to convert an RGB image to numpy array?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 How To Convert An Rgb Image To Numpy Array?
00:21 Answer 1 Score 105
00:58 Accepted Answer Score 201
01:17 Answer 3 Score 94
01:28 Answer 4 Score 17
01:45 Thank you

--

Full question
https://stackoverflow.com/questions/7762...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #image #opencv #numpy

#avk47



ACCEPTED ANSWER

Score 201


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 cv2
im = cv2.imread("abc.tiff",mode='RGB')
print(type(im))

result:

<type 'numpy.ndarray'>



ANSWER 2

Score 105


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

I use the following functions.

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 )

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:

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



ANSWER 3

Score 94


You can also use matplotlib for this.

from matplotlib.image import imread

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

output: <class 'numpy.ndarray'>




ANSWER 4

Score 17


Late answer, but I've come to prefer the imageio module to the other alternatives

import imageio
im = imageio.imread('abc.tiff')

Similar to cv2.imread(), it produces a numpy array by default, but in RGB form.