import numpy as np import json class BackData: def __init__(self, json_data): """ 初始化背部数据处理器 Args: json_data: 包含背部标注信息的JSON数据字典 """ self.json_data = json_data self.vertices = [] # 背部区域四个顶点 self.back_center_point = None # 背部中心点坐标 self.length = 0 # 背部区域长度 self.width = 0 # 背部区域宽度 # 处理数据 self._process_data() def _calculate_distance(self, point1, point2): """计算两点之间的欧几里得距离""" return np.sqrt((point2[0] - point1[0])**2 + (point2[1] - point1[1])**2) def _process_data(self): """处理JSON数据,提取背部相关信息""" for shape in self.json_data.get('shapes', []): label = shape['label'] points = shape['points'] if shape['shape_type'] == 'polygon' and label == 'back': # 存储四个顶点坐标 self.vertices = [tuple(map(float, point)) for point in points] # 计算背部长和宽 self.length = self._calculate_distance(points[0], points[1]) # 第1点和第2点之间的距离 self.width = self._calculate_distance(points[1], points[2]) # 第2点和第3点之间的距离 elif shape['shape_type'] == 'point' and label == 'back_center': # 存储背部中心点坐标 self.back_center_point = tuple(map(float, points[0])) def get_all_data(self): """获取所有处理后的背部数据""" return { 'vertices': self.vertices, 'back_center_point': self.back_center_point, 'dimensions': { 'length': self.length, 'width': self.width } } def get_vertices(self): """获取背部区域四个顶点坐标""" return self.vertices def get_back_center_point(self): """获取背部中心点坐标""" return self.back_center_point def get_dimensions(self): """获取背部区域长度和宽度""" return { 'length': self.length, 'width': self.width } # 使用示例 if __name__ == "__main__": # 示例JSON数据 sample_json = { "version": "5.6.0", "flags": {}, "shapes": [ { "label": "back", "points": [ [263.12977099236645, 119.96183206106873], [451.2977099236641, 140.19083969465652], [439.0839694656489, 243.24427480916032], [250.53435114503822, 218.4351145038168] ], "shape_type": "polygon" }, { "label": "back_center", "points": [[358.5496183206107, 184.84732824427482]], "shape_type": "point" } ] } # 从文件读取JSON数据 with open('/home/kira/codes/jsfb-back-manal/rotjsons1/color_65.json', 'r') as f: sample_json = json.load(f) # 创建背部数据处理器实例 processor = BackData(sample_json) # 获取所有数据 all_data = processor.get_all_data() # 打印结果 print("背部区域四个顶点坐标:") for i, vertex in enumerate(processor.get_vertices(), 1): print(f"顶点{i}: {vertex}") print(f"\n背部中心点坐标: {processor.get_back_center_point()}") dimensions = processor.get_dimensions() print(f"\n背部长度: {dimensions['length']:.2f}") print(f"背部宽度: {dimensions['width']:.2f}")