import os import cv2 # ========================================================= # 配置 # ========================================================= SRC_DIR = "muban_image" # 原始模板目录 DST_DIR = "muban_image2" # 裁剪后保存目录 # 三个 ROI(x, y, w, h) ROI_1 = (782, 614, 164, 128) ROI_2 = (837, 791, 100, 99) ROI_3 = (873, 736, 141, 110) # ========================================================= # 裁剪函数 # ========================================================= def crop_and_save(img_path, save_dir): img = cv2.imread(img_path) if img is None: print(f"[WARN] 读取失败: {img_path}") return h_img, w_img = img.shape[:2] base = os.path.splitext(os.path.basename(img_path))[0] roi_list = [ROI_1, ROI_2, ROI_3] for idx, roi in enumerate(roi_list, start=1): x, y, w, h = roi # 边界保护 x1 = max(0, x) y1 = max(0, y) x2 = min(w_img, x + w) y2 = min(h_img, y + h) if x2 <= x1 or y2 <= y1: print(f"[WARN] ROI_{idx} 超出图像范围: {img_path}") continue roi_img = img[y1:y2, x1:x2] save_name = f"{base}_roi{idx}.png" save_path = os.path.join(save_dir, save_name) cv2.imwrite(save_path, roi_img) print(f"[OK] 保存: {save_path}") # ========================================================= # main # ========================================================= if __name__ == "__main__": if not os.path.isdir(SRC_DIR): raise RuntimeError(f"源目录不存在: {SRC_DIR}") os.makedirs(DST_DIR, exist_ok=True) for fname in os.listdir(SRC_DIR): if not fname.lower().endswith((".png", ".jpg", ".jpeg", ".bmp")): continue img_path = os.path.join(SRC_DIR, fname) crop_and_save(img_path, DST_DIR) print("\n[INFO] 所有图片裁剪完成")