O'ahrudsayn
O'ahrudsayn

Reputation: 13

Reading image files in a given directory in Python

I want to convert all images in a folder to gray. That's my code and I get this error:

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

import cv2
import os

path = r'C:\Users\User\PycharmProjects\computerVision\CarDetection_withOpenCV\p'
for filename in os.listdir(path):
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

How can I fix this?

Upvotes: 0

Views: 777

Answers (1)

Rakesh
Rakesh

Reputation: 82755

Use full path to file

Ex:

import cv2
import os

path = r'C:\Users\User\PycharmProjects\computerVision\CarDetection_withOpenCV\p'
for filename in os.listdir(path):
    img = cv2.imread(os.path.join(path, filename))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Upvotes: 3

Related Questions