import os from ultralytics import YOLO import cv2 import os # 定义函数读取YOLO格式的标注文件 def read_yolo_labels(label_path): labels = [] with open(label_path, 'r') as f: for line in f: parts = line.strip().split() if len(parts) < 5: continue # 跳过无效行 class_id = int(parts[0]) x_center = float(parts[1]) y_center = float(parts[2]) width = float(parts[3]) height = float(parts[4]) labels.append({'class': class_id, 'x_center': x_center, 'y_center': y_center, 'width': width, 'height': height}) return labels # 定义函数绘制bounding box def draw_bounding_boxes(image, labels, image_width, image_height): for label in labels: x_center = label['x_center'] * image_width y_center = label['y_center'] * image_height width = label['width'] * image_width height = label['height'] * image_height x_min = int(x_center - width / 2) y_min = int(y_center - height / 2) x_max = int(x_center + width / 2) y_max = int(y_center + height / 2) cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2) cv2.putText(image, str(label['class']), (x_min, y_min - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) return image model = YOLO('best.pt') images_to_annote_path = './imgs_no_labels' new_label_path = './new_labels' images_names = os.listdir(images_to_annote_path) images_path = [os.path.join(images_to_annote_path, img) for img in images_names] confidence = 0.5 results = [] for i in range(0, len(images_path), 10): if i + 10 < len(images_path): results += model.predict(images_path[i:i+10]) else: results += model.predict(images_path[i:]) import shutil shutil.rmtree(new_label_path) os.mkdir(new_label_path) for i, result in enumerate(results): result.boxes = [box for box in result.boxes if box.conf > confidence] result.save_txt(f'./{new_label_path}/{images_names[i].replace(".jpg", ".txt").replace(".png", ".txt").replace(".jpeg", ".txt")}') print(f"Saved {images_names[i]}") # 设置图片和标注文件的路径 image_folder = images_to_annote_path label_folder = new_label_path # 遍历图片文件夹, for image_file in os.listdir(image_folder): if image_file.endswith('.jpg') or image_file.endswith('.png') or image_file.endswith('.jpeg'): image_path = os.path.join(image_folder, image_file) label_file = image_file.split('.')[0] + '.txt' label_path = os.path.join(label_folder, label_file) if os.path.exists(label_path): image = cv2.imread(image_path) image_height, image_width, _ = image.shape labels = read_yolo_labels(label_path) image_with_boxes = draw_bounding_boxes(image, labels, image_width, image_height) cv2.imshow('Image', image_with_boxes) cv2.waitKey(0) cv2.destroyAllWindows() else: print(f'Label file {label_file} not found.')