Dan Raymond
Dan Raymond

Reputation: 143

TypeError: NoneType, when trying to loop crop images

from os import listdir
import cv2


files=listdir('/home/raymond/Desktop/Test/Test') #Importing the dir for cropping
for file in files:
    img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir
    crop_img = img[0:1600, 0:1600]
    cv2.imwrite('/home/raymond/Desktop/Test/cropped'+file,crop_img) # write new data to img 

Im trying to loop crop images, while getting an error of

Traceback (most recent call last):
  File "Files.py", line 8, in <module>
    crop_img = img[0:1600, 0:1600]
TypeError: 'NoneType' object is not subscriptable
(fixi) ➜  exercises 

Upvotes: 2

Views: 951

Answers (2)

J. Smith
J. Smith

Reputation: 108

img = cv2.imread('/home/raymond/Desktop/Test/Test'+file)

Hello Dan Raymond,

This cannot work because Python does not add a slash (/) before listed filenames.
Which means that if you have a filename "hello", then what is appended to '/home/raymond/Desktop/Test/Test' is "hello" which results in '/home/raymond/Desktop/Test/Testhello' which does not exist.

Replace your line with this:

img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file)

Upvotes: 0

daphshez
daphshez

Reputation: 9638

You are probably missing a slash at the end of the path here:

img = cv2.imread('/home/raymond/Desktop/Test/Test'+file) # reading a single image from the dir

Should be:

img = cv2.imread('/home/raymond/Desktop/Test/Test/'+file) # reading a single image from the dir

or even better:

import os 
img = cv2.imread(os.path.join('/home/raymond/Desktop/Test/Test/',file)) # reading a single image from the dir

Upvotes: 1

Related Questions