引言
- 想學習一下cv2.boxPoints(),該方法可以計算帶有旋轉的矩形框坐標,想知道返回四個點的具體順序
- 找了好久,就是沒有找到一個可以運行的例子,來驗證
- 自己畫了一個圖,可以簡單運行,方便看
cv2.boxPoints()
- boxPoints返回四個點順序:右下→左下→左上→右上
import cv2
import requests
import numpy as np
file = requests.get("https://files-cdn.cnblogs.com/files/shiwanghualuo/1.bmp")
img = cv2.imdecode(np.frombuffer(file.content, np.uint8), 1)
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# opencv2 返回兩個值:coutours,hierarchy
# opencv3 返回三個值:img, coutours, hierarchy
contours, hierarchy = cv2.findContours(imgray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0]) # 得到最小外接矩形的(中心(x,y), (寬,高), 旋轉角度)
print(rect)
box = cv2.boxPoints(rect) # 獲取最小外接矩形的4個頂點坐標(ps: cv2.boxPoints(rect) for OpenCV 3.x)
print(box) #
box = np.int0(box)
# 畫出來
cv2.drawContours(img, [box], 0, (0, 0, 255), 5)
# cv2.imwrite('contours.png', img)
plt.imshow(img)
plt.show()
# out
# rect: ((144.0, 154.0), (150.0, 170.0), -90.0)
# box:
# [[229. 229.]
# [ 59. 229.]
# [ 59. 79.]
# [229. 79.]]
效果圖:
