我尝试根据图像创建自己的数据集,并将其分为2类。当我使用代码时,图像中仅保留1个文件夹,因为数组2nd write-图像数据无法转换为float。我在做什么错了?
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()
答案 0 :(得分:0)
TypeError: Image data cannot be converted to float
是duplicate of this question。问题可能是因为您试图加载无效的图像。 os.listdir()
还会返回目录,而目录会从None
返回imread
,从而导致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
。选择满足您需求的一种。