The Python Oracle

how to convert an RGB image to numpy array?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 183)
00:52 Answer 2 (Score 100)
01:37 Answer 3 (Score 89)
01:55 Answer 4 (Score 45)
02:15 Thank you

--

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

Answer 2 links:
[matplotlib]: https://matplotlib.org

--

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.