python - 无法使用 opencv 正确加载包含图像的文件夹
问题描述
我有一个简单的任务要解决。嗯,我是这么想的。我现在已经花了 2 个小时,但我无法修复错误。基本上我只想按目录中的特定速率调整每个图像的大小。所以路径 X 包含很多图像,我想调整所有图像的大小。我的方法如下:
import cv2
import glob
images = [cv2.imread(file) for file in glob.glob("C:\\Users\\Laptop\\Desktop\\imgs*.png")]
for file in images:
try:
img = cv2.imread(file)
img_size = cv2.resize(img, None, fx=0.5, fy= 0.5)
cv2.imwrite(file, img_size)
except Exception as e:
print(e)
我还尝试使用带有 os.listdir() 的 os 库
但我总是得到一个例外,比如:
OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3784: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'
我不知道出了什么问题,如果它无法正确加载图像,或者我只是忘记了一些非常重要的事情。
也许有人可以帮助我...
解决方案
首先,您阅读所有图像:
images = [cv2.imread(file) for file in glob.glob("C:\\Users\\Laptop\\Desktop\\imgs*.png")]
然后对于这些图像中的每一个,您再次调用cv2.imread
:
for file in images:
img = cv2.imread(file)
这一秒imread
毫无意义。您正在传递一个图像数组,而不是一个文件名!
您可能希望像这样循环:
for file in glob.glob("C:\\Users\\Laptop\\Desktop\\imgs*.png"):
try:
img = cv2.imread(file)
img_size = cv2.resize(img, None, fx=0.5, fy= 0.5)
cv2.imwrite(file, img_size)
except Exception as e:
print(e)
推荐阅读
- python - 如何使用 Python 中的生命周期包获得客户生命周期的期望值
- python - 如何以清脆的形式禁用 django 中的字段
- tomcat - Apache Tomcat context.xml 文件
- mysql - MySQL Group and count rows with data
- flutter - firestore 中的子字段颤动
- javascript - 3D画布导览
- dependency-injection - ASP.NET Core 2.0 + Swashbuckle(奇数路径截断)
- python - 让@property 只运行一次
- tomcat - JNDI GlobalNamingResource 加载顺序
- mysql - 从 JSONArray 向 MySQL 表中插入记录