其实这个问题的出现一般是某个变量是空,也就是'NoneType'类型导致的,大致按照这个方向排错即可解决。最近在处理一个图片问题的时候,大致写的代码是把某个路径下面的图片找到,读到内存里面,在依据x1,y1; x2, y2四个坐标值把图片的ROI扣下来,其中有一段代码是这样写的:
# 遍历
for every_capture_image_dict in content_dict["captures"]:
capture_pic_name = every_capture_image_dict["big_image"]
# 读图片
img = cv2.imread('../Export/' + Sub_Files + '/' + Same_Person_file + '/'
+ capture_pic_name)
crop_image = img[int(every_capture_image_dict["position"]["top"]):
int(every_capture_image_dict["position"]["bottom"]),
int(every_capture_image_dict["position"]["left"]):
int(every_capture_image_dict["position"]["right"])]
cv2.imwrite('1/' + Same_Person_file + '/' + capture_pic_name, crop_image)
运行的时候报错:TypeError: 'NoneType' object has no attribute '__getitem__',定位的代码行是:
int(every_capture_image_dict["position"]["right"])]
按照报错提示,经过我的思考,我猜想是某个变量为空导致的,而这个代码最有可能是空变量的就是img这个东西虽然被都进来了,但是是空值导致的。辛亏小哥机智,提前把路径给print下来了,然后我找到报错对应的图片路径下面,果然这个路径下面的图片有问题,上图为证
有个图片是不支持的格式,于是果断修改了下代码,改成如下:
# 遍历
for every_capture_image_dict in content_dict["captures"]:
capture_pic_name = every_capture_image_dict["big_image"]
# 读图片
img = cv2.imread('../Export/' + Sub_Files + '/' + Same_Person_file + '/'
+ capture_pic_name)
if img is None:
continue
else:
crop_image = img[int(every_capture_image_dict["position"]["top"]):
int(every_capture_image_dict["position"]["bottom"]),
int(every_capture_image_dict["position"]["left"]):
int(every_capture_image_dict["position"]["right"])]
cv2.imwrite('1/' + Same_Person_file + '/' + capture_pic_name, crop_image)
再次运行程序,便顺利通过了!!!
调试程序,本来就是要有耐心的。