import numpy as np
import cv2
import matplotlib.pyplot as plt
def order_points(pts):
# sort the points based on their x-coordinates
xSorted = pts[np.argsort(pts[:, 0]), :]
# grab the left-most and right-most points from the sorted
# x-roodinate points
leftMost = xSorted[:2, :]
rightMost = xSorted[2:, :]
if leftMost[0,1]!=leftMost[1,1]:
leftMost=leftMost[np.argsort(leftMost[:,1]),:]
else:
leftMost=leftMost[np.argsort(leftMost[:,0])[::-1],:]
(tl, bl) = leftMost
if rightMost[0,1]!=rightMost[1,1]:
rightMost=rightMost[np.argsort(rightMost[:,1]),:]
else:
rightMost=rightMost[np.argsort(rightMost[:,0])[::-1],:]
(tr,br)=rightMost
# return the coordinates in top-left, top-right,
# bottom-right, and bottom-left order
return np.array([tl, tr, br, bl])
img = cv2.imread('/Users/nickccnie/Desktop/images.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]
contours = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
for cnt in contours:
min_rect = cv2.minAreaRect(cnt) # ((x_center, y_center), (w, h), angle)
min_bbox = cv2.boxPoints(min_rect).astype(np.int32)
# 顶点排序:右下 》左下 》左上 》右上
min_bbox = order_points(min_bbox)
cv2.polylines(img, [min_bbox], True, (255, 0, 0), 5)
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
【python】最小外接矩形顶点排序
最新推荐文章于 2024-01-25 19:04:46 发布