在 OpenCV 中绘制带角度的矩形

Drawing angled rectangles in OpenCV

我正在使用 OpenCV 和 python 开展一个涉及 body 跟踪的项目,我正在使用 HSV 值查找肤色然后在其周围画一个框。

然而,虽然我可以找到跟踪的 object 并在其周围画一个框,但矩形始终是垂直的,我想知道矩形是否有角度,以便它们更好地显示检测到的 object,有点像 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()

输入图像:

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

您需要使用 cv2.minAreaRect(...) and then cv2.boxPoints(...) to obtain a sequence of points representing the polygon in a format that can be used by other OpenCV drawing functions, such as cv2.drawContours(...) or cv2.polylines(...).


基于 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)

输出: