如何在每个蓝色对象周围绘制矩形?

How to draw rectangles around every blue object?

我找到了很多关于如何在框架中最大的蓝色对象周围绘制矩形的信息,但我需要在所有蓝色对象周围绘制矩形。

这是我当前的代码

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

这就是它目前所做的,围绕最大的蓝色对象绘制一个矩形,但我需要它围绕每个对象。

在您的 Python/OpenCV 代码中,尝试替换

   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)

   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)

(未测试)