coco 删除小目标
import glob
import os
import jsondef get_normalized_box(points):"""将任意顺序的点转换为 [x_min, y_min, x_max, y_max] 格式"""x_coords = [point[0] for point in points]y_coords = [point[1] for point in points]x_min = min(x_coords)y_min = min(y_coords)x_max = max(x_coords)y_max = max(y_coords)return [x_min, y_min, x_max, y_max]def is_small_box(box, min_size=10):"""检查框是否小于指定尺寸"""x_min, y_min, x_max, y_max = boxwidth = x_max - x_minheight = y_max - y_minreturn width * height < min_size * min_sizedef remove_small_boxes(json_path, min_size=10):"""删除文件中的小框"""with open(json_path, 'r', encoding='utf-8') as f:data = json.load(f)shapes = data.get('shapes', [])kept_shapes = []removed_boxes = []for shape in shapes:box = get_normalized_box(shape['points'])if is_small_box(box, min_size):width = box[2] - box[0]height = box[3] - box[1]removed_boxes.append({'label': shape['label'],'width': width,'height': height})else:kept_shapes.append(shape)# 如果有小框被删除,更新文件if removed_boxes:print(f"删除小框: {json_path}")for box_info in removed_boxes:print(f" - 删除 {box_info['label']}: {box_info['width']:.1f}x{box_info['height']:.1f}")data['shapes'] = kept_shapeswith open(json_path, 'w', encoding='utf-8') as f:json.dump(data, f, ensure_ascii=False, indent=4)return True, len(removed_boxes)return False, 0if __name__ == '__main__':folder = r"D:\data\det_chantu\val_pen"dirs = glob.glob(os.path.join(folder, "*"))total_files = 0total_removed_boxes = 0for dir_a in dirs:json_files = ['%s/%s' % (i[0].replace("\\", "/"), j) for i in os.walk(dir_a) for j in i[-1] ifj.lower().endswith('.json')]print(f"=== 目录: {os.path.basename(dir_a)} ===")dir_files = 0dir_removed_boxes = 0for json_file in json_files:# json_file=r"D:\data\det_chantu\train_pen\20251028_1646_part007_seg\0_ok\28_19_0.json"removed, count = remove_small_boxes(json_file)if removed:dir_files += 1dir_removed_boxes += counttotal_files += 1total_removed_boxes += countif dir_removed_boxes > 0:print(f"目录统计: {dir_files} 个文件删除了小框, 共删除 {dir_removed_boxes} 个小框")print(f"\n总体统计: {total_files} 个文件删除了小框")print(f"总共删除 {total_removed_boxes} 个小框")