minAreaRect

import cv2

img = cv2.imread("./test2.jpg")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
xx,contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)  #将所有轮廓勾画出来

for i in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[i]) #包覆轮廓的最小正矩形
    print(x,y,w,h)
    cv2.rectangle(img, (x, y), (x + w , y + h ), (0, 255, 0), 2) #实地的画出这个矩形框
    theRect = cv2.minAreaRect(contours[i])  #包覆轮廓的最小斜矩形
    print(theRect)
    center = theRect[0]
    center=(int(center[0]),int(center[1]))
    print(center)
    cv2.circle(img, center, 1, (0, 255, 0), 4)

cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

minAreaRect_第1张图片

 


minAreaRect_第2张图片

 


 函数 cv2.minAreaRect() 返回如下:
((最小外接矩形的中心x,最小外接矩形的中心y),(宽度width,高度height),旋转角度angle)

minAreaRect_第3张图片

 

你可能感兴趣的:(opencv,opencv,python)