I have found lots of information about how to draw rectangles around the biggest blue object in the frame but I need to draw rectangles around all of the blue objects.
This is my current code
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
# Convert BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# define range of blue color in HSV
lower_blue = np.array([100,50,50])
upper_blue = np.array([130,255,255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange (hsv, lower_blue, upper_blue)
bluecnts = cv2.findContours(mask.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
if len(bluecnts)>0:
blue_area = max(bluecnts, key=cv2.contourArea)
print(blue_area)
(xg,yg,wg,hg) = cv2.boundingRect(blue_area)
cv2.rectangle(frame,(xg,yg),(xg wg, yg hg),(0,255,0),2)
result = cv2.bitwise_and(frame, frame, mask=mask)
cv2.imshow('frame',frame)
cv2.imshow('mask',mask)
cv2.imshow('blue', result)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
And this is what it currently does, draw one rectangle around the biggest blue object but I need it around each one.
CodePudding user response:
In your Python/OpenCV code, try replacing
if len(bluecnts)>0:
blue_area = max(bluecnts, key=cv2.contourArea)
print(blue_area)
(xg,yg,wg,hg) = cv2.boundingRect(blue_area)
cv2.rectangle(frame,(xg,yg),(xg wg, yg hg),(0,255,0),2)
with
if len(bluecnts)>0:
for cnt in bluecnts:
area = cv2.contourArea(cnt)
print(area)
(xg,yg,wg,hg) = cv2.boundingRect(cnt)
cv2.rectangle(frame,(xg,yg),(xg wg, yg hg),(0,255,0),2)
(Untested)