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


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:projectsopencv-pythonopencvmoduleshighguisrcwindow.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

What am I doing wrong??

Asked By: Mattijs Kok



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)

Answered By: Sudomap

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

Having this folder structure:

    - 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)
Answered By: pytness

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