【问题标题】:Convert an image array to a binarized image将图像数组转换为二值化图像
【发布时间】:2018-01-03 05:15:58
【问题描述】:

我有一个图像数组Indice,如下所示:

array([[158,   0, 252, ..., 185, 186, 187],
   [254, 253, 252, ..., 188, 188, 189],
   [247, 249, 252, ..., 188, 187, 186],
   ..., 
   [176, 172, 168, ..., 204, 205, 205],
   [178, 175, 172, ..., 206, 205, 206],
   [180, 177, 174, ..., 206, 207, 207]], dtype=uint8)

我想将Indice 转换为阈值接近 0(0.1 或 0.2)的二值化图像(值介于 0 和 1 之间)。我怎样才能在 Python 中做到这一点?

【问题讨论】:

标签: python arrays image binary


【解决方案1】:

您可以使用np.where将数据除以255转换为0到1的范围后进行二值化

threshold = 0.2
new_indice = np.where(Indice/255>=threshold, 1, 0)

【讨论】:

    【解决方案2】:

    如果布尔二进制数组适合您,您可以简单地使用 numpy 的逐元素比较:

    new_indice = (Indice/255 > threshold)
    

    事实上,对于随机测试数组,这似乎比np.where 解决方案稍快。如果你需要一个整数二进制数组,你可以简单地在括号前添加一个1*,但这样速度优势似乎就消失了。

    【讨论】:

      【解决方案3】:

      执行此类任务的一种简单方法是使用list comprehensions

      在你的情况下:

      array([[1 if x>threshold else 0 for x in line] for line in Indice])
      

      threshold 将设置为您想要的值。

      【讨论】:

      • 他的起始数组是8位整数,不是浮点数
      • 看起来他正在使用一个 numpy 数组。遍历数组通常不是一个好方法。
      • @James 是的,没错。有什么更好的方法?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 2012-02-07
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2015-01-20
      • 2013-07-04
      相关资源
      最近更新 更多