gpt4 book ai didi

python - 在 OpenCV 中绘制有角度的矩形

转载 作者:太空狗 更新时间:2023-10-29 22:29:25 24 4
gpt4 key购买 nike

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

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

图像可能更好地解释了我正在寻找的东西。我得到的盒子是绿色的,而我要找的东西是用黄色画的。如您所见, mask 显示和成角度的矩形也可以更好地包含所选区域。我还包含了原始图像。

我的代码是:

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

最佳答案

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


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

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)

输出:

关于python - 在 OpenCV 中绘制有角度的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com