我正在尝试创建自己的图像数据集,并有2个类别。当我使用代码时,图像中只有一个文件夹保留为数组第二次写入-Image数据不能转换为浮点型。我做错了什么?
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
Datadir= 'D:\\mml\\malariya\\'
Categories = ['parazitesone', 'uninfectedone']
for category in Categories:
path = os.path.join(Datadir, category)
for img in os.listdir(path):
img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
plt.imshow(img_array, cmap='gray')
plt.show()发布于 2019-04-13 23:54:39
TypeError: Image data cannot be converted to float是一个duplicate of this question。这个问题可能是因为你试图加载一个无效的图像。os.listdir()还返回目录,这些目录将从imread返回None,并指向TypeError。
我建议检查img是否是一个文件,如果您希望您的图像位于给定的扩展名集中,也要检查这一点。它看起来像这样:
import numpy as np
import matplotlib.pyplot as plt
import cv2
import os
Datadir= 'D:\\mml\\malariya\\'
Categories = ['parazitesone', 'uninfectedone']
for category in Categories:
path = os.path.join(Datadir, category)
for img in os.listdir(path):
img_fname = os.path.join(path, img)
# check if is file
if not os.path.isfile(img_fname):
print('Skipping: {}'.format(img_fname))
continue
# or check for extensions
if not any([img_fname.endswith(e) for e in ['.png', '.jpg']]):
print('This file has an unsupported extension: {}'.format(img_fname))
continue
img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
# or check if the return is None
if img_array is None:
print('This image could not be loaded: {}'.format(img_fname))
continue
plt.imshow(img_array, cmap='gray')
plt.show()当然,您不需要使用所有这些if。选择一个符合您需求的。
https://stackoverflow.com/questions/55667173
复制相似问题