简体   繁体   English

如何在 Python OpenCV 中打开指定文件夹/目录中的随机图像

[英]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:\\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??我究竟做错了什么??

This happens because os.listdir returns the contents of a folder.发生这种情况是因为os.listdir返回文件夹的内容。

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. file实际上包含images/中的文件名,因此cv2.imread找不到该文件,因为它在错误的位置寻找它。

You have to pass cv2.imread the path to the file:你必须通过cv2.imread文件的路径:

IMAGE_FOLDER = './images'

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

capture = cv2.imread(path)

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)

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.主要是因为os.listdir返回的是文件夹的内容。 When you are using os.listdir , it just returns file name.当您使用os.listdir ,它只返回文件名。 As a result it is running like capture = cv2.imread("file_name.png") whereas it should be capture = cv2.imread("path/file_name.png")结果它像capture = cv2.imread("file_name.png")一样运行,而它应该是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.这将帮助您运行代码。

Try this:尝试这个:

import random , glob, cv2

images = glob.glob(random.choice("./images/*.jpg"))

img = cv2.imread(images)
cv2.imshow(pic_name, img)
cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM