Ira*_*ris 3 command-line imagemagick image-processing
你好!我想从透明图像中删除所有出现的杂散像素。
下面是一个示例图像,为方便起见放大:
以下是相同的图像,但我希望它在处理后看起来如何:
我能想到的描述我想要实现的最佳方式是应该删除周围像素完全透明的每个像素。把选择器想象成一个 3x3 的网格,网格的中间是操作的像素。
我查看了 IM 手册中的Morphology,但它似乎没有为此提供足够好的方法。
ImageMagick 可以做到这一点吗?如果没有,是否还有其他命令行软件可以实现这一点?
在 Imagemagick 中,您可以使用 -connected-components 来移除那些孤立的像素块。它们的一侧似乎是 5x5 像素。所以我们将面积阈值保持在 26。我们删除 alpha 通道中的那些块,然后在图像中替换它。(请注意,我们需要使用 8-connected 与 4-connected 区域检测来保留您的其他区域)。
既然你说你的图像被放大了,所以我假设你的孤立区域是 1x1 像素。因此,将 area-threshold 更改为 2,以删除单个像素区域。
输入:
Unix 语法:
convert img.png \
\( -clone 0 -alpha extract -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:area-threshold=26 \
-connected-components 8 \) \
-alpha off -compose copy_opacity -composite \
result.png
Run Code Online (Sandbox Code Playgroud)
Windows 语法:
convert img.png ^
( -clone 0 -alpha extract -type bilevel ^
-define connected-components:mean-color=true ^
-define connected-components:area-threshold=26 ^
-connected-components 8 ) ^
-alpha off -compose copy_opacity -composite ^
result.png
Run Code Online (Sandbox Code Playgroud)
添加:
如果您只想删除小的孤立彩色像素而不是彩色像素内的任何透明像素,那么没有简单的方法可以做到这一点。这是我想要的增强功能。但是,这是可以做到的。
这是您修改后的图像,以便左上角的红色块具有单个透明的中心像素。我在其右侧添加了一条红线,以确保当中心变为透明时它大于 25 像素,以便您可以看到哪个像素具有透明中心。您必须下载并放大此图像才能看到丢失的像素。
4 倍变焦:
方法是在alpha通道中找到所有的白色区域,然后将所有小于26像素的区域做一个列表。然后重新处理图像以通过 ID 删除这些区域。
获取 ID 列表
id_list=""
OLDIFS=$IFS
IFS=$'\n'
arr=(`convert img2.png -alpha extract -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:verbose=true \
-connected-components 8 null: | grep "gray(255)" | sed 's/^[ ]*//'`)
echo "${arr[*]}"
num=${#arr[*]}
IFS=$OLDIFS
for ((i=0; i<num; i++)); do
id=`echo "${arr[$i]}" | cut -d' ' -f1 | sed 's/[:]*$//'`
count=`echo "${arr[$i]}" | cut -d' ' -f4`
if [ $count -lt 26 ]; then
id_list="$id_list $id"
fi
done
echo "$id_list"
Run Code Online (Sandbox Code Playgroud)
这是打印的内容
12: 5x5+120+70 122.0,72.0 25 gray(255)
14: 5x5+30+85 32.0,87.0 25 gray(255)
15: 5x5+110+85 112.0,87.0 25 gray(255)
16: 5x5+75+90 77.0,92.0 25 gray(255)
17: 5x5+40+100 42.0,102.0 25 gray(255)
18: 5x5+110+110 112.0,112.0 25 gray(255)
19: 5x5+140+110 142.0,112.0 25 gray(255)
21: 5x5+15+130 17.0,132.0 25 gray(255)
22: 5x5+40+140 42.0,142.0 25 gray(255)
23: 5x5+85+140 87.0,142.0 25 gray(255)
24: 5x5+120+140 122.0,142.0 25 gray(255)
2: 5x5+55+5 57.0,7.0 25 gray(255)
5: 5x5+100+20 102.0,22.0 25 gray(255)
7: 5x5+65+30 67.0,32.0 25 gray(255)
8: 5x5+125+30 127.0,32.0 25 gray(255)
9: 5x5+105+50 107.0,52.0 25 gray(255)
11: 5x5+25+65 27.0,67.0 25 gray(255)
12 14 15 16 17 18 19 21 22 23 24 2 5 7 8 9 11
Run Code Online (Sandbox Code Playgroud)
重新处理以按 ID 删除区域
convert img2.png \
\( -clone 0 -alpha extract -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:remove="$id_list" \
-connected-components 8 -background black -flatten +write tmp.png \) \
-alpha off -compose copy_opacity -composite \
result2.png
Run Code Online (Sandbox Code Playgroud)
4 倍变焦: