Home > Mobile >  how to read an image with opencv using path variable in Python
how to read an image with opencv using path variable in Python

Time:07-01

So I have a variable that holds the image path as a string. but I get the below error while trying to read the image using the path variable. The path variable is coming from another function that calls this code.
Error:
can't open/read file: check file path/integrity

My code:

path = "D://dev//py_scripts//SS1.jpg"
image=cv2.imread(path) 

Tried several solutions but ended up with same error.

CodePudding user response:

Double forward slashes make the path invalid.

Use single forward slashes. That is commonly tolerated on Windows, which natively wants backslashes.

Double backslashes are only what you see. They're actually single backslashes in the path/string, but the string syntax requires escaping backslashes (and other stuff) by a preceding backslash, so that's why one has to use double backslashes in most string literals...

Python has "r-strings" ("raw" strings). In a raw string, even backslashes are taken literally, and nothing is escapable (a matching quote character ends the string, always).

"D:/dev/py_scripts/SS1.jpg"
r"D:\dev\py_scripts\SS1.jpg"
"D:\\dev\\py_scripts\\SS1.jpg"

CodePudding user response:

import cv2
path1= "SS1.jpg" 
#sometimes doesnt work depends on the compiler. If its on sub folder #py_scripts\SS1.jpg

or 

path2= "d:\dev\py_scripts\SS1.jpg"

image = cv2.imread(path2)

If you want to use path1 method, and set it to work 100%

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

CodePudding user response:

I would suggest changing the format of the path as follows:

import cv2

#Several options
path = r"D:\dev\py_scripts\SS1.jpg"
path = r"D:/dev/py_scripts/SS1.jpg"
path = "D:/dev/py_scripts/SS1.jpg"
image=cv2.imread(path)

But based on the error you are getting, you need to check the format of the image and its integrity, as the error says. That means you must be able to open the image without issues on an editor like Windows Photos to check if the file is not corrupted.

  • Related