def transform_by4(self, img, points):
points = sorted(points, key=lambda x: x[1])
if len(points) == 4:
top = sorted(points[:2], key=lambda x: x[0])
bottom = sorted(points[2:], key=lambda x: x[0], reverse=True)
points = np.array(top + bottom, dtype='float32')
else:
y_min, y_max = points[0][1], points[-1][1]
points = sorted(points, key=lambda x: x[0])
x_min, x_max = points[0][0], points[-1][0]
points = np.array([np.array([x_min, y_min]),
np.array([x_max, y_min]),
np.array([x_max, y_max]),
np.array([x_min, y_max])],
np.float32)
width = max(np.sqrt(((points[0][0] - points[2][0]) ** 2) * 2),
np.sqrt(((points[1][0] - points[3][0]) ** 2) * 2))
height = max(np.sqrt(((points[0][1] - points[2][1]) ** 2) * 2),
np.sqrt(((points[1][1] - points[3][1]) ** 2) * 2))
dst = np.array([np.array([0, 0]),
np.array([width - 1, 0]),
np.array([width - 1, height - 1]),
np.array([0, height - 1]),
], np.float32)
# ??????????????????????????
trans = cv2.getPerspectiveTransform(points, dst)
return cv2.warpPerspective(img, trans, (int(width), int(height)))
评论列表
文章目录