0

I'm writing an script for cropping png images and I get the result, but I also ran into the error "TypeError: 'NoneType' object is not subscriptable"

import os
import cv2

path = "/content/image/"
dest_path = "/content/cropped/"

for f in os.listdir(path):
    image = cv2.imread(os.path.join(path, f))
    imgcropped = image[150:400, 250:600]
    cv2.imwrite(os.path.join(dest_path, f), imgcropped)

Here is my error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-ea6eac11778b> in <module>
      7 for f in os.listdir(path):
      8     image = cv2.imread(os.path.join(path, f))
----> 9     imgcropped = image[150:400, 250:600]
     10     cv2.imwrite(os.path.join(dest_path, f), imgcropped)

TypeError: 'NoneType' object is not subscriptable

enter image description here

Pegah
  • 1
  • 1
  • 1
    `imread` can return None if it fails to read the indicated file. – khelwood Dec 11 '22 at 20:46
  • Are some of the files in `/content/image` not image files? – John Gordon Dec 11 '22 at 20:59
  • All the files are images and the script successfully returns the cropped images. However, it also gives me the mentioned error. – Pegah Dec 11 '22 at 21:34
  • `print(os.listdir(path))` will show the filenames directly. – John Gordon Dec 12 '22 at 01:01
  • I have 7 images in the folder but when I ask how many files there are in the folder it shows one more file which is hidden, I assume. ' import os, os.path print (len([img for img in os.listdir(path)])) ' 8 – Pegah Dec 12 '22 at 01:01
  • `listdir()` does not skip over hidden files. You need special code to exclude those, if that is what you want. – John Gordon Dec 12 '22 at 01:02
  • Thank you so much, John Gordon. I used "print(os.listdir(path))" to show me what is the hidden file and it was ".ipynb_checkpoints". I deleted the hidden file and the code run with no error. Many thanks for the help. I really appreciate it. – Pegah Dec 12 '22 at 01:20

0 Answers0