0

I have a ".jpg" image and I can't read it using cv2.imread():

img=cv2.imread(file_path)
print(img.shape) 


AttributeError: 'NoneType' object has no attribute 'shape'

Even if I try :

img=cv2.imread(file_path,cv2.IMREAD_UNCHANGED)
print(img.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

However, if I try :

img=plt.imread(file_path)
print(img.shape) 

It works successfully:

(3300, 2550, 3)

However, I want to work with cv2.imread(), so why its not working here ?

Update: The file basename in the file path contains arabic letters, when I change the base name to english letters, the cv2.imread() works and read the image, but I need to pass it using its original name, so I have tried :

img=cv2.imread(u'{}'.format(file_path))

But still it doesnt work.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
AAA
  • 305
  • 1
  • 7
  • `print(os.getcwd())` -- and post that image file to some file hoster (not image hoster, they convert!) so we can inspect the data of the file. – Christoph Rackwitz Jun 08 '23 at 10:51
  • @ChristophRackwitz I am providing the full path of the image in the variable file_path – AAA Jun 08 '23 at 10:52
  • it's likely not a true JPEG. – Christoph Rackwitz Jun 08 '23 at 10:53
  • @ChristophRackwitz I have updated the post. Please see it. Also, I can't upload the image as it contains sensitive data. – AAA Jun 08 '23 at 12:01
  • 1
    good thinking. arabic letters in the path are probably the issue. OpenCV has trouble with paths that contain "unusual" characters. anything beyond ASCII can get you in trouble. the usual workaround is to read the file using Python itself, then convert the `bytes` to a numpy array, then pass that to `cv.imdecode` -- `u'{}'.format(some_string) == some_string` – Christoph Rackwitz Jun 08 '23 at 12:37
  • 1
    @ChristophRackwitz why would OpenCV have problems with unusual characters? I'd expect it to pass the file name unchanged to a file open call at some point. – Mark Ransom Jun 08 '23 at 12:56
  • @ChristophRackwitz Please write it as an answer – AAA Jun 08 '23 at 12:56
  • @MarkRansom it's a known problem. it is incomprehensible to me too. still, it's real. – Christoph Rackwitz Jun 08 '23 at 13:40
  • 1
    @AAA I'd rather someone flag this as a duplicate of https://stackoverflow.com/questions/24769623/opencv-imread-on-windows-for-non-ascii-file-names so the site's idea (to be a Q&A repository) is adhered to. [it's a common issue but hard to search for](https://stackoverflow.com/search?tab=relevance&q=opencv%20imread%20unicode&searchOn=3) because who'd think the file path being "invalid" could be an issue? it always needs some debugging. – Christoph Rackwitz Jun 08 '23 at 13:43
  • 2
    for completeness (the canonical explains the situation but doesn't give Python code), the usual workaround's code is `cv.imdecode(np.fromfile(fname, np.uint8), flags=cv.IMREAD_COLOR)` – Christoph Rackwitz Jun 08 '23 at 14:01

0 Answers0