【问题标题】:Open cv 2 wont read images from more then 1 folder?Opencv 2 不会从超过 1 个文件夹中读取图像?
【发布时间】:2019-04-13 15:40:40
【问题描述】:

我尝试从图像创建我自己的数据集并有 2 个类别。当我使用代码时,图像中只有 1 个文件夹保留为数组第二次写入 - 图像数据无法转换为浮点数。我做错了什么?

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()

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    TypeError: Image data cannot be converted to floatduplicate 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。选择一个符合您需求的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多