【问题标题】:Scale and Save Images (AttributeError: 'NoneType' object has no attribute 'shape')缩放和保存图像(AttributeError:'NoneType' 对象没有属性'shape')
【发布时间】:2018-10-16 06:18:09
【问题描述】:

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

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

代码如下。请帮帮我。

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'

【问题讨论】:

  • cv2.imread(addr) 返回None。你确定addr 是正确的吗?该目录中是否有任何非图像文件?
  • 确保它是正确的,如果我没有 for 语句运行,那么它运行良好。
  • 上面的代码有点错误,scaling_shirink函数的返回是shirink。
  • 如果有问题,请修复它。如果您不向我们展示真实代码,我们将无能为力。
  • 我解决了这个问题哈哈,这很简单!谢谢你回答约翰:)

标签: python opencv image-processing scale attributeerror


【解决方案1】:

编辑:

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

此外,您的函数 scaling_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 

应该可以!

【讨论】:

  • 这不是导致错误的问题(尽管它是 OP 的另一个问题); img.shapereturn 语句甚至会发生之前抛出错误,因为 imread() 函数正在返回 None
  • @AlexanderReynolds 你是对的!尽管函数中缺少返回也是一个问题。感谢您的提示
猜你喜欢
  • 2019-10-18
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 2020-11-07
  • 2015-07-31
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多