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

基于ImageMagick 7裁剪不规则内嵌图为最大规整矩形

在Windows系统用ImageMagick 7裁剪倾斜内嵌图的实现方案

完全可以实现,核心思路是先区分白色边框和内嵌图区域,再计算内嵌图内部的最大轴对齐矩形,最后执行裁剪。以下是具体步骤和脚本:

步骤说明

  1. 生成二值掩码:将原图中的白色边框与内嵌图区域区分开,生成黑白掩码图(内嵌图为白色,边框为黑色)。
  2. 计算边界坐标:遍历掩码图的每一行和每一列,确定最大轴对齐矩形的四个边界(左、右、上、下)。
  3. 执行裁剪:根据计算出的边界,裁剪原图得到目标矩形。

PowerShell脚本实现

将以下代码保存为crop_inner_rect.ps1,替换input.jpg和output.jpg为你的实际文件路径,运行脚本即可:

# 配置文件路径
$inputFile = "input.jpg"
$outputFile = "output.jpg"
$tempMask = "temp_mask.png"

# 生成掩码图:调整-fuzz值适配白色深浅,阈值可根据实际情况修改
magick $inputFile -fuzz 15% -threshold 90% $tempMask

# 获取图片宽高
$dim = magick $tempMask -format "%w %h" info:
$width = [int]($dim -split " ")[0]
$height = [int]($dim -split " ")[1]

# 计算左边界:所有行中第一个非白像素的最大X坐标
$left = 0
for ($y=0; $y -lt $height; $y++) {
    $currX = magick $tempMask -crop ${width}x1+0+$y -format "%[fx:minima.x]" info:
    if ([int]$currX -gt $left) { $left = [int]$currX }
}

# 计算右边界:所有行中最后一个非白像素的最小X坐标
$right = $width
for ($y=0; $y -lt $height; $y++) {
    $currX = magick $tempMask -crop ${width}x1+0+$y -format "%[fx:maxima.x]" info:
    if ([int]$currX -lt $right) { $right = [int]$currX }
}

# 计算上边界:所有列中第一个非白像素的最大Y坐标
$top = 0
for ($x=0; $x -lt $width; $x++) {
    $currY = magick $tempMask -crop 1x${height}+$x+0 -format "%[fx:minima.y]" info:
    if ([int]$currY -gt $top) { $top = [int]$currY }
}

# 计算下边界:所有列中最后一个非白像素的最小Y坐标
$bottom = $height
for ($x=0; $x -lt $width; $x++) {
    $currY = magick $tempMask -crop 1x${height}+$x+0 -format "%[fx:maxima.y]" info:
    if ([int]$currY -lt $bottom) { $bottom = [int]$currY }
}

# 执行裁剪
magick $inputFile -crop ($right - $left)x($bottom - $top)+$left+$top $outputFile

# 清理临时文件
Remove-Item $tempMask

参数调整提示

  • -fuzz值:如果原图白色边框不是纯白,可调整-fuzz 15%的百分比(比如10%-20%),确保能正确识别所有白色区域。
  • -threshold值:配合fuzz使用,调整阈值让掩码图的黑白区分更准确。

这个方案适配横竖版图片,无论内嵌图倾斜角度、比例如何,都能计算出内部最大的规整矩形并完成裁剪。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:16:30