Python cannot find a directory

Question:

I wrote a code like this with jupyter notebook in a project;

import os


image_path = r'C:UsersaysDesktopIR1.jpg'
image_files = os.listdir(image_path)
img = cv2.imread(os.path.join(image_path,image_files))
cv2.imshow('image',img)

it gives an error like;

[WinError 3] The system cannot find the path specified: ‘C:UsersaysDesktopIR1.jpg’

i was trying to print an image and
i had a directory problem

Asked By: Ayşe Nur Eliçora

||

Answers:

Your image_path seems to be a file, not a directory. Drop the file name and you should be OK:

image_path = r'C:UsersaysDesktopIR'
Answered By: Mureinik

The argument to os.listdir() must be the directory, not the image file, so remove 1.jpg.

Then you’ll need to loop over the result of os.listdir(), since it returns a list.

import os

image_path = r'C:UsersaysDesktopIR'
image_files = os.listdir(image_path)
for file in image_files:
    img = cv2.imread(os.path.join(image_path,file))
    cv2.imshow('image',img)
Answered By: Barmar
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.