我正在使用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()
输入图片:
输出图像(输出框为绿色,所需方框为黄色):
解决方法:
您需要使用cv2.minAreaRect(...)
然后cv2.boxPoints(...)
来获取表示多边形的点序列,其格式可以由其他OpenCV绘图函数(例如cv2.drawContours(...)
或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)
输出: