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

AttributeError raises when tried to read an image from text file

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

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 and 2中寻找答案,但没有解决方案。 大多数时候,人们建议将 \ 编辑为 \ 或类似的东西,因为图像的路径可能是错误的。我想我已经尝试了所有组合,但仍然没有解决方案。 错误出现在行 (h, w) = image.shape[:2] 中说

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

我想 cv2.imread() 的路径无法将其作为图像打开,并给出 Nonetype 对象。 以下是我的文本文件中的一些示例:

D:\user\data_partitions_annotated\partition1\images3-13-1_00311.jpg
D:\user\data\ImageNet_Utils-master\images\n03343560_url77528821_231f057b3f.jpg
D:\user\data\lighter\images\webcam-fire3\scene00211.jpg
D:\user\data\smoke\images\scene07341.jpeg
D:\user\data\smoke\images\scene07351.jpeg 

我在 Windows 7, 64.

有人可以帮忙吗?谢谢。

当您使用 readlines 时,您会得到 linefeed/newline 个字符。如果你做一个

print(repr(image_path))

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

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 作业,将所有输出文件放在正确的位置。