gpt4 book ai didi

python - cv2.imread和os.listdir不起作用

转载 作者:行者123 更新时间:2023-12-02 17:36:55 25 4
gpt4 key购买 nike

我试图通过文件夹中的图像进行进一步处理。
我尝试使用此代码仅读取文件夹中的一张图像

import cv2  
import os

img=cv2.imread('/home/hch/Desktop/Database/sample.jpg')
print (img.shape)

for filename in os.listdir('Database') :
if filename.endswith(".jpg") :
img=cv2.imread(filename)
print (img.shape)

如您所见,第一部分直接读取图像,第二部分则尝试通过 os.listdir读取图像。

问题是第二部分不起作用。它给了我这个信息:
Traceback (most recent call last):
File "resize.py", line 10, in <module>
print (img.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

当我打印文件名时,它会打印图像的名称“sample.jpg”。

您能帮我了解为什么它不起作用吗?

谢谢

最佳答案

问题是openCv无法打开图片。
图片位于目录“数据库”中,但脚本未从此处触发。

您输入的路径错误。

适当的路径为:

img=cv2.imread(os.path.join('Database',filename))

关于python - cv2.imread和os.listdir不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50273023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com