在OpenCV中绘制有角度的矩形

2024-04-30 01:16:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用OpenCV和python来完成一个涉及身体跟踪的项目,我使用HSV值来找到肤色,然后在它周围画一个框。

不过,尽管我可以找到被跟踪的对象并在其周围绘制一个框,但矩形始终是垂直的,而且我想知道这些矩形是否仍然存在角度,以便它们更好地显示检测到的对象,有点像minEnclosingCircle函数,但使用矩形

这些照片也许能更好地解释我在寻找什么。我得到的盒子都是绿色的,我要找的东西都是黄色的。如您所见,遮罩显示和角矩形也会更好地包围选定的区域。我还包括了原始图像。

我的代码是:

    import numpy as np
    import cv2

    # Input image
    image = cv2.imread('TestIn.png')

    # Converts to grey for better reulsts
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Converts to HSV
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # HSV values
    lower_skin = np.array([5,36,53])
    upper_skin = np.array([19,120,125])

    mask = cv2.inRange(hsv, lower_skin, upper_skin)

    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)

    # Finds contours
    im2, cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Draws contours
    for c in cnts:
        if cv2.contourArea(c) < 3000:
            continue

        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(image, (x,y), (x+w,y+h), (0, 255, 0), 2)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

输入图像:

Input Image

输出图像(绿色输出框,黄色所需框):

output image. output boxes in green, desired boxes in yellow


Tags: to对象图像imageimportfornpmask
1条回答
网友
1楼 · 发布于 2024-04-30 01:16:29

您需要使用^{}然后^{}获得一系列点,这些点以其他OpenCV绘图函数(如^{}^{})可以使用的格式表示多边形。


基于OpenCV文档中的example,我在代码中添加了一些语句,以获得所需的结果:

import numpy as np
import cv2

# Input image
image = cv2.imread('oaHUs.jpg')

# Converts to grey for better reulsts
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Converts to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# HSV values
lower_skin = np.array([5,36,53])
upper_skin = np.array([19,120,125])

mask = cv2.inRange(hsv, lower_skin, upper_skin)

mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)

# Finds contours
im2, cnts, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Draws contours
for c in cnts:
    if cv2.contourArea(c) < 3000:
        continue

    (x, y, w, h) = cv2.boundingRect(c)
    cv2.rectangle(image, (x,y), (x+w,y+h), (0, 255, 0), 2)

    ## BEGIN - draw rotated rectangle
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(image,[box],0,(0,191,255),2)
    ## END - draw rotated rectangle

cv2.imwrite('out.png', image)

输出:

相关问题 更多 >