【发布时间】:2019-12-26 16:42:51
【问题描述】:
我正在从事一个关于鸟类的项目,该项目需要我检测杂草。我在下面编写了程序code2,它可以工作。但是,我需要在图像上显示最大的矩形。我尝试使用 code1,但是,当我在 code2 中使用这段代码时,它会给出错误:
“第 21 行 for (x, y, w, h) in最大:TypeError: cannot unpack non-iterable numpy.int32 object”。
我不知道如何解决它。请帮助我,谢谢!
代码1
areas = [w*h for x,y,w,h in birds]
a_biggest = np.argmax(areas)
biggest = birds[a_biggest]
代码2
import cv2
import numpy as np
bird_cascade = cv2.CascadeClassifier("birdcascadeHAAR.xml")
gray = cv2.imread("trialpic30.jpg", 0)
birds, rejectLevels, levelWeights = bird_cascade.detectMultiScale3(
gray,
scaleFactor=1.185,
minNeighbors=20,
outputRejectLevels = True
)
print(rejectLevels)
print(levelWeights)
for (x,y,w,h) in birds:
cv2.rectangle(gray, (x,y), (x+w, y+h), (255,0,0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(gray, str(levelWeights), (x+w-115, y+h-115), font, 0.5, (255, 0, 0), 1, cv2.LINE_AA)
cv2.imshow("img", gray)
cv2.waitKey()
【问题讨论】:
-
np.argmax() 返回数组中最大值的索引。我想你可能想要 np.amax()。见docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html 和docs.scipy.org/doc/numpy/reference/generated/…
-
我阅读了文档,看起来 np.amax 返回数组中的最大值,但是,我需要最大的总数组值,本质上是给我最大的矩形。不过谢谢!
-
使用 print 检查您在
biggest中的内容。如果您有一个列表中的元素,那么您可能需要在没有for-loop 的情况下解压缩它x, y, w, h = biggest。或将其转换为包含一个元素[biggest]的列表,然后与for-loop 一起使用 -for x, y, w, h in [biggest] -
当我打印最大时,程序正确地将较大矩形的数组输出为 [922 551 322 322]
标签: python numpy opencv computer-vision artificial-intelligence