首页 > 解决方案 > 将灰度图像转换为具有可定义阈值的 1 位黑/白,保持透明度?

问题描述

如何将灰度图像转换为具有可定义阈值的 1 位黑/白,但保持现有的透明度/alpha?

现有问题错过了我问题的透明度部分。

另外,我需要在 macOS 的命令行上执行此操作。ImageMagickconvert是一种选择,但不是唯一的选择。

示例图片: 灰度图像

要求的行为:

  1. 低于可定义阈值的像素为黑色
  2. 高于可定义阈值的像素为白色
  3. 透明像素保持不变

我手动准备了这个“目标”图像:

目标

我试过的:

  1. $ convert -threshold 50% in.png out.png

    • 超过阈值的所有东西都变成白色
    • 低于阈值的一切都变得透明!
  2. $ convert -white-threshold 50% in.png out.png

    • 超过阈值的所有东西都变成白色
    • 低于阈值的一切都变得透明!
  3. $ convert -black-threshold 50% in.png out.png

    • 超过不同阈值的所有东西都变成白色
    • 什么都不会变黑!
  4. $ convert +dither -monochrome in.png out.png

    • 抖动禁用
    • 1 位转换锁定到 50%,但按预期执行
    • 但是:透明像素变黑了!
  5. $ convert -depth 1 -colors 3 -alpha set in.png out.png

    • 差不多好了
    • 但是:阈值无法定义!

任何想法表示赞赏!

图片参考: http: //www.studentshow.com/gallery/6097929/Pyramid-Module-Value-Grayscale

标签: command-linegraphicsimagemagick-convert

解决方案


这适用于 IM 6.9.11.34 Q16 Mac OSX Sierra。

在此处输入图像描述

convert in.png -colorspace gray -channel rgb -threshold 50% +channel out.png

(在上面,您指定阈值应仅应用于 rgb 通道,而不是通过 -channel rgb 的 alpha。在阈值之后,我再次打开所有通道)

在此处输入图像描述


推荐阅读