点击图片获取图片中的坐标位置代码

点击图片获取图片中的坐标位置代码

import tkinter as tk
from PIL import Image, ImageTk



class ImageApp:
    def __init__(self, root, image_path,filename="result.csv"):
        self.root = root
        self.root.title("Image Viewer")
        self.file = open(filename, 'w', encoding='utf-8')
        # Load the image
        self.image = Image.open(image_path)
        self.tk_image = ImageTk.PhotoImage(self.image)

        # Create canvas for displaying image
        self.canvas = tk.Canvas(root, width=self.image.width, height=self.image.height)
        self.canvas.pack()

        # Display the image on the canvas
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.tk_image)

        # Bind mouse click event to canvas
        self.canvas.bind("<Button-1>", self.on_canvas_click)

        # Initialize variables
        self.coordinate_groups = []
        self.group_counter = 1

        # Create a button to save coordinates
        self.save_button = tk.Button(root, text="Save Coordinates", command=self.save_coordinates)
        self.save_button.pack()


    def on_canvas_click(self, event):
        # Output the clicked coordinates
        print(f"Clicked at: ({event.x}, {event.y})")

        # Store coordinates
        self.coordinate_groups.append((event.x, event.y))

    def save_coordinates(self):
        if not self.coordinate_groups:
            print("No coordinates to save.")
            return
        # Save all coordinates to a CSV file with a sequential number
        self.file.write(str(self.group_counter) +","+ str(self.coordinate_groups)+"\n")
        self.coordinate_groups.clear()
        self.group_counter = self.group_counter + 1


if __name__ == "__main__":
    # Replace 'path/to/your/image.jpg' with the actual path to your image file
    image_path = r'D:\traffic_model\天津.png'

    # Create the main window
    root = tk.Tk()
    save_file="天津.csv"
    # Create an instance of the ImageApp class
    app = ImageApp(root, image_path,save_file)

    # Start the main loop
    root.mainloop()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值