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

如何简易识别两张截图的重叠区域以完成拼接?

针对固定宽度截图的简便拼接方案

你的场景(两张宽度一致、存在近似重叠/渐变重叠的截图拼接)不需要用到OpenCV这类重型工具,以下是两种轻量可行的实现方案:

方案一:用Python Pillow库实现核心逻辑

Pillow是轻量的图像处理库,完全能满足你的需求,核心思路是滑动窗口+模糊像素比对,可应对渐变导致的非精确重叠:

实现步骤

  1. 加载两张截图,可先校验宽度是否一致(你的场景可跳过,但建议保留作为容错逻辑)
  2. 从第一张图的下半区域和第二张图的上半区域开始,逐块比对像素相似度
  3. 设定一个相似度阈值(比如80%),找到最接近阈值的重叠位置
  4. 裁剪掉第二张图的重叠部分,将两张图垂直拼接

示例代码

from PIL import Image
import numpy as np

def find_overlap_height(img1, img2, threshold=0.8):
    # 转为numpy数组方便计算
    arr1 = np.array(img1)
    arr2 = np.array(img2)
    img_width = arr1.shape[1]
    # 限定比对范围:最多比对每张图1/3高度的区域
    max_check_height = min(arr1.shape[0], arr2.shape[0]) // 3
    
    best_overlap = 0
    best_score = 0
    
    for overlap_h in range(1, max_check_height + 1):
        # 取img1的底部overlap_h区域,img2的顶部overlap_h区域
        block1 = arr1[-overlap_h:, :]
        block2 = arr2[:overlap_h, :]
        # 计算像素相似度(用平均颜色差的反向值)
        color_diff = np.mean(np.abs(block1 - block2))
        similarity = 1 - (color_diff / 255)
        if similarity > best_score and similarity >= threshold:
            best_score = similarity
            best_overlap = overlap_h
    return best_overlap

def stitch_screenshots(img1_path, img2_path, output_path):
    img1 = Image.open(img1_path).convert('RGB')
    img2 = Image.open(img2_path).convert('RGB')
    
    overlap_h = find_overlap_height(img1, img2)
    if overlap_h == 0:
        # 未找到重叠,直接拼接(可根据需求调整逻辑)
        stitched = Image.new('RGB', (img1.width, img1.height + img2.height))
        stitched.paste(img1, (0, 0))
        stitched.paste(img2, (0, img1.height))
    else:
        # 裁剪img2的重叠部分,拼接
        stitched_height = img1.height + img2.height - overlap_h
        stitched = Image.new('RGB', (img1.width, stitched_height))
        stitched.paste(img1, (0, 0))
        stitched.paste(img2.crop((0, overlap_h, img2.width, img2.height)), (0, img1.height))
    
    stitched.save(output_path)

# 调用示例
stitch_screenshots("UKhA1.png", "CKXjd.png", "stitched_result.png")

方案二:ImageMagick结合简单脚本实现

你之前没找到ImageMagick的直接功能,但可以用它的基础命令配合脚本(比如bash/python)先计算重叠高度,再拼接:

  1. 用convert命令将图片转为像素数据,提取顶部/底部区域的颜色统计
  2. 比对颜色分布找到重叠位置
  3. 用convert img1.png img2.png -append -crop WxH+0+0(W为图片宽度,H为总高度减去重叠高度)完成拼接

这种方案适合偏好命令行工具的场景,核心还是先通过简单的颜色比对确定重叠区域,再调用ImageMagick的拼接命令。

这两种方案都比OpenCV轻量,完全适配你的简单场景,不需要全景照片的复杂特征匹配逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:33:59