【问题标题】:'builtin_function_or_method' object is not iterable in object detection using openCV\'builtin_function_or_method\' 对象在使用 openCV 的对象检测中不可迭代
【发布时间】:2022-12-05 20:37:03
【问题描述】:

我正在尝试使用 OpenCV 处理我的对象检测项目,它输出和错误我无法理解这是我的代码:

`

import cv2

img = cv2.imread('lena.png')
ClassNames = []
ClassFile = 'coco.names'`

with open(ClassFile, 'rt') as f:
    ClassNames = f.read().rstrip('\n').split('\n')

configpath = 'ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt'
weightspath = 'frozen_inference_graph.pb'

net = cv2.dnn_DetectionModel(weightspath, configpath)

net.setInputSize(320, 320)
net.setInputScale(1.0/ 127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)

classIds, confs, bbox = net.detect(img, confThreshold= 0.5)
print(classIds, bbox)

for classId, confidence, box in zip(classIds.flatten(), confs.flatten, bbox):
    cv2.rectangle(img, box, color=(0, 255, 0), thickness= 3)


cv2.imshow('Lena image',img)

`

使用上面的代码是错误的:

TypeError Traceback(最后一次调用) ~\AppData\Local\Temp\ipykernel_2776\4286890995.py 中 ----> 1 for classId, confidence, box in zip(classIds.flatten(), confs.flatten, bbox): 2 cv2.rectangle(img, box, color=(0, 255, 0), 厚度= 3)

TypeError: 'builtin_function_or_method' 对象不可迭代

【问题讨论】:

  • confs.flatten——你错过了()

标签: python opencv object-detection


【解决方案1】:

在您的代码中,您试图迭代对 confs 对象调用 flatten 方法的结果。 flatten 方法是一种内置方法,可用于 Python 中的某些对象,例如列表和 NumPy 数组。

错误消息表明 Python 无法迭代 confs.flatten 对象,因为它不是列表或其他可迭代类型。这是因为您没有将 flatten 方法作为方法调用——您只是通过名称引用它。换句话说,不是写 confs.flatten(),它会调用 flatten 方法并返回扁平列表,而是写 confs.flatten,它只是对方法本身的引用。

要修复此错误,您只需在confs.flatten 之后添加括号,例如:confs.flatten()。这将调用 flatten 方法并返回展平列表,然后您可以在循环中对其进行迭代。

for classId, confidence, box in zip(classIds.flatten(), confs.flatten(), bbox):
    cv2.rectangle(img, box, color=(0, 255, 0), thickness= 3)

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多