0

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

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) 

我在12中寻找答案,但没有解决方案。大多数时候,人们建议编辑\to\\或类似的东西,因为图像的路径可能是错误的。我想我已经尝试了每一种组合,但仍然没有解决方案。(h, w) = image.shape[:2]错误在行中引发

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

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

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 上。

任何人都可以帮忙吗?谢谢你。

4

1 回答 1

1

当您使用 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任务,将所有输出文件放在正确的位置。

于 2018-04-27T18:46:57.203 回答