import cv2
import os
# 图片文件夹路径
image_folder = "D:/PycharmProjects/yolov5-master/sodanight2.0/images/test"
# 标注文件夹路径
annotation_folder = "D:/PycharmProjects/yolov5-master/sodanight2.0/labels/test"
# 获取图片文件夹中所有图片文件的路径
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 = 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)
# 显示带有标注的图像
cv2.imshow("Image with Annotations", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
(四)生成图片,对应其yolo格式标签
于 2023-06-27 14:45:41 首次发布