简体   繁体   中英

Finding the Biggest Rectangle with OpenCV detectMultiScale

I am working on a project on birds that requires me to detect weeds. I have written the program, code2, below and it works. I however, need the largest rectangle to be shown on the image. I try to to this with code1, however, when I use this piece of code in code2, it gives the error:

"line 21 for (x, y, w, h) in biggest: TypeError: cannot unpack non-iterable numpy.int32 object".

I don't know how to fix it. Please assist me, thank you!

code1

areas = [w*h for x,y,w,h in birds]
a_biggest = np.argmax(areas)
biggest = birds[a_biggest]

code2

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()

Using

biggest = birds[a_biggest]

biggest = [922 551 322 322]

you get one element from list and you don't have list any more so you should unpack it directly

x, y, w, h = biggest

x, y, w, h = [922 551 322 322]

Eventually you would have to create list with this single element [biggest] to use with loop

for x, y, w, h in [biggest]:

for x, y, w, h in [ [922 551 322 322] ]:

When you use single element with for -loop

for x, y, w, h in biggest:

then you have something like

for x, y, w, h in [922 551 322 322]:

so it gets first element from list [922 551 322 322] (which is 922 ) and it tries to assing

x, y, w, h = 922

and it makes problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM