Python Forum
Error for convert image PIL to CV2 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Error for convert image PIL to CV2 (/thread-9883.html)



Error for convert image PIL to CV2 - karlo123 - May-02-2018

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.


RE: Error for convert image PIL to CV2 - ThiefOfTime - May-02-2018

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 :)


RE: Error for convert image PIL to CV2 - karlo123 - May-07-2018

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!