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

labelme实例分割标注的图片和标注数据微微旋转1度2度 做数据扩增

点击查看代码
import json
import os
import base64
import numpy as np
import cv2
from math import cos, sin, radians
import argparsedef rotate_point_opencv_style(point, rotation_matrix):"""用OpenCV旋转矩阵计算标注点,确保与图像旋转逻辑一致"""point_homo = np.array([point[0], point[1], 1], dtype=np.float32)rotated_point = np.dot(rotation_matrix, point_homo)return (round(rotated_point[0]), round(rotated_point[1]))def image_to_base64(img):"""OpenCV图像转Base64编码(LabelMe imageData字段需求)"""ret, buffer = cv2.imencode('.jpg', img)if not ret:raise ValueError("无法编码图像为JPEG格式")return base64.b64encode(buffer).decode('utf-8')def rotate_single_labelme(json_path, output_root_dir, angle):"""单文件LabelMe旋转处理(核心功能,复用原逻辑):param json_path: 单个JSON文件路径:param output_root_dir: 批量输出的根目录(会保持原目录结构):param angle: 旋转角度(度,逆时针为正)"""try:# 1. 读取LabelMe数据和原始图像with open(json_path, 'r', encoding='utf-8') as f:data = json.load(f)# 拼接原始图像路径(LabelMe的imagePath是相对JSON的路径)img_origin_abs_path = os.path.splitext(json_path)[0] + '.jpg'# img_origin_abs_path = os.path.join(os.path.dirname(json_path), img_origin_rel_path)img_origin = cv2.imread(img_origin_abs_path)if img_origin is None:raise FileNotFoundError(f"图像文件不存在:{img_origin_abs_path}")# 2. 图像维度与旋转中心(严格对齐LabelMe与OpenCV坐标)h_origin, w_origin = img_origin.shape[:2]  # OpenCV:h=行(y),w=列(x)center_origin = (w_origin // 2, h_origin // 2)  # 旋转中心:(x=列, y=行)# 3. 计算旋转后图像尺寸(避免裁剪,完整保留旋转内容)angle_rad = radians(angle)w_rot = int(h_origin * abs(sin(angle_rad)) + w_origin * abs(cos(angle_rad)))h_rot = int(w_origin * abs(sin(angle_rad)) + h_origin * abs(cos(angle_rad)))# 4. 生成OpenCV旋转矩阵(图像与标注共用,强制同步)M = cv2.getRotationMatrix2D(center=center_origin, angle=angle, scale=1.0)# 偏移量:让旋转后的图像居中显示dx = (w_rot // 2) - center_origin[0]dy = (h_rot // 2) - center_origin[1]M[0, 2] += dxM[1, 2] += dy# 5. 旋转图像img_rot = cv2.warpAffine(src=img_origin,M=M,dsize=(w_rot, h_rot),flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=(255, 255, 255)  # 白色背景(可自定义))# 6. 旋转标注点(用同一个矩阵M,无偏差)for shape in data['shapes']:rotated_points = [rotate_point_opencv_style(p, M) for p in shape['points']]shape['points'] = [list(p) for p in rotated_points]  # 转为List格式(LabelMe要求)# 7. 构建输出路径(保持原目录结构,避免文件混乱)# 例:原路径 ./data/label1.json → 输出 ./output/data/label1_rotated_90deg.jsonrelative_json_path = os.path.relpath(json_path, start=os.path.dirname(output_root_dir))output_json_dir = os.path.join(output_root_dir, os.path.dirname(relative_json_path))os.makedirs(output_json_dir, exist_ok=True)# 8. 更新LabelMe JSON字段并保存# 处理图像文件名(添加旋转标识)img_filename = os.path.basename(img_origin_abs_path)img_name, img_ext = os.path.splitext(img_filename)new_img_name = f"{img_name}_rotated_{angle}deg{img_ext}"# 处理JSON文件名json_filename = os.path.basename(json_path)json_name, json_ext = os.path.splitext(json_filename)new_json_name = f"{json_name}_rotated_{angle}deg{json_ext}"# 更新JSON内容data['imagePath'] = new_img_name  # 关联旋转后的图像data['imageWidth'] = w_rot  # 旋转后图像宽度(列数)data['imageHeight'] = h_rot  # 旋转后图像高度(行数)data['imageData'] = image_to_base64(img_rot)  # 更新Base64编码# 保存旋转后的图像和JSONoutput_img_path = os.path.join(output_json_dir, new_img_name)output_json_path = os.path.join(output_json_dir, new_json_name)cv2.imwrite(output_img_path, img_rot)with open(output_json_path, 'w', encoding='utf-8') as f:json.dump(data, f, ensure_ascii=False, indent=2)return True, f"成功:{os.path.basename(json_path)} → {new_json_name}"except Exception as e:return False, f"失败:{os.path.basename(json_path)} → 错误原因:{str(e)}"def batch_rotate_labelme(input_root_dir, output_root_dir, angle):"""批量旋转目录中所有LabelMe JSON文件:param input_root_dir: 输入根目录(会递归遍历所有子目录):param output_root_dir: 输出根目录(保持与输入一致的目录结构):param angle: 旋转角度(度,逆时针为正)"""# 校验输入目录是否存在if not os.path.isdir(input_root_dir):raise NotADirectoryError(f"输入目录不存在:{input_root_dir}")os.makedirs(output_root_dir, exist_ok=True)# 统计变量total_count = 0success_count = 0fail_list = []# 递归遍历所有子目录,寻找JSON文件for root, dirs, files in os.walk(input_root_dir):for file in files:# 只处理LabelMe生成的JSON文件(避免非标注JSON)if file.endswith('.json'):total_count += 1json_abs_path = os.path.join(root, file)# 调用单文件处理函数success, msg = rotate_single_labelme(json_abs_path, output_root_dir, angle)print(msg)  # 实时打印处理进度if success:success_count += 1else:fail_list.append(msg)# 输出批量处理总结print("\n" + "=" * 50)print(f"批量处理完成!")print(f"总文件数:{total_count}")print(f"成功数:{success_count}")print(f"失败数:{len(fail_list)}")if fail_list:print("失败详情:")for fail_msg in fail_list:print(f"  - {fail_msg}")if __name__ == "__main__":# 命令行参数配置(支持批量处理)# parser = argparse.ArgumentParser(description='批量旋转LabelMe标注数据(图像与标注100%对齐)')# parser.add_argument('input_dir', default=r'trains\seg_gelinmei_yicikeli\labeled', help='输入根目录(会递归遍历所有子目录的JSON)')# parser.add_argument('output_dir', default=r'seg_gelinmei_yicikeli\augumented',help='输出根目录(保持与输入一致的目录结构)')# parser.add_argument('angle', type=float, default='3', help='旋转角度(度,逆时针为正,例:90/180/-90)')# input_dir = r'trains\seg_gelinmei_yicikeli\labeled'# output_dir = r'trains\seg_gelinmei_yicikeli\augumented'input_dir = r'trains\seg_hongmoshui\labeled'output_dir = r'trains\seg_hongmoshui\augumented'angle = 3# args = parser.parse_args()# 启动批量处理batch_rotate_labelme(input_dir, output_dir, angle)
http://www.jsqmd.com/news/417901/

