(六)txt格式对应图片的真值框,在图片中展示

import cv2
import os

# 图片文件夹路径
image_folder = r"D:\PycharmProjects\yolov5-master\enhance_images\low_images_demo"

# 标注文件夹路径
annotation_folder = r"D:\PycharmProjects\yolov5-master\enhance_images\labels"

# 保存文件夹路径
output_folder = r"D:\PycharmProjects\yolov5-master\signtabel"

# 创建保存文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)

# 类别名称到数字的映射字典
class_map = {
"0": "car",
"1": "Bus",
"2": "Person",
"3": "Bike",
"4": "Trunk",
"5": "Motor",
"6": "Train",
"7": "Rider",
"8": "Sign",
"9": "Ligt",
# 其他类别依此类推
}

# 获取图片文件夹中所有图片文件的路径
image_files = os.listdir(image_folder)

# 遍历每张图片
for image_file in image_files:
# 图片路径
image_path = os.path.join(image_folder, image_file)
# 读取图片
image = cv2.imread(image_path)

# 对应的标注文件路径(假设标注文件名与图片文件名相同,只是后缀不同)
annotation_file = os.path.splitext(image_file)[0] + ".txt"
annotation_path = os.path.join(annotation_folder, annotation_file)

# 读取标注数据
with open(annotation_path, "r") as file:
annotations = file.readlines()

# 在图像上显示标注
for annotation in annotations:
annotation_data = annotation.split()
label = class_map[annotation_data[0]]
x_center = float(annotation_data[1])
y_center = float(annotation_data[2])
width = float(annotation_data[3])
height = float(annotation_data[4])

# 计算标注框的左上角和右下角坐标
x_min = int((x_center - width / 2) * image.shape[1])
y_min = int((y_center - height / 2) * image.shape[0])
x_max = int((x_center + width / 2) * image.shape[1])
y_max = int((y_center + height / 2) * image.shape[0])

# 画框
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)

# 标注文本
cv2.putText(image, label, (x_min, y_min - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

# 保存图像
output_path = os.path.join(output_folder, image_file)
cv2.imwrite(output_path, image)

# 显示完成消息
print("图像处理完成!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值