如何匹配影像与坐标,准备头影测量Landmark定位模型训练数据集?
头影测量关键点定位:图像与坐标匹配解决方案
image_dataset_from_directory更适合基于目录分类的任务,无法直接关联你自定义的坐标标签。要构建适配model.fit的训练数据集,建议通过自定义数据加载逻辑实现图像与坐标的匹配,具体步骤如下:
1. 准备标注文件
把你提供的图像路径与坐标数据保存为CSV文件(比如命名为landmarks.csv),格式如下:
filename,X1,Y1 /Images_data/binary0006.png,89,80 /Images_data/binary0008.png,37,70 /Images_data/binary0007.png,50,76 /Images_data/binary0003.png,55,92 /Images_data/binary0005.png,91,64 /Images_data/binary0004.png,100,76
2. 自定义数据加载函数
通过tf.data.Dataset构建数据集,实现图像读取、预处理与坐标匹配,同时处理图像resize后的坐标缩放问题:
import tensorflow as tf import pandas as pd # 定义图像尺寸和批次大小 img_height = 256 img_width = 256 batch_size = 2 def load_image_and_coords(row): # 读取并预处理图像 img = tf.io.read_file(row['filename']) img = tf.image.decode_png(img, channels=1) # 适配二值图的单通道格式 original_shape = tf.shape(img)[:2] # 图像resize与归一化 img = tf.image.resize(img, (img_height, img_width)) img = tf.cast(img, tf.float32) / 255.0 # 按比例缩放坐标,匹配resize后的图像尺寸 x_scaled = row['X1'] * (img_width / original_shape[1]) y_scaled = row['Y1'] * (img_height / original_shape[0]) coords = tf.convert_to_tensor([x_scaled, y_scaled], dtype=tf.float32) return img, coords # 加载CSV标注 df = pd.read_csv('landmarks.csv') # 构建数据集 ds = tf.data.Dataset.from_tensor_slices(dict(df)) ds = ds.map(load_image_and_coords, num_parallel_calls=tf.data.AUTOTUNE)
3. 划分训练/验证集并配置
完成数据集的打乱、划分与批量处理,直接用于model.fit:
# 打乱数据集 ds = ds.shuffle(buffer_size=len(df), seed=123) # 划分训练集(80%)与验证集(20%) val_size = int(0.2 * len(df)) train_ds = ds.skip(val_size).batch(batch_size).prefetch(tf.data.AUTOTUNE) val_ds = ds.take(val_size).batch(batch_size).prefetch(tf.data.AUTOTUNE)
关键说明
- 坐标缩放是核心:如果对图像进行了resize操作,必须按原始图像与目标图像的尺寸比例缩放坐标,否则模型训练出的关键点位置会偏离实际。
- 该方案适配回归任务:你的关键点定位属于连续值回归任务,输出为坐标值,后续模型的损失函数可选用
MSE(均方误差)。
内容的提问来源于stack exchange,提问作者whatisthisthisisabook
相关产品推荐
相关产品推荐