相关文章:

  • 2026看中医去哪里?中医诊疗机构推荐及选择指南 - 品牌排行榜
  • 2026年优质清洁设备厂家口碑榜 涵盖智能清洁 适配多场景实用之选 - 深度智识库
  • 2026年全国保洁设备厂家哪家好?技术过硬服务周到 适配多场景需求 - 深度智识库
  • 港校逐梦“加速器”:留学中介TOP10实力大揭秘 - 博客湾
  • 干燥设备订制优选集:2026年这些厂家评价颇高,离心造粒包衣机/高效沸腾制粒机/高效粉碎机,干燥设备生产厂家有哪些 - 品牌推荐师
  • LORA无线数传模块
  • 2026年 全自动洗车机厂家实力推荐榜:隧道式/往复式/公交大巴/智能无人值守洗车机品牌深度解析与选购指南 - 品牌企业推荐师(官方)
  • 2026磁轴键盘排名TOP1!迈从Ace 68 Turbo|实至名归的磁轴键盘性价比之王 - 速递信息
  • 揭秘2026:GEO优化如何助力企业突破增长瓶颈,GEO服务/GEO优化AI搜索,GEO优化企业有哪些 - 品牌推荐师
  • LoRa无线数传模块:点对多点通信,一主多从全覆盖
  • mongodb数据库被攻击后分析排查,恢复数据操作
  • 详解文献中引用其他参考文献格式对应的含义
  • 港校申请“加速键”:十大留学中介助力冲刺香港名校 - 博客湾
  • 2026 年知识库部署厂商排行:优质服务商、定制方案商、全栈部署厂商全面汇总 - 品牌2025
  • 浙大 × 西湖大学最新:超越π0.5,融合人类数据与世界模型的高效VLA训练框架
  • 本科留学秘籍大公开!留学中介助力名校梦 - 博客湾
  • 2026年四川省机房建设厂家推荐榜 西南数基建设实力企业甄选(附评分) - 深度智识库
  • 2026 靠谱知识库部署厂商盘点:企业级服务商、AI 方案商、本地化部署商一应俱全 - 品牌2025
  • 联想全新服务打造永不停机的基础设施:由主动式 AI 驱动支持赋能的服务器 Premier Support Plus 服务
  • 圆梦海本科: 靠谱留学中介实力护航,冲刺顶尖本科 - 博客湾
  • 2026年徐州压路机/装载机/清扫机防撞系统/夜间施工照明灯/LED信息看板厂家综合评测报告 - 2026年企业推荐榜
  • 2026市场靠谱冰火板公司哪家好?优质之选在这里,玻纤板/冰火板/A级抗倍特/石英纤维板/树脂板,冰火板供应商怎么选择 - 品牌推荐师
  • 广西地产集团 | 破资产信息混乱,稳保收益不流失 - 搭贝
  • 2026磁轴键盘品牌排名前10名出炉!迈从Ace 68 Turbo成关注焦点 - 速递信息
  • GEO优化服务公司来了 这个AI风口快快抓住 - 品牌推荐大师1
  • 【211高校-湖南师范大学主办 | ACM出版,EI检索快速稳定 | IEEE Fellow加持 | 可持续、计算机主题EI会议征稿】2026年计算机技术与可持续发展国际学术会议(CTSD 2026)
  • 写论文省心了 9个AI论文工具测评:本科生毕业论文+科研写作必备神器
  • 2026年2月徐州称重给料机、电子皮带秤、称重给煤机厂家综合测评 - 2026年企业推荐榜
  • 留学申请更省心:TOP10 本科留学中介靠谱甄选 - 博客湾
  • ABB称重传感器PFTL201DE-100.0