特征标注
导入必要的库
import tkinter as tk
: 导入Tkinter库,并将其重命名为tk。
from tkinter import filedialog
: 从Tkinter中导入文件对话框功能。
import cv2
: 导入OpenCV库。
from PIL import Image, ImageTk
: 从PIL库导入Image和ImageTk模块,用于处理图像。
from tkinter import messagebox
: 从Tkinter中导入消息框功能,用于显示消息提示框。
import dlib
:导入dlib库,这个库用于人脸检测和关键点标注。
import tkinter as tk
from tkinter import filedialog
import cv2
from PIL import Image, ImageTk
from tkinter import messagebox
import dlib
创建窗口
创建了一个Tkinter窗口实例win,设置窗口标题为"特征标注",大小为800x650像素。
win = tk.Tk()
win.title("特征标注")
win.geometry("800x650")
显示原始图片和标注后的图片
创建了两个空的标签控件
image_label_original
和image_label_landmarks
,用于显示原始图像和带有标注的图像。
mage_label_original = tk.Label(win)
image_label_landmarks = tk.Label(win)
存储用户选择的图片路径
初始化一个变量
selected_image_path
,用于存储用户选择的图片路径。
selected_image_path = None
字体样式和大小
定义了字体样式
my_font
,使用Times New Roman
字体,大小为20。
my_font = ("Times New Roman", 20)
定义了select_image函数
global selected_image_path
: 声明selected_image_path为全局变量,以便在函数内部修改其值。
selected_image_path = filedialog.askopenfilename()
:
使用文件对话框让用户选择一个图像文件,并将选择的文件路径存储在selected_image_path变量中。
if selected_image_path:
: 检查是否成功选择了图像文件。
img = cv2.imread(selected_image_path)
:
使用OpenCV的imread()函数读取选择的图像文件,并将其存储在img变量中。
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
:
将BGR格式的图像转换为RGB格式,便于后续处理。
img_pil = Image.fromarray(img_rgb)
: 将RGB格式的图像数据转换为PIL图像对象。
img_pil = img_pil.resize((300, 300), Image.Resampling.LANCZOS)
:
调整图像大小为300x300像素,使用LANCZOS插值方法保持图像质量。
img_tk = ImageTk.PhotoImage(image=img_pil)
:
将PIL图像对象转换为Tkinter图像对象,用于在GUI中显示。
image_label_original.config(image=img_tk)
: 在原始图像标签控件上配置显示图像。
image_label_original.image = img_tk
: 更新原始图像标签的图像数据,确保图像正确显示在GUI中。
def select_image():
global selected_image_path
selected_image_path = filedialog.askopenfilename()
if selected_image_path:
img = cv2.imread(selected_image_path)
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_rgb)
img_pil = img_pil.resize((300, 300), Image.Resampling.LANCZOS)
img_tk = ImageTk.PhotoImage(image=img_pil)
image_label_original.config(image=img_tk)
image_label_original.image = img_tk
定义了annotate_landmarks()函数
if selected_image_pat