import os
import cv2
# 定义输入和输出路径
images_dir = r'C:\Users\DELL\Desktop\dhd_campus\images' # 输入图片路径
labels_dir = r'C:\Users\DELL\Desktop\dhd_campus\txt' # 输入TXT标签文件路径
output_dir = r'C:\Users\DELL\Desktop\outputs' # 输出图片路径
# 如果输出目录不存在,创建它
os.makedirs(output_dir, exist_ok=True)
# 获取所有TXT标签文件
label_files = [f for f in os.listdir(labels_dir) if f.endswith('.txt')]
# 处理每个TXT文件
for label_file in label_files:
label_path = os.path.join(labels_dir, label_file)
image_filename = os.path.splitext(label_file)[0] + '.jpg'
image_path = os.path.join(images_dir, image_filename)
# 检查图像文件是否存在
if not os.path.exists(image_path):
print(f"警告: 找不到图像文件 {image_filename},跳过该文件。")
continue
# 读取图像
image = cv2.imread(image_path)
height, width, _ = image.shape
# 读取标签文件
with open(label_path, 'r') as file:
for line in file:
# 解析每一行,格式: class_id x_center y_center width height
parts = line.strip().split()
if len(parts) != 5:
continue
class_id, x_center, y_center, box_width, box_height = map(float, parts)
# 计算边界框的坐标
x_center *= width
y_center *= height
box_width *= width
box_height *= height
xmin = int(x_center - box_width / 2)
ymin = int(y_center - box_height / 2)
xmax = int(x_center + box_width / 2)
ymax = int(y_center + box_height / 2)
# 绘制矩形框
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), (0, 255, 0), 2)
# 保存绘制有检测框的图片
output_image_path = os.path.join(output_dir, image_filename)
cv2.imwrite(output_image_path, image)
print(f"处理完成并保存: {output_image_path}")
print("所有文件已处理完成。")