如何使用Python裁剪不同尺寸图片的指定区域并生成新图片
批量定位裁剪指定区域Python脚本
依赖安装
首先安装所需的第三方库:
pip install opencv-python pillow numpy
实现逻辑
采用多尺度模板匹配算法,以你已有的裁剪后效果图作为匹配模板,可自动在不同尺寸的原始图片中定位到目标区域的准确位置,完成自动裁剪输出。
完整脚本代码
import cv2 import os import numpy as np # -------------------------- 可修改参数区域 -------------------------- # 模板文件路径:替换为你自己的裁剪后效果图路径 TEMPLATE_PATH = "template.jpg" # 待处理原始图片存放文件夹 INPUT_DIR = "./input" # 裁剪后图片输出文件夹 OUTPUT_DIR = "./output" # 匹配阈值,取值0-1,数值越高匹配精度要求越高,误匹配率越低 MATCH_THRESHOLD = 0.8 # 缩放检测范围:0.5代表缩小到原图50%,2代表放大到原图200%,可根据实际情况调整 SCALE_RANGE = (0.5, 2.0) # 缩放步长,步长越小检测越精细,速度越慢 SCALE_STEP = 30 # ------------------------------------------------------------------- # 加载灰度模板 template = cv2.imread(TEMPLATE_PATH, 0) if template is None: raise FileNotFoundError(f"模板文件{TEMPLATE_PATH}不存在,请检查路径") tpl_height, tpl_width = template.shape[:2] # 创建输出目录 os.makedirs(OUTPUT_DIR, exist_ok=True) # 遍历所有待处理图片 for filename in os.listdir(INPUT_DIR): # 跳过非图片文件 if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')): continue img_path = os.path.join(INPUT_DIR, filename) # 读取原始图片 origin_img = cv2.imread(img_path) if origin_img is None: print(f"文件{filename}不是有效图片,跳过") continue # 转灰度图用于匹配 gray_img = cv2.cvtColor(origin_img, cv2.COLOR_BGR2GRAY) best_score = -1 best_location = None best_scale = 1.0 # 多尺度遍历匹配 for scale in np.linspace(SCALE_RANGE[0], SCALE_RANGE[1], SCALE_STEP)[::-1]: # 按比例缩放当前图片 resized_gray = cv2.resize(gray_img, (int(gray_img.shape[1] * scale), int(gray_img.shape[0] * scale)), interpolation=cv2.INTER_AREA) # 缩放后的图片比模板还小就停止缩小 if resized_gray.shape[0] < tpl_height or resized_gray.shape[1] < tpl_width: break # 计算缩放比例 resize_ratio = gray_img.shape[1] / float(resized_gray.shape[1]) # 模板匹配 match_result = cv2.matchTemplate(resized_gray, template, cv2.TM_CCOEFF_NORMED) _, max_val, _, max_loc = cv2.minMaxLoc(match_result) # 记录最优匹配结果 if max_val > best_score: best_score = max_val best_location = max_loc best_scale = resize_ratio # 匹配度达标则裁剪 if best_score >= MATCH_THRESHOLD: x_start = int(best_location[0] * best_scale) y_start = int(best_location[1] * best_scale) x_end = int((best_location[0] + tpl_width) * best_scale) y_end = int((best_location[1] + tpl_height) * best_scale) # 裁剪图片 cropped_img = origin_img[y_start:y_end, x_start:x_end] # 保存结果 cv2.imwrite(os.path.join(OUTPUT_DIR, filename), cropped_img) print(f"图片{filename}处理完成") else: print(f"图片{filename}未匹配到目标区域,匹配度{best_score:.2f},已跳过")
使用步骤
- 将任意一张已裁剪好的目标效果图保存为
template.jpg,和脚本放在同一目录下 - 新建名为
input的文件夹,把所有需要裁剪的原始图片都放入该文件夹 - 运行脚本,裁剪完成的图片会自动输出到自动生成的
output文件夹中 - 若出现误匹配或者漏匹配的情况,可根据实际情况调整脚本开头的匹配阈值、缩放范围等参数
内容的提问来源于stack exchange,提问作者Abdul Moiz
相关产品推荐
相关产品推荐

