Python Forum

Full Version: Error for convert image PIL to CV2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I am working with Python and ia habe a problem with convert the format PIL to CV2, my code is:

from PIL import Image
import numpy as np

img = Image.open('C:/Users/XYZ/example.png')

#Format PIL to CV2
cv_img = np.asarray(img)[:,:,::].copy()
The error is:

Error:
cv_img = np.asarray(img)[:,:,::].copy() Traceback (most recent call last): File "<ipython-input-81-422b4aff8d72>", line 1, in <module> cv_img = np.asarray(img)[:,:,::].copy() IndexError: too many indices for array
Please our help!

Thank,
karlo.
Which dimensions has the picture?
I tried it with a some pic I found on my drive and I didn't recive the error.
Do you need this part: [:,:,::] ? you are copying the whole picture, therefore
cv_img = np.asarray(img).copy()
should work. The picture I used had three dimensions: x, y, colors. In my case 202 x 202 x 3. Maybe you have a greyscale image or so? so that the last dimension is not there. Because it seems only 1 or 2 dimensions should be there, but you want to copy three. Try without [:,:,::] and check the dimensions :)
Thank you very much for your answer, I applied the following line and it works for me now (no error):

img = Image.open('C:/Users/XYZ/example.png').convert('RGB')
... however, I will continue to do tests with what you recommend.

At the moment I have another problem, the decoding I am working on is not good ... I will open a new theme with this problem.

Thanks again!