代码之家  ›  专栏  ›  技术社区  ›  bit_scientist

试图从文本文件读取图像时,AttributeError会引发

  •  0
  • bit_scientist  · 技术社区  · 7 年前

    我正在尝试从文本文件中读取图像。文本文件包含这些图像的路径。图像位于不同的目录中,我检查了它们是否存在。

    PATH_IN = 'D:\\user\\data\\Augmentation'
    path_out = 'D:\\user\\data\\Augmentation\\images_90t'
    
    try:
        if not os.path.exists('images_90t'):
            os.makedirs('images_90t')
    except OSError:
        print ('Error: Creating directory of data')
    
    with open('filelist.txt', 'r') as f:
    
        for image_path in f.readlines():
            image = cv2.imread(image_path, 1)
            print("The type of image is: " , type(image)) # OUTPUT: The type of image is:  <class 'NoneType'>
            (h, w) = image.shape[:2]
            center = (w / 2, h / 2)
            M = cv2.getRotationMatrix2D(center, 90, 1.0)
            rotated = cv2.warpAffine(image, M, (w, h))
            #cv2.imshow("rotated", rotated)
            cv2.imwrite(path_out, rotated)
            cv2.waitKey(0) 
    

    我在 1 2 但没有解决办法。 大多数时候,人们建议编辑 \ \\ 或者类似的东西,因为到图像的路径可能是错误的。我想我已经尝试了各种组合,但仍然没有解决方案。 错误在直线上出现 (h, w) = image.shape[:2]

    AttributeError: 'NoneType' object has no attribute 'shape'
    

    我想 cv2.imread() 无法将其作为图像打开 非类型 对象 以下是我的文本文件中的一些示例:

    D:\user\data\16_partitions_annotated\partition1\images\073-1\073-1_00311.jpg
    D:\user\data\ImageNet_Utils-master\images\n03343560_url\2077528821_231f057b3f.jpg
    D:\user\data\lighter\images\webcam-fire3\scene00211.jpg
    D:\user\data\smoke\11\images\scene07341.jpeg
    D:\user\data\smoke\11\images\scene07351.jpeg 
    

    我在上 Windows 7、64。

    有人能帮忙吗?非常感谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   bfris    7 年前

    使用readlines时,会得到换行符/换行符。如果你做了

    print(repr(image_path))
    

    您将在输出中看到换行符(\n)。使用strip()删除字符串开头和结尾的空格(空格、制表符、换行符、回车符)。因此,您的代码变成:

    import os
    import cv2
    
    PATH_IN = 'D:\\user\\data\\Augmentation'
    path_out = 'D:\\user\\data\\Augmentation\\images_90t'
    
    try:
        if not os.path.exists('images_90t'):
            os.makedirs('images_90t')
    except OSError:
        print ('Error: Creating directory of data')
    
    with open('filelist.txt', 'r') as f:
    
        for image_path in f.readlines():
            print(repr(image_path)) # will show the newlines \n in image_path
            image_path = image_path.strip()
            image = cv2.imread(image_path)
            print("The type of image is: " , type(image)) # OUTPUT: The type of image is:  <class 'NoneType'>
            (h, w) = image.shape[:2]
            center = (w / 2, h / 2)
            M = cv2.getRotationMatrix2D(center, 90, 1.0)
            rotated = cv2.warpAffine(image, M, (w, h))
            #cv2.imshow("rotated", rotated)
            path_out = os.path.join(path_out, os.path.basename(image_path))
            cv2.imwrite(path_out, rotated)
            cv2.waitKey(0) 
    

    我还修复了你的 path_out 将所有输出文件放置在正确位置的赋值。