Reputation: 1471
I am trying to read images from a text file. Text file contains the paths for those images. Images are in different directories, I checked that they do exist there.
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)
I looked for the answers in 1 and 2 but there was no solution.
Most of the times, folks suggest editing the \
to \\
or something similar because paths to images might be wrong. I think I have tried every combination, but still, no solution.
The error raises in line (h, w) = image.shape[:2]
saying
AttributeError: 'NoneType' object has no attribute 'shape'
I suppose the path to cv2.imread()
can't open it as an image, and giving Nonetype object.
Here are some samples from my text file:
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
I am on Windows 7, 64.
Can anyone help? Thank you.
Upvotes: 1
Views: 118
Reputation: 5805
When you use readlines, you get linefeed/newline characters. If you do a
print(repr(image_path))
You'll see newlines (\n) in the output. Use strip() to remove whitespace (spaces, tabs, newlines, carriage returns) a the beginning and end of strings. So your code becomes:
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)
I also fixed up your path_out
assignment to put all of the output files in the right place.
Upvotes: 1