You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用OpenCV或PIL自动识别目标矩形并实现跨分辨率截图裁剪

解决方案

完全可以通过OpenCV的轮廓识别功能自动定位视频播放框区域,适配不同分辨率的显示器截图,全程保留图像彩色属性,不需要固定裁剪坐标。

实现原理

Youtube播放框是截图中面积最大的规则矩形区域,通过以下步骤可自动定位:

  • 将彩色图像转为灰度图后做边缘检测,过滤背景冗余信息
  • 查找所有轮廓,筛选出面积最大、符合常规视频长宽比的四边形轮廓
  • 获取该轮廓的外接矩形坐标,直接在原彩色图像上完成裁剪

完整可运行代码

首先安装依赖:pip install opencv-python pillow

代码如下:

import os
import random
import cv2
import numpy as np
from PIL import Image

# 自动创建输出文件夹,不存在就新建
os.makedirs("newdir", exist_ok=True)

# 支持的图像格式
SUPPORTED_EXTS = (".jpg", ".jpeg", ".png")

def get_video_roi_coords(img_path):
    # 读取图像
    cv_img = cv2.imread(img_path)
    if cv_img is None:
        return None
    height, width = cv_img.shape[:2]
    # 转灰度图做边缘检测
    gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 150)
    # 膨胀操作连接断开的边缘
    kernel = np.ones((5,5), np.uint8)
    edges = cv2.dilate(edges, kernel, iterations=1)
    # 查找所有轮廓并按面积从大到小排序
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)
    
    target_rect = None
    for cnt in contours:
        # 拟合轮廓为规则形状
        epsilon = 0.02 * cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)
        # 筛选四边形、面积和长宽比符合视频特征的区域
        if len(approx) == 4:
            x, y, w, h = cv2.boundingRect(approx)
            area_ratio = (w*h)/(width*height)
            aspect_ratio = w / h
            # 适配16:9、9:16、4:3等常见视频比例,误差范围10%
            if 0.3 < area_ratio < 0.95 and (1.2 < aspect_ratio < 1.9 or 0.5 < aspect_ratio < 0.85):
                target_rect = (x, y, x+w, y+h)
                break
    return target_rect

for filename in os.listdir():
    ext = os.path.splitext(filename)[1].lower()
    if ext not in SUPPORTED_EXTS:
        print(f'Passed by {filename}! It is not an image!')
        continue
    roi_coords = get_video_roi_coords(filename)
    if not roi_coords:
        print(f"Failed to find video area in {filename}")
        continue
    # 用PIL裁剪原彩色图,保留原有色彩属性
    img = Image.open(filename)
    cropped_img = img.crop(roi_coords)
    # 随机命名保存
    save_name = hex(random.randint(100000,500000)) + ext
    cropped_img.save(os.path.join("newdir", save_name))

可调参数说明

如果出现识别不准的情况,可以调整以下参数适配你的场景:

  • 边缘检测的Canny阈值:默认是50、150,数值越高识别的边缘越少,适合背景复杂的场景
  • 面积占比阈值0.3 < area_ratio < 0.95:如果视频框在截图中占比特别小,可以调低0.3的下限
  • 长宽比范围:如果是特殊比例的视频,可以调整aspect_ratio的判断区间

内容的提问来源于stack exchange,提问作者Peter Nielsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 06:06:02