将图像(np.array)转换为二值图像

新手上路,请多包涵

感谢您阅读我的问题。

我是 python 的新手,对 scipy 很感兴趣。我想弄清楚如何将 Racoon 的图像(在 scipy misc 中)制作成二进制图像(黑色,白色)。这在 scipy-lecture 教程中没有讲授。

到目前为止,这是我的代码:

 %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc  #here is how you get the racoon image

face = misc.face()
image = misc.face(gray=True)
plt.imshow(image, cmap=plt.cm.gray)
print image.shape

def binary_racoon(image, lowerthreshold, upperthreshold):
    img = image.copy()
    shape = np.shape(img)

    for i in range(shape[1]):
        for j in range(shape[0]):
             if img[i,j] < lowerthreshold and img[i,j] > upperthreshold:
                 #then assign black to the pixel
             else:
                 #then assign white to the pixel

    return img

    convertedpicture = binary_racoon(image, 80, 100)
    plt.imshow(convertedpicture, cmap=plt.cm.gist_gray)

我见过其他人使用 OpenCV 制作图片二进制文件,但我想知道如何通过遍历像素以这种方式做到这一点?我不知道给上限和下限阈值赋予什么值,所以我猜了80和100。这也有办法确定吗?

原文由 User12049279432 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 730
1 个回答

如果其他人正在寻找一个快速的最小示例来进行试验,这里是我用来对图像进行二值化的方法:

 from scipy.misc import imread, imsave

# read in image as 8 bit grayscale
img = imread('cat.jpg', mode='L')

# specify a threshold 0-255
threshold = 150

# make all pixels < threshold black
binarized = 1.0 * (img > threshold)

# save the binarized image
imsave('binarized.jpg', binarized)

输入:

在此处输入图像描述

输出:

在此处输入图像描述

原文由 duhaime 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题