added polygon support
Browse files149 unmodified lines1501511521531541553 unmodified lines1591601611621631641651669 unmodified lines1761771781791801811828 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223149 unmodified linesimage_paths: List of image file pathsoutput_dir: Directory to save annotated images and labelsimage_size: Size for inference"""if not self.model:raise ValueError("β No model loaded. Please load a model first.")3 unmodified linesimage_size = image_size or Config.DEFAULT_IMAGE_SIZE# clean_directory(output_dir)totla_images = len(image_paths)print(f"π¨ Annotating {totla_images} images and saving labels...")for idx, image_path in enumerate(image_paths):if not os.path.isfile(image_path):9 unmodified lines# Run inferenceresults = self.model(image_path, imgsz=image_size)annotated_frame = results[0].plot()# Prepare save pathsoriginal_name = os.path.basename(image_path)8 unmodified lines# Write YOLO label filewith open(save_txt_path, 'w') as f:for box in results[0].boxes:# box.xyxy format: (xmin, ymin, xmax, ymax)xyxy = box.xyxy[0].tolist()cls_id = int(box.cls[0].item()) # class idxmin, ymin, xmax, ymax = xyxy# Convert to YOLO format (normalized)x_center = ((xmin + xmax) / 2) / wy_center = ((ymin + ymax) / 2) / hwidth = (xmax - xmin) / wheight = (ymax - ymin) / h# Write one line per objectf.write(f"{cls_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")if label_path:shutil.copyfile(save_txt_path, label_path)print(f'β Saved annotated image: {save_img_path}')print(f'β Saved label file: {save_txt_path}')print(f"π Annotation and label saving complete! Results saved to: {output_dir}")if totla_images == 1:return save_img_path, save_txt_pathexcept Exception as e:print(f"β Error processing {image_path}: {str(e)}")return None, Nonedef __enter__(self):# When entering context, just return self149 unmodified lines1501511521531541551561573 unmodified lines1611621631641651661671689 unmodified lines1781791801811821831841858 unmodified lines194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257149 unmodified linesimage_paths: List of image file pathsoutput_dir: Directory to save annotated images and labelsimage_size: Size for inferencesave_image: Whether to save annotated imageslabel_path: Optional specific path for label file"""if not self.model:raise ValueError("β No model loaded. Please load a model first.")3 unmodified linesimage_size = image_size or Config.DEFAULT_IMAGE_SIZE# clean_directory(output_dir)total_images = len(image_paths)print(f"π¨ Annotating {total_images} images and saving labels...")for idx, image_path in enumerate(image_paths):if not os.path.isfile(image_path):9 unmodified lines# Run inferenceresults = self.model(image_path, imgsz=image_size)result = results[0]annotated_frame = result.plot()# Prepare save pathsoriginal_name = os.path.basename(image_path)8 unmodified lines# Write YOLO label filewith open(save_txt_path, 'w') as f:# Check if we have segmentation masks (YOLO-seg model)if hasattr(result, 'masks') and result.masks is not None:print(f"π Processing segmentation masks...")# Process segmentation masksmasks = result.masksfor i, mask in enumerate(masks.xy): # masks.xy gives polygon coordinatescls_id = int(result.boxes.cls[i].item())# mask is already in pixel coordinates# Normalize coordinates to [0,1] rangenormalized_coords = []for point in mask:x_norm = point[0] / wy_norm = point[1] / hnormalized_coords.extend([x_norm, y_norm])# Write segmentation format: class_id x1 y1 x2 y2 x3 y3 ...coords_str = ' '.join(f'{coord:.6f}' for coord in normalized_coords)f.write(f"{cls_id} {coords_str}\n")# Fallback to bounding boxes if no masks (YOLO detection model)elif hasattr(result, 'boxes') and result.boxes is not None:print(f"π¦ Processing bounding boxes...")for box in result.boxes:# box.xyxy format: (xmin, ymin, xmax, ymax)xyxy = box.xyxy[0].tolist()cls_id = int(box.cls[0].item())xmin, ymin, xmax, ymax = xyxy# Convert to YOLO format (normalized)x_center = ((xmin + xmax) / 2) / wy_center = ((ymin + ymax) / 2) / hwidth = (xmax - xmin) / wheight = (ymax - ymin) / h# Write bounding box format: class_id x_center y_center width heightf.write(f"{cls_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}\n")else:print("β οΈ No detections found in this image")if label_path:shutil.copyfile(save_txt_path, label_path)if save_img_path:print(f'β Saved annotated image: {save_img_path}')print(f'β Saved label file: {save_txt_path}')print(f"π Annotation and label saving complete! Results saved to: {output_dir}")if total_images == 1:return save_img_path, save_txt_pathexcept Exception as e:print(f"β Error processing {image_path}: {str(e)}")if total_images == 1:return None, Nonedef __enter__(self):# When entering context, just return self
comic_panel_extractor/yolo_manager.py+52-18