2

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.

2
  • Is it a jpg, JPEG, or png image? Commented Jun 30, 2022 at 13:06
  • double forward slashes, makes the path invalid. double backslashes are actually single backslashes, but the string syntax requires escaping them, so that's why one has to use double backslashes... or use r-strings Commented Jun 30, 2022 at 13:11

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely explained. 👌
1
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__)))

1 Comment

I downvote answers that are wrong, misleading, or not useful (the literal alt-text of the downvote button). I stand by that. see this as a signal to consider a moment longer before posting answers.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.