Why isn't imread in openCV opening some of the images?

Question:

The error im getting is

“Traceback (most recent call last): File
“C:UsersharitDesktopred.py”, line 6, in
cv2.imshow(‘img’,img) error: C:projectsopencv-pythonopencvmoduleshighguisrcwindow.cpp:304:
error: (-215) size.width>0 && size.height>0 in function cv::imshow”

The relevant code is this:

import cv2
import numpy as np

img = cv2.imread('C:UsersharitDesktopimages12.jpg')

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Asked By: Harit Ahuja

||

Answers:

Try changing

img = cv2.imread('C:UsersharitDesktopimages12.jpg')

to

img = cv2.imread(r'C:UsersharitDesktopimages12.jpg')

Backslash is an escape character, and the r before the quotes tells python to “ignore” them.

For example:

>>> s = 'C:UsersharitDesktopimages12.jpg'
>>> print s
C:UsersharitDesktopimages
.jpg

This is the wrong path!… with an ‘r’ in front of the string:

>>> s = r'C:UsersharitDesktopimages12.jpg'
>>> print s
C:UsersharitDesktopimages12.jpg

See https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals for more on raw strings

I think I kind of understand the problem. Maybe I am wrong with my solution. When I first encountered this problem I thought that open cv only accepts png images instead of jpg however, even after converting the image into an png it still did not make the problem go away. Later on, I tried to rename the name of the image and the new name started with a letter instead of a number and it worked. So, maybe python open cv can’t read files with names starting with a number like it cannot accept any variable names that start with numbers. Maybe I am totally wrong, but renaming the image file made the problem go away.

Answered By: srijon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.