import cv2
import numpy as np
def draw_distance_lines(image, small_rect, big_rect):
x1, y1, x2, y2 = small_rect
bx1, by1, bx2, by2 = big_rect
# 小矩形
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 2)
small_centers = [(x1, (y1 + y2) // 2), (x2, (y1 + y2) // 2),
((x1 + x2) // 2, y1), ((x1 + x2) // 2, y2)]
for center in small_centers:
cv2.circle(image, center, 5, (0, 0, 255), -1)
# 大矩形
cv2.rectangle(image, (bx1, by1), (bx2, by2), (0, 255, 0), 2)
big_centers = [(bx1, (by1 + by2) // 2), (bx2, (by1 + by2) // 2),
((bx1 + bx2) // 2, by1), ((bx1 + bx2) // 2, by2)]
for center in big_centers:
cv2.circle(image, center, 5, (0, 255, 0), -1)
# 连接中心点并计算线条长度
for small_center, big_center in zip(small_centers, big_centers):
line_length = int(np.sqrt((big_center[0] - small_center[0])**2 + (big_center[1] - small_center[1])**2))
cv2.line(image, small_center, big_center, (255, 255, 255), 2)
cv2.putText(image, f"{line_length}", ((small_center[0] + big_center[0]) // 2, (small_center[1] + big_center[1]) // 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
# 定义矩形坐标列表
small_rectangles = [[201, 266, 217, 282]]
big_rectangles = [[59, 214, 255, 335]]
# 创建一个空白图像
image = np.zeros((500, 500, 3), dtype=np.uint8)
for i in range(len(small_rectangles)):
small_rect = small_rectangles[i]
big_rect = big_rectangles[i]
draw_distance_lines(image, small_rect, big_rect)
# 显示图像
cv2.imshow("Rectangles with Distances", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
如何改为 连接最短的距离