TypeError:NoneType,尝试循环裁剪图像时

时间:2019-02-20 08:43:09

标签: python

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 

我正在尝试循环裁剪图像,但出现错误

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 

2 个答案:

答案 0 :(得分:1)

您可能在此处的路径末尾缺少斜线:

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

应该是:

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

甚至更好:

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

答案 1 :(得分:0)

  

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

你好Dan Raymond,

这不起作用,因为 Python 不会在列出的文件名之前添加斜杠(/)。
这意味着,如果文件名是“ hello”,则附加到“ / home / raymond / Desktop / Test / Test”的文件是“ hello”,这将导致'/ home / raymond / Desktop / Test / Testhello 不存在。

用以下内容替换行:

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