Friday, July 29, 2022

[FIXED] How to open a random image from specified folder/directory in Python OpenCV

Issue

I want my program to open a random image from the folder.

This works:

import cv2
import os
import random

capture = cv2.imread(".Images/IMG_3225.JPEG")

But when I want to do this random it doesn't work:

file = random.choice(os.listdir("./images/"))
capture = cv2.imread(file)

I'm getting the following error:

cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

What am I doing wrong??


Solution

This is one of the small mistakes that we usually overlook while working on it. It is mainly because os.listdir returns the contents of a folder. When you are using os.listdir, it just returns file name. As a result it is running like capture = cv2.imread("file_name.png") whereas it should be capture = cv2.imread("path/file_name.png")

So when you are working, try to use the code snippet:

path = './images'
file = random.choice(os.listdir("./images/"))
capture = cv2.imread(os.path.join(path,file))

This will help you run the code.



Answered By - Joyanta J. Mondal
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.