import cv2
import numpy as np
# 初始化两个端点的坐标
pt1 = np.array([100, 100])
pt2 = np.array([300, 300])
# 计算线段的长度
def get_line_length(p1, p2):
return np.linalg.norm(p2 - p1)
# 计算点a和不动的端点pt2之间的线段,截取出与原线段相同长度的部分
def get_point_on_line(a, fixed_point, length):
# 计算a和固定端点的方向
direction = a - fixed_point
norm_direction = direction / np.linalg.norm(direction) # 归一化方向
# 计算截取线段的新端点c,保持长度不变
new_point = fixed_point + norm_direction * length
return new_point
# 鼠标点击事件
def mouse_callback(event, x, y, flags, param):
global p1, p2
if event == cv2.EVENT_LBUTTONDOWN:
a = np.array([x, y])
# 计算离点击点最近的端点
dist1 = np.linalg.norm(a - p1)
dist2 = np.linalg.norm(a - p2)
# 确定需要移动的端点
if dist1 < dist2:
# pt1 更近,移动 pt1
new_pt1 = get_point_on_line(a, p2, get_line_length(p1, p2))
pt1 = new_pt1 # 更新 pt1
else:
# pt2 更近,移动 pt2
new_pt2 = get_point_on_line(a, p1, get_line_length(p1, p2))
pt2 = new_pt2 # 更新 pt2
# 可视化结果
img = np.ones((500, 500, 3), dtype=np.uint8) * 255 # 白色背景
# 画更新后的线段
cv2.line(img, tuple(p1.astype(int)), tuple(p2.astype(int)), (0, 0, 255), 2) # 画线段
# 画出鼠标点击点
cv2.circle(img, tuple(a.astype(int)), 5, (0, 255, 0), -1) # 鼠标点击点
# 显示图像
cv2.imshow('Line Movement', img)
# 创建一个空白图像
img = np.ones((500, 500, 3), dtype=np.uint8) * 255 # 白色背景
# 初始绘制线段
cv2.line(img, tuple(pt1.astype(int)), tuple(pt2.astype(int)), (0, 0, 255), 2)
cv2.imshow('Line Movement', img)
cv2.setMouseCallback('Line Movement', mouse_callback)
cv2.waitKey(0)
cv2.destroyAllWindows()
选择一个点,旋转线段,不改变线段角度
最新推荐文章于 2025-12-19 16:26:43 发布
6115

被折叠的 条评论
为什么被折叠?



