如何在打开的 cv python 中围绕彩色对象绘制矩形?

How can I draw a rectangle around a colored object in open cv python?

如何在原始凸轮(帧 window 中)出现的白色对象(掩码 window 中)上绘制一个矩形 see image

我的代码:

    import cv2
    import numpy as np
    cap = cv2.VideoCapture(0)

    while(1):
        # Take each frame
        _, frame = cap.read()
        # Convert BGR to HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # define range of red color in HSV
        lower_blue = np.array([0,89,190])
        upper_blue = np.array([180,255,255])
        # Threshold the HSV image to get only red colors
        mask = cv2.inRange(hsv, lower_blue, upper_blue)
        # Bitwise-AND mask and original image
        res = cv2.bitwise_and(frame,frame, mask= mask)
        cv2.imshow('frame',frame)
        cv2.imshow('mask',mask)
        cv2.imshow('res',res)
        k = cv2.waitKey(5) & 0xFF
        if k == 27:
            break
    cv2.destroyAllWindows()

抱歉我的英语不好,我正在努力提高它。

使用 cv2.findContours 在蒙版图像上找到对象,然后 cv2.drawContours 显示它。

Doc here

正如 Tiphel 所说,您可以使用 cv2.findContours 和 cv2.drawContours。或者,在获得轮廓后,您也可以使用 cv2.boundingRect() 函数绘制一个框。这 returns 4 个参数,比如 x、y、w 和 h。 x,y代表一个点,w,h分别代表矩形的宽高。然后您可以使用 cv2.rectangle 绘制矩形。您也可以类似地拟合其他形状,例如椭圆、圆形等。

i, contours, heirarchy = cv2.findContours(a_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cont_sorted = sorted(cnts2, key=cv2.contourArea, reverse=True)[:5]

x,y,w,h = cv2.boundingRect(cont_sorted[0])

cv2.rectangle(a,(x,y),(x+w,y+h),(0,0,255),5)

这里,a_thresh是对输入图像进行阈值处理后的二值图像。在 cv2.rectange() 函数中,第一个参数对应于要绘制的图像,第四个参数指定颜色,第五个参数指定用于绘制矩形的线的粗细。

此外,我使用 'sorted' 获得前 5 个轮廓的大小,理想情况下我感兴趣的对象是面积最大的那个。

您可以在线找到这些文件的文档。我建议您阅读上面使用的所有函数的文档,以便在您的应用程序中适当地使用它!