在OpenCV中绘制有角度的矩形

时间:2016-04-28 17:10:36

标签: python opencv tracking

我正在使用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

1 个答案:

答案 0 :(得分:7)

您需要使用cv2.minAreaRect(...)然后cv2.boxPoints(...)来获取表示多边形的点序列,其格式可以由其他OpenCV绘图函数使用,例如cv2.drawContours(...)或{ {3}}

基于OpenCV文档中的cv2.polylines(...),我在代码中添加了一些语句来实现所需的结果:

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)

输出:

example