python - 为什么 CV2 不读取图像?
问题描述
我有一个训练图像和测试图像的数据集。我想要做的是输入训练图像并将它们调整为 150x150 大小。然后,根据图像文件的类名,将标签附加到数组“y”,这是我的标签数组。
但是,我收到此错误消息:
OpenCV(4.2.0) /io/opencv/modules/imgproc/src/resize.cpp:4045: error: (-215:Assertion failed) !ssize.empty() in function 'resize'
我的代码的相关部分如下:
nrows = 150
ncolumns = 150
channels = 3
def read(imgarray):
x = []
y = []
for image in imgarray:
try:
x.append(cv2.resize(cv2.imread(image, cv2.IMREAD_COLOR), (nrows,ncolumns), interpolation=cv2.INTER_CUBIC))
except Exception as e:
print(str(e))
if 'chicken' in image:
y.append(0)
elif 'cat' in image:
y.append(1)
elif 'scoop' in image:
y.append(2)
return x,y
x,y = read(train_images) #train_images is composed of ~5400 images, of mixed sizes and image formats
请有人告诉我为什么 CV2 没有“看到”图像以及如何调整图像大小?
编辑:示例图像名称为“../input/train/train/chicken (1438).jpg”,图像形状为 (340,594, 3)
我正在使用 Kaggle 内核,我的训练图像和测试图像存储在一个名为“输入”的目录中。训练图像在 input/train/train/img.jpg 中,测试图像在 input/test/img2.jpg 中。
更新:当我尝试在 train_images 中显示图像时:
for image in imgarray:
#print(image)
image = mpimg.imread(image)
showplot = plt.imshow(image)
我收到了这个错误:
<built-in function imread> returned NULL without setting an error
这很奇怪,因为前面的代码工作得非常好,显示图像:
import matplotlib.image as mpimg
for i in train_images[0:3]:
img=mpimg.imread(i)
imgplot = plt.imshow(img)
plt.show()
更新:当我输出导致错误的图像时,我得到这个:
Please check this image, has some issues ../input/train/train/scoop (1360).jpg
OpenCV(4.2.0) /io/opencv/modules/imgproc/src/resize.cpp:4045: error: (-215:Assertion failed) !ssize.empty() in function 'resize'
解决方案
简单地说,忽略有问题的图像。
添加标签的方式,即使丢失了一些图像,标签也会添加到数组中。
nrows = 150
ncolumns = 150
channels = 3
def read(imgarray):
x = []
y = []
for image in imgarray:
try:
im = cv2.resize(cv2.imread(image), (nrows,ncolumns)
x.append(im)
print(type(im))
print(im.shape)
if 'chicken' in image:
y.append(0)
elif 'cat' in image:
y.append(1)
elif 'scoop' in image:
y.append(2)
except Exception as e:
print(str(e))
print(f'Please check this image, has some issues {image}')
return x,y
x,y = read(train_images) #train_images is composed of ~5400 images, of mixed sizes and ima
推荐阅读
- javascript - 按顺序异步每一行,等待它返回
- c# - 反序列化 JSON 错误:类型需要 JSON 对象
- clang - libc++ 是否向后兼容旧版本?
- django - django 联系页面错误地发送电子邮件
- mocha.js - 如何在 Cypress It() 命令描述中使用模板文字
- css - 生成字体的 SCSS @each 规则不适用于输出
- php - 爆炸功能还是其他原因?
- python - 在 Plotly 中为具有相应边的每个节点添加图例
- angular - 如何使用 NPM 在 Angular 10 中安装引导 ngx
- unit-testing - Elixir 的 Mix 负载源是否可能来自多个路径?