【问题标题】:How to draw rectangles around every blue object?如何在每个蓝色对象周围绘制矩形?
【发布时间】:2022-01-04 21:54:43
【问题描述】:

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

这是我当前的代码

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

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

【问题讨论】:

  • 在每个轮廓上添加一个 for 循环。然后为每个轮廓获取该轮廓及其边界框的轮廓区域。
  • @fmw42 你介意给我那个代码的细节吗?我认为问题在于“最大值”在哪里,但我不知道用什么来代替它,因为我对机器学习还很陌生。这是我尝试过的,但得到的结果与之前相同 for object in bluecnts: item_area = max(bluecnts, key=cv2.contourArea) (xg,yg,wg,hg) = cv2.boundingRect(item_area) cv2.rectangle(frame,(xg,yg),(xg+wg, yg+hg),(0,255,0),2)

标签: python opencv machine-learning deep-learning


【解决方案1】:

在您的 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)

(未测试)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2021-12-17
    相关资源
    最近更新 更多