基于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文件路徑")