Home > database >  How to open a random image from specified folder/directory in Python OpenCV
How to open a random image from specified folder/directory in Python OpenCV

Time:10-21

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??

CodePudding user response:

This happens because os.listdir returns the contents of a folder.

Having this folder structure:

images/
    - a.png
    - b.png
    - c.png

This would be the expected result.

>>> os.listdir('images')
['a.png', 'b.png', 'c.png']

file actually contains the name of a file in images/, so cv2.imread does not find the file because it's looking for it in the wrong place.

You have to pass cv2.imread the path to the file:

IMAGE_FOLDER = './images'

filename = random.choice(os.listdir(IMAGE_FOLDER))
path = '%s/%s' % (IMAGE_FOLDER , filename)

capture = cv2.imread(path)

CodePudding user response:

Try this:

import os
import cv2
import random


dirs = []
for i in os.listdir("images"):
    if i.endswith(".JPEG"):
        dirs.append(os.path.join("images", i))

pic = random.choice(dirs)

pic_name = pic.split("\\")[-1]
pic = cv2.imread(pic)

cv2.imshow(pic_name, pic)

cv2.waitKey(0)

CodePudding user response:

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.

  • Related