缩放并保存图像(AttributeError:“ NoneType”对象没有属性“ shape”)

时间:2018-10-15 02:57:28

标签: python opencv image-processing scale attributeerror

我正在尝试缩放一千张图像并将其保存到目录中。

我成功调整了图像大小。但是,保存时会发生错误。

代码在下面。请帮助我。

import cv2
import numpy as np
import os

def scaling_shirink(addr):
    img = cv2.imread(addr)
    height, width = img.shape[:2]
    shrink = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Shrink', shrink)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

count = 0
IMAGE_DIR_BASE = 'C:/ClassShared\Data/CM_ML_IMG_181011/CASE_01/FPS_10_PNG'
image_file_list = os.listdir(IMAGE_DIR_BASE)
for file_name in image_file_list:
    image = scaling_shirink(IMAGE_DIR_BASE + '/' + file_name)
    cv2.imwrite('C:/ClassShared\Data/CM_ML_IMG_181011/CASE_01/34_sdetect_db1/' + '_' + "%04d" % (count) + '.png', image)
    count = count + 1

错误消息如下。

Traceback (most recent call last):
  File "C:/PycharmProjects/TS_S/Scailing.py", line 19, in <module>
    image = scaling_shirink(IMAGE_DIR_BASE + '/' + file_name)
  File "C:/PycharmProjects/TS_S/Scailing.py", line 8, in scaling_shirink
    height, width = img.shape[:2]
AttributeError: 'NoneType' object has no attribute 'shape'

我不明白为什么会这样说     AttributeError:“ NoneType”对象没有属性“ shape”

1 个答案:

答案 0 :(得分:1)

编辑:

检查图像路径是否正确以及它是否实际上是Opencv接受的格式的图像。因为如果您的路径错误,img = cv2.imread(addr)将返回None,而height, width = img.shape[:2]将引发错误

另外,您的函数scale_shirink()返回None。 要对其进行修复,只需将其更改为以下功能即可:

def scaling_shirink(addr):
    img = cv2.imread(addr)
    height, width = img.shape[:2]
    shrink = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Shrink', shrink)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    #this return was missing
    return shrink 

应该可以!