如何解决为什么“cv2.imread”对于具有不同名称的图像文件表现不同?
我正在尝试编写一个 python 脚本,该脚本应该将图像作为输入并裁剪它们并将裁剪后的图像保存在具有相同(原始)文件名的不同文件夹中。所以我写了下面的代码..
import cv2
#import numpy
import os
import glob
#import sys
for imgfile in glob.glob(r"C:\Users\mainu\Documents\ACADEMIC YEAR 20_21\Master thesis\Implementation\Applications\Apps_with_opencv\Test\*.jpg"):
img= cv2.imread(imgfile)
name = os.path.basename(imgfile)
print('old name :',name)
rows,colmn,channel = img.shape # to know the shape of the image
#cv2.imshow('This image has :' + str(rows) +' number of rows,' + str(colmn) +' number of columns',img) #shows the image
#cv2.waitKey(0) #waits untill any key is pressed
cropped_img = img[400:949,408:1588] # here we are cutting the image
#rows,channel = cropped_img.shape # to know the shape of the new image
#cv2.imshow('This image has :' + str(rows) +' number of rows,cropped_img) #shows the new image
#cv2.waitKey(0) #waits untill any key is pressed
filename = r"C:\Users\mainu\Documents\ACADEMIC YEAR 20_21\Master thesis\Implementation\Applications\Apps_with_opencv\Test_2/" + name
name_2 = os.path.basename(filename)
print('new name :',name_2)
cv2.imwrite(filename,cropped_img)
现在的问题是它工作正常,直到它得到如下文件名:tes_1.jpg ...但当文件名更长时不起作用。请看:
(Env_CV2) C:\Users\mainu\Documents\ACADEMIC YEAR 20_21\Master thesis\Implementation\Applications\Apps_with_opencv>"c:/Users/mainu/Documents/ACADEMIC YEAR 20_21/Master thesis/Implementation/Applications/Apps_with_opencv/Env_CV2/Scripts/python.exe" "c:/Users/mainu/Documents/ACADEMIC YEAR 20_21/Master thesis/Implementation/Applications/Apps_with_opencv/Crop_app.py"
old name : test_1.jpg
new name : test_1.jpg
old name : test_2.jpg
new name : test_2.jpg
old name : test_3.jpg
new name : test_3.jpg
old name : test_4.jpg
new name : test_4.jpg
old name : test_5.jpg
new name : test_5.jpg
old name : WebCam_RGB_Car_2_screws_out_#1_°0-03_24_21-10_45.jpg
Traceback (most recent call last):
File "c:/Users/mainu/Documents/ACADEMIC YEAR 20_21/Master thesis/Implementation/Applications/Apps_with_opencv/Crop_app.py",line 13,in <module>
rows,channel = img.shape # to know the shape of the image
AttributeError: 'NoneType' object has no attribute 'shape'
如果有人能解释一下原因就好了..?
解决方法
错误显示您的 img 变量为 None
。这意味着 cv2.imread(imgfile)
行为 for 循环中的某个文件返回了 None
。
如果您传递的文件参数不存在,则 cv2.imread 方法默认返回 None
。它不会引发任何错误。
您可能想在那里放置一个 try-except OR if-else 块来处理丢失的图像。
我想我找到了错误的原因。我的图像文件名包含像“°”这样的字符和空格。当我删除它们时,它起作用了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。