【问题标题】:OpenCV-Python: object of type 'NoneType' has no len()OpenCV-Python:“NoneType”类型的对象没有 len()
【发布时间】:2018-08-30 11:27:33
【问题描述】:

我有以下 Python 代码在标题中引发错误:

# calculate number of all ROI pixels inside defined(hsv -) color range 
pts2 = cv2.findNonZero(mask_final)
non_zero_pixel = int(len(pts2))

这里也一样:

# calculate number of all ROI pixels inside defined(bgr -) color range "black"
pts = cv2.findNonZero(mask_black)
black_pixel = int(len(pts))

我从它的 C++ 版本中翻译了这段代码,它确实可以正常工作:

// Calculate number of all ROI pixels inside defined (hsv-)color range           
vector<Point> pts2;
findNonZero(mask_final, pts2);
double non_zero_pixel = static_cast<int>(pts2.size());

我不知道为什么 Python 版本会出现问题,而 C++ 版本不会。

有什么想法吗?

编辑:异常详情:

--------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-119-f76eaba94311> in <module>()
     28 
     29 if __name__ == "__main__":
---> 30     main() # pass the list of arguments from the command line

<ipython-input-119-f76eaba94311> in main()
     16 
     17         # detect screws
---> 18         detectScrews(img)
     19 
     20         for j in range(len(screw_radiuses)):

<ipython-input-118-4c225e9bc794> in detectScrews(img)
     80             # calculate number of all ROI pixels inside defined(bgr -) color range "black"
     81             pts = cv2.findNonZero(mask_black)
---> 82             black_pixel = int(len(pts))
     83 
     84             # if number of black pixel is lower than threshold

TypeError: object of type 'NoneType' has no len()

【问题讨论】:

  • 你检查过文档,看看是什么情况导致cv2.findNonZero(mask_black) 返回无?
  • 为什么 C++ 版本不这样做?我在同一个图像上运行它。 Python 一个失败,C++ 一个通过。这很奇怪。
  • 因为函数在返回的内容和时间方面可能有不同的行为。同样,文档可能会在这里给出答案。
  • 我试图在我的回答中回答你的问题。

标签: python c++ opencv


【解决方案1】:

表示mask_final中没有非零元素。

这显示了同样的错误:

print(len(cv2.findNonZero(np.zeros([3,3], np.uint8))))

为什么 C++ 版本不这样做?我在同一个图像上运行它。 Python 一个失败,C++ 一个通过。很奇怪

Python 返回类型None,这是典型的 Python 指定没有任何内容的方式。例如,您可以编写(非常 Pythonic):

if cv2.findNonZero(np.zeros([3,3], np.uint8)) is None:
    print('I didnt find any zeros')

C++ 这样的语言没有具有相同含义的不同类型。它确实有一个Null,但它本质上只是一个0。这意味着如果函数返回一个Null,它可能会被误认为是索引0 处的元素。 Python 中的None 是它自己的,根本不代表0

【讨论】:

  • 我使用条件语句让程序只有在返回值不是 none 的情况下才能继续,并且它有效。谢谢。
猜你喜欢
  • 2021-03-03
  • 2015-07-30
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2016-06-06
  • 2019-10-28
  • 1970-01-01
  • 2021-06-14
相关资源
最近更新 更多