first commit
This commit is contained in:
51
ailai_pc/caculate_xiangsu.py
Normal file
51
ailai_pc/caculate_xiangsu.py
Normal file
@ -0,0 +1,51 @@
|
||||
import cv2
|
||||
|
||||
# 全局变量
|
||||
refPt = []
|
||||
drawing = False
|
||||
|
||||
|
||||
def draw_line(event, x, y, flags, param):
|
||||
global refPt, drawing, image
|
||||
|
||||
# 鼠标左键按下时,记录起始点坐标并开始绘制
|
||||
if event == cv2.EVENT_LBUTTONDOWN:
|
||||
refPt = [(x, y)]
|
||||
drawing = True
|
||||
|
||||
# 当鼠标移动且处于绘制状态时,更新图像以显示当前的线段
|
||||
elif event == cv2.EVENT_MOUSEMOVE and drawing:
|
||||
temp_image = image.copy()
|
||||
cv2.line(temp_image, refPt[0], (x, y), (0, 255, 0), 2)
|
||||
cv2.imshow("Image", temp_image)
|
||||
|
||||
# 鼠标左键释放时,记录终点坐标,结束绘制并计算线段长度
|
||||
elif event == cv2.EVENT_LBUTTONUP:
|
||||
refPt.append((x, y))
|
||||
drawing = False
|
||||
# 在图像上画线
|
||||
cv2.line(image, refPt[0], refPt[1], (0, 255, 0), 2)
|
||||
cv2.imshow("Image", image)
|
||||
|
||||
# 计算线段长度
|
||||
dx = refPt[1][0] - refPt[0][0]
|
||||
dy = refPt[1][1] - refPt[0][1]
|
||||
length = (dx ** 2 + dy ** 2) ** 0.5
|
||||
print(f"线段长度: {length:.2f} 像素")
|
||||
|
||||
|
||||
# 加载图像
|
||||
image_path = 'your_image_path_here.jpg' # 替换为你的图像路径
|
||||
image = cv2.imread(image_path)
|
||||
cv2.namedWindow("Image")
|
||||
cv2.setMouseCallback("Image", draw_line)
|
||||
|
||||
while True:
|
||||
cv2.imshow("Image", image)
|
||||
key = cv2.waitKey(1) & 0xFF
|
||||
|
||||
# 按下 'q' 键退出循环
|
||||
if key == ord('q'):
|
||||
break
|
||||
|
||||
cv2.destroyAllWindows()
|
||||
Reference in New Issue
Block a user