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

2024-10-03 11:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我成功地调整了图像的大小。但是,保存时出错。在

代码如下。请帮帮我。在

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

错误消息如下。在

^{pr2}$

我不明白为什么上面写着 AttributeError:“NoneType”对象没有属性“shape”


Tags: imageimportimgbaseoscountdircv2
1条回答
网友
1楼 · 发布于 2024-10-03 11:24:51

编辑:

检查图像路径是否正确,以及它是否是一个具有Opencv所接受格式的图像。因为如果路径错误,img = cv2.imread(addr)将返回None,而{}将抛出一个错误

另外,函数scaling\u 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 

那应该行得通!在

相关问题 更多 >