当前位置: 首页 > news >正文

coco 可视化 txt版

txt和图片在同一个目录中:

#!/usr/bin/env python3
"""
yolo_to_labelme_json.pyConvert YOLO-style txt annotations to LabelMe JSON format (one JSON per image).
Each line: CLASS X_CENTER Y_CENTER WIDTH HEIGHTUsage examples:python yolo_to_labelme_json.py --images /path/to/images --labels /path/to/labels --outdir ./labelme_jsonspython yolo_to_labelme_json.py -i ./images -l ./labels -c classes.txt
"""import os
import json
import argparse
import base64
from pathlib import Pathdef load_class_names(path):"""Load class names from file"""if not path:return Noneif not os.path.exists(path):print(f"[warn] classes file not found: {path}")return Nonewith open(path, 'r', encoding='utf-8') as f:names = [line.strip() for line in f if line.strip() != ""]return namesdef parse_label_line(line):"""Parse a single line from YOLO label file"""parts = line.strip().split()if len(parts) < 5:return Nonecls = int(float(parts[0]))x_c = float(parts[1])y_c = float(parts[2])w = float(parts[3])h = float(parts[4])return cls, x_c, y_c, w, hdef yolo_to_labelme_bbox(x_center, y_center, width, height, img_width, img_height):"""Convert YOLO format to LabelMe rectangle points [[x1,y1], [x2,y2]]"""# Convert normalized coordinates to pixel coordinatesw_pixel = width * img_widthh_pixel = height * img_heightx_center_pixel = x_center * img_widthy_center_pixel = y_center * img_height# Calculate bounding box coordinatesx_min = x_center_pixel - w_pixel / 2y_min = y_center_pixel - h_pixel / 2x_max = x_center_pixel + w_pixel / 2y_max = y_center_pixel + h_pixel / 2# Ensure coordinates are within image boundsx_min = max(0, x_min)y_min = max(0, y_min)x_max = min(img_width - 1, x_max)y_max = min(img_height - 1, y_max)# LabelMe uses [[x1, y1], [x2, y2]] format for rectanglesreturn [[round(x_min), round(y_min)], [round(x_max), round(y_max)]]def get_image_info(img_path, include_image_data=False):"""Get image information and optionally encode image data"""try:import cv2img = cv2.imread(img_path)if img is not None:height, width = img.shape[:2]image_data = Noneif include_image_data:# Encode image to base64success, encoded_image = cv2.imencode('.jpg', img)if success:image_data = base64.b64encode(encoded_image).decode('utf-8')return width, height, image_dataexcept Exception as e:print(f"[warn] Could not read image {img_path}: {e}")return None, None, Nonedef convert_yolo_to_labelme(label_path, img_path, class_names=None, version="5.3.1", include_image_data=False):"""Convert YOLO label file to LabelMe JSON formatArgs:label_path: Path to YOLO label fileimg_path: Path to corresponding image fileclass_names: List of class namesversion: LabelMe version stringinclude_image_data: Whether to include base64 encoded image dataReturns:LabelMe JSON format dictionary"""# Get image informationimg_width, img_height, image_data = get_image_info(img_path, include_image_data)if img_width is None or img_height is None:print(f"[warn] Could not get image dimensions for {img_path}")return None# Initialize shapes listshapes = []# Process label file if it existsif os.path.exists(label_path):with open(label_path, 'r', encoding='utf-8') as f:lines = [ln.strip() for ln in f if ln.strip()]for line_num, line in enumerate(lines):parsed = parse_label_line(line)if parsed is None:continuecls_id, x_center, y_center, width, height = parsed# Convert YOLO bbox to LabelMe pointspoints = yolo_to_labelme_bbox(x_center, y_center, width, height, img_width, img_height)# Get label namelabel_name = class_names[cls_id] if class_names and 0 <= cls_id < len(class_names) else f"class_{cls_id}"# Create shape objectshape = {"label": label_name, "group_id": None, "description": "", "shape_type": "rectangle", "flags": {}, "points": points}shapes.append(shape)# Create LabelMe JSON structurelabelme_json = {"version": version, "flags": {}, "imageData": image_data, "imageHeight": img_height, "imageWidth": img_width, "imagePath": os.path.basename(img_path), "shapes": shapes}return labelme_jsondef find_label_for_image(img_path, labels_dir, label_ext=".txt"):"""Find corresponding label file for an image"""base = os.path.splitext(os.path.basename(img_path))[0]# Try several common label filename patternscandidates = [os.path.join(labels_dir, base + label_ext), os.path.join(labels_dir, base + ".txt"), ]for candidate in candidates:if os.path.exists(candidate):return candidate# Fallback: label file in same directory as imagealt = os.path.splitext(img_path)[0] + label_extif os.path.exists(alt):return altreturn Nonedef main():parser = argparse.ArgumentParser(description="Convert YOLO txt annotations to LabelMe JSON format")parser.add_argument('--images', '-i', default=r'B:\data\wangqiu\12\12\output\train\images', help="Image directory or single image file")parser.add_argument('--labels', '-l', required=False, default=r'B:\data\wangqiu\12\12\output\train\labels', help="Labels directory (default: same as images)")parser.add_argument('--outdir', '-o', required=False,default=r'B:\data\wangqiu\12\12\output\train\labels', help="Output directory for JSON files")parser.add_argument('--classes', '-c', required=False, help="Optional classes txt file (one name per line)")parser.add_argument('--version', '-v', default='5.3.1', help="LabelMe version string")parser.add_argument('--include-image-data', action='store_true', help="Include base64 encoded image data in JSON")parser.add_argument('--ext', required=False, help="Image extensions to scan (comma separated)", default="jpg,jpeg,png,bmp,tiff")args = parser.parse_args()# Load class namesclass_names = load_class_names(args.classes)if class_names:print(f"[info] Loaded {len(class_names)} class names")# Create output directoryos.makedirs(args.outdir, exist_ok=True)# Find image filesimgs = []if os.path.isdir(args.images):exts = [e.strip().lower() for e in args.ext.split(',')]for root, _, files in os.walk(args.images):for fn in files:if fn.split('.')[-1].lower() in exts:imgs.append(os.path.join(root, fn))elif os.path.isfile(args.images):imgs = [args.images]else:print("[error] Images path not found:", args.images)returnprint(f"[info] Found {len(imgs)} images")# Process each imageconverted_count = 0for img_path in sorted(imgs):try:# Find corresponding label filelabel_path = find_label_for_image(img_path, args.labels)if not label_path or not os.path.exists(label_path):print(f"[warn] No label file found for: {os.path.basename(img_path)}")# Create empty LabelMe JSON (image with no objects)img_width, img_height, image_data = get_image_info(img_path, args.include_image_data)if img_width is None:print(f"[error] Could not process image: {img_path}")continuelabelme_json = {"version": args.version, "flags": {}, "imageData": image_data if args.include_image_data else None, "imageHeight": img_height, "imageWidth": img_width,"imagePath": os.path.basename(img_path), "shapes": []}else:# Convert label filelabelme_json = convert_yolo_to_labelme(label_path, img_path, class_names, args.version, args.include_image_data)if labelme_json is None:print(f"[error] Failed to convert label for: {os.path.basename(img_path)}")continue# Save JSON filebase_name = os.path.splitext(os.path.basename(img_path))[0]json_path = os.path.join(args.outdir, base_name + '.json')with open(json_path, 'w', encoding='utf-8') as f:json.dump(labelme_json, f, indent=2, ensure_ascii=False)converted_count += 1num_shapes = len(labelme_json['shapes'])print(f"[ok] Converted: {os.path.basename(img_path)} -> {os.path.basename(json_path)} "f"({num_shapes} objects)")except Exception as e:print(f"[error] Failed to process {img_path}: {e}")print(f"\n[summary] Successfully converted {converted_count}/{len(imgs)} images to LabelMe JSON format")print(f"[summary] Output directory: {args.outdir}")print(f"[summary] LabelMe version: {args.version}")if args.include_image_data:print(f"[summary] Image data: included (base64 encoded)")else:print(f"[summary] Image data: not included")if __name__ == "__main__":main()

http://www.dtcms.com/a/531782.html

相关文章:

  • idea字体的问题(idea应用本身的字体问题)
  • 计算机操作系统 — 链接
  • 网站图片加altwordpress前端库加速
  • 在linux上使用docker搭建ELK日志框架
  • Docker 应该如何学习 分四个阶段
  • 面试过程中的扣分项,你踩过几个?
  • 中牟高端网站建设专做户外装备测评视频网站
  • CSS属性(二)
  • 2011年下半年试题四:论软件需求获取技术及应用
  • Mujoco 仿真 PPO 强化学习机械臂末端路径规划到达指定位置(代码讲解)
  • 【C#】EventHandler的使用
  • C++ 实际应用系列(第六部分):并发系统的性能优化与工程实践(完)
  • 上市公司网站建设分析wordpress 转 app
  • Prometheus+Grafana 智能监控告警系统(服务器指标采集、mysql指标采集)
  • html5电影网站如何做企业网站流量怎么做
  • <数据集>yolo煤矿安全帽识别数据集<目标检测>
  • excel中加载数据分析工具的步骤
  • 一文厘清:文库 vs 知识库、核心功能清单、开源方案对比
  • 图片转excel vlm 提取手写清单信息 Qwen/Qwen3-VL-235B-A22B-Instruct
  • webrtc代码走读(七)-QOS-FEC-ulpfec rfc5109
  • 第十五章认识Ajax(六)
  • 逻辑回归解释
  • B038基于博途西门子1200PLC物料分拣控制系统仿真
  • 第十二章认识Ajax(三)
  • Spring Boot3零基础教程,安装 docker,笔记67
  • FLOW翻译
  • 第十六章jQuery中的Ajax
  • 实现 AI 流式响应:从等待到实时交互的技术解析
  • 东莞站福公司工资室内设计手绘图 基础入门
  • HTTPS 加密原理介绍