yolov8-line-cross/line_selector.py

67 lines
2.3 KiB
Python

import tkinter as tk
class LineSelector:
def __init__(self, image_path):
self.image_path = image_path
self.start_x, self.start_y = None, None
self.end_x, self.end_y = None, None
self.line_id = None
self.coordinates = None
self.success = False
def on_mouse_press(self, event):
self.start_x, self.start_y = event.x, event.y
def on_mouse_drag(self, event):
if self.line_id:
self.canvas.delete(self.line_id)
self.end_x, self.end_y = event.x, event.y
self.line_id = self.canvas.create_line(self.start_x, self.start_y, self.end_x, self.end_y, fill="white")
def on_mouse_release(self, event):
self.end_x, self.end_y = event.x, event.y
self.update_coordinates_label()
def update_coordinates_label(self):
coordinates = f"起点坐标: ({self.start_x}, {self.start_y}),终点坐标: ({self.end_x}, {self.end_y})"
self.coordinates_label.config(text=coordinates)
def on_confirm_button_click(self):
self.success = True
self.root.destroy()
self.root.quit()
def draw_image_and_get_coordinates(self):
self.root = tk.Tk()
self.root.title("绘制检测线")
self.canvas = tk.Canvas(self.root, width=1920, height=1080)
self.canvas.pack()
image = tk.PhotoImage(file=self.image_path)
self.canvas.create_image(0, 0, anchor=tk.NW, image=image)
self.coordinates_label = tk.Label(self.root, text="", fg="red")
self.coordinates_label.pack()
confirm_button = tk.Button(self.root, text="确认", command=self.on_confirm_button_click)
confirm_button.pack()
self.canvas.bind("<ButtonPress-1>", self.on_mouse_press)
self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_mouse_release)
self.root.mainloop()
def get_coordinates(self):
self.coordinates = [self.start_x, self.start_y, self.end_x, self.end_y]
return self.coordinates
def main():
image_path = "background.png"
selector = LineSelector(image_path)
selector.draw_image_and_get_coordinates()
coordinates = selector.get_coordinates()
print("坐标:", coordinates)
if __name__ == "__main__":
main()