基于JSON的图片缺陷处理流程
├── 1. 输入检查
│ ├── 验证图片文件是否存在
│ └── 验证JSON文件是否存在
│
├── 2. 数据加载
│ ├── 打开并加载图片
│ └── 读取并解析JSON文件
│
├── 3. 缺陷信息提取
│ ├── 检查JSON中是否存在shapes字段
│ └── 遍历每个缺陷形状
│ ├── 验证形状类型是否为矩形
│ ├── 提取缺陷坐标点
│ └── 计算边界框(左上角和右下角)
│
├── 4. 缺陷区域处理
│ ├── 从原图裁剪缺陷区域
│ ├── 保存缺陷区域为BMP文件
│ └── 在原图上标记缺陷位置
│
└── 5. 结果保存├── 保存标记后的原图└── 输出处理结果信息
安装好包,修改好文件路径后,可直接使用的代码展示:
(注意,原图与Json文件要在同一目录下)
import json
import os
from PIL import Image, ImageDraw# 在pycharm中通过josn文件定位图片缺陷点,并复制一份缺陷特征打印成bmp文件保存在该路径def process_defects(image_path, json_path):"""基于JSON文件中的坐标信息,处理图片中的缺陷:param image_path: 图片文件路径:param json_path: JSON文件路径,包含缺陷坐标"""try:# 加载图片with Image.open(image_path) as img:# 读取JSON文件with open(json_path, 'r') as f:defect_data = json.load(f)# 从shapes字段获取缺陷信息(适配实际JSON结构)if 'shapes' not in defect_data or not defect_data['shapes']:print("JSON文件中未发现缺陷信息")return# 获取图片目录和基本名称img_dir = os.path.dirname(image_path)img_base_name = os.path.splitext(os.path.basename(image_path))[0]# 为每个缺陷创建子图像for i, shape in enumerate(defect_data['shapes']):# 检查是否为矩形if shape.get('shape_type') != 'rectangle':print(f"缺陷 {i + 1} 不是矩形,跳过")continue# 从points提取坐标(四个点转为两个点)points = shape.get('points')if not points or len(points) != 4:print(f"缺陷 {i + 1} 的坐标格式不正确")continue# 提取左上角和右下角坐标x_coords = [p[0] for p in points]y_coords = [p[1] for p in points]left = min(x_coords)top = min(y_coords)right = max(x_coords)bottom = max(y_coords)# 转换为整数left, top, right, bottom = map(int, [left, top, right, bottom])# 提取缺陷区域defect_region = img.crop((left, top, right, bottom))# 保存缺陷区域为BMP文件defect_filename = f"{img_base_name}_defect_{i + 1}.bmp"defect_filepath = os.path.join(img_dir, defect_filename)defect_region.save(defect_filepath, 'BMP')print(f"缺陷 {i + 1} 已保存至: {defect_filepath}")# 在原图上标记缺陷draw = ImageDraw.Draw(img)draw.rectangle([left, top, right, bottom], outline="red", width=2)# 保存标记后的原图(可选)marked_img_path = os.path.join(img_dir, f"{img_base_name}_marked.jpg")img.save(marked_img_path)print(f"标记后的图片已保存至: {marked_img_path}")except FileNotFoundError as e:print(f"错误:文件未找到 - {e}")except json.JSONDecodeError:print(f"错误:无法解析JSON文件 - {json_path}")except Exception as e:print(f"发生未知错误: {e}")if __name__ == "__main__":# 使用实际文件路径image_file = r"pptt\0.bmp"json_file = r"pptt\0.json"# 检查文件是否存在if os.path.exists(image_file) and os.path.exists(json_file):process_defects(image_file, json_file)else:print("请提供有效的图片和JSON文件路径")