【问题标题】:AttributeError: 'NoneType' object has no attribute 'shape'AttributeError:“NoneType”对象没有属性“形状”
【发布时间】:2015-05-07 18:41:54
【问题描述】:
import numpy as np 
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('AB.jpg')
mask = np.zeros(img.shape[:2] , np.uint8) 

bgdModel = np.zeros((1,65), np.float64)
fgdModel = np.zeros((1,65), np.float64)

rect = (300 , 120 , 470 , 350)

#this modifies mask
cv2.grabCut(img,mask,rect,bgdModel, fgdModel , 5 , cv2.GC_INIT_WITH_RECT)

#If mask==2 or mask==1 , mask2 get 0, otherwise it gets 1 as 'uint8' type
mask2 = np.where((mask==2) | (mask==0),0,1).astype('uint8')

#adding additional dimension for rgb to the mask, by default it gets 1
#multiply with input image to get the segmented image
img_cut = img*mask2[: , : , np.newaxis]

plt.subplot(211),plt.imshow(img)
plt.title('Input Image') , plt.xticks([]),plt.yticks([])
plt.subplot(212),plt.imshow(img_cut)
plt.title('Grab cut'), plt.xticks([]),plt.yticks([])
plt.show()

编译时出现此错误:

python img.py AB.jpg
Traceback (most recent call last):
File "img.py", line 6, in <module>
mask = np.zeros(img.shape[:2] , np.uint8) 
AttributeError: 'NoneType' object has no attribute 'shape'

【问题讨论】:

标签: python opencv


【解决方案1】:

回答,因为社区把它带回来了。添加我的两个对象(美分)。

您看到该错误的唯一原因是因为您试图获取信息或对最初不存在的对象执行操作。要检查,请尝试打印对象。比如,添加 -

print img      # such as this case
print contours # if you are working with contours and cant draw one
print frame    # if you are working with videos and it doesn't show

给你一个无。这意味着你没有正确阅读它。您提供的图像名称不存在或路径错误。如果你发现这样的错误,这里是快速的事情-

  1. 检查路径或将您的图像带到工作目录
  2. 检查您输入的名称是否正确(包括扩展名-.jpg、.png 等)
  3. 将整个代码放在带有对象的 if 语句中,如果为真则继续执行代码
  4. 如果在 cmets 中提出建议,将添加更多内容。

【讨论】:

    【解决方案2】:

    首先

    python img.py AB.jpg
    

    不会像您期望的那样工作(从当前目录加载 AB.jpg)。要加载的文件在所提供示例的第 6 行中进行了硬编码:要按预期工作,它应该是这样的:

    import sys
    img = cv2.imread(sys.argv[1])
    

    返回错误是因为运行 img.py 的目录(当前工作目录)中不存在 AB.jpg,并且在尝试读取之前没有验证丢失的文件。

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 2021-12-26
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2017-02-11
      • 2021-09-05
      • 2020-04-24
      相关资源
      最近更新 更多