admin 管理员组

文章数量: 887016

insp4

import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog

# 初始化一些变量
rectangles = []
drawing = False  # 是否正在绘制矩形框
ix, iy = -1, -1  # 起始坐标
fx, fy = -1, -1  # 结束坐标

# 创建一个窗口
cv2.namedWindow('Image')

# 创建一个Tkinter窗口
root = tk.Tk()
root.withdraw()  # 隐藏主窗口

# 打开文件对话框来选择图片文件
file_path = filedialog.askopenfilename()
if file_path:
    image = cv2.imread(file_path)

    # 定义鼠标回调函数
    def draw_rectangle(event, x, y, flags, param):
        global ix, iy, fx, fy, drawing

        if event == cv2.EVENT_LBUTTONDOWN:
            drawing = True
            ix, iy = x, y
        elif event == cv2.EVENT_MOUSEMOVE:
            if drawing:
                fx, fy = x, y
        elif event == cv2.EVENT_LBUTTONUP:
            drawing = False
            fx, fy = x, y
            rectangles.append(((ix, iy), (fx, fy)))

    # 设置鼠标回调函数
    cv2.setMouseCallback('Image', draw_rectangle)

    # 创建一个文本框来显示坐标
    coordinate_text = tk.Text(root, height=10, width=30)
    coordinate_text.pack()

    while True:
        img_copy = image.copy()

        # 绘制矩形框
        for rect in rectangles:
            cv2.rectangle(img_copy, rect[0], rect[1], (0, 255, 0), 2)

        cv2.imshow('Image', img_copy)

        key = cv2.waitKey(1) & 0xFF

        # 更新坐标文本框
        coordinate_text.delete(1.0, tk.END)
        for i, rect in enumerate(rectangles):
            coordinate_text.insert(tk.END, f"Rectangle {i + 1}: {rect}\n")

        # 保存图片和坐标文本文件
        if key == ord('s'):
            output_image = image.copy()
            for rect in rectangles:
                cv2.rectangle(output_image, rect[0], rect[1], (0, 255, 0), 2)
            output_path = filedialog.asksaveasfilename(defaultextension=".jpg")
            if output_path:
                cv2.imwrite(output_path, output_image)
                print('图片已保存为', output_path)

                # 保存坐标文本文件
                txt_path = output_path[:-4] + ".txt"
                with open(txt_path, "w") as txt_file:
                    for i, rect in enumerate(rectangles):
                        txt_file.write(f"Rectangle {i + 1}: {rect}\n")

                print('坐标已保存为', txt_path)
                rectangles = []  # 清空矩形框列表
        # 退出程序
        elif key == 27:
            break

    cv2.destroyAllWindows()

本文标签: insp4