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

如何使用ImageMagick将单色图像转换为0和1的n×m数组?

使用ImageMagick将单色图像转为0/1矩阵文本文件

问题背景

我已通过以下命令将彩色JPG图像转换为单色图像:

convert image.jpg -monochrome monochrome.jpg

现在希望将monochrome.jpg转换为n×m数组格式的文本文件,要求黑色像素用1表示、白色像素用0表示(反之亦可)。尝试了如下命令:

convert monochrome_800x480.jpg -depth 1 -format 'txt' monochrome.txt

但输出并非预期的0和1矩阵,而是包含像素详细信息的内容:

# ImageMagick pixel enumeration: 800,480,0,255,gray
0,0: (255)  #FFFFFF  gray(255)
1,0: (255)  #FFFFFF  gray(255)
2,0: (255)  #FFFFFF  gray(255)
...

解决方法

完全可以通过ImageMagick实现需求,以下是几种可行的命令方案:

方案1:直接用ImageMagick内置表达式生成矩阵

convert monochrome.jpg -format "%[fx:pixel.r==0?1:0]" -write info:- -delete 0--1 -format "%[fx:w]x%[fx:h]\n" info:- | tr -d '\n' | fold -w $(identify -format "%w" monochrome.jpg) > matrix.txt
  • 逻辑:%[fx:pixel.r==0?1:0]遍历每个像素,将黑色(红色通道值为0)转为1,白色(红色通道值为255)转为0;fold -w根据图像宽度自动换行,保证每行对应图像的一行像素。

方案2:结合awk处理像素输出

convert monochrome.jpg txt:- | awk 'NR>1 {print ($3 == "(0)") ? 1 : 0}' | paste -sd "\n" - | fold -w $(identify -format "%w" monochrome.jpg) > matrix.txt
  • 逻辑:用txt:-输出像素信息后,跳过第一行注释,通过awk判断像素值,将黑色像素(值为(0))替换为1,白色替换为0,最后按图像宽度换行。

方案3:利用PGM格式快速转换

convert monochrome.jpg -depth 1 -compress none pgm:- | tail -n +3 | tr ' \n' '' | fold -w $(identify -format "%w" monochrome.jpg) > matrix.txt
  • 逻辑:将单色图像转为深度1的无压缩PGM格式,该格式头部后直接存储0/1像素值,去掉头部两行后整理成矩阵格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:57:47