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

时间:2016-11-06 13:18:58

标签: python numpy

感谢您阅读我的问题。

我是python的新手并且对scipy感兴趣。我试图弄清楚如何将浣熊(在scipy misc中)的图像变成二进制(黑色,白色)。这在scipy讲座教程中没有教授。

这是我的代码:

%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.还有办法确定吗?

3 个答案:

答案 0 :(得分:2)

你过分思考这个:

def to_binary(img, lower, upper):
    return (lower < img) & (img < upper)

numpy中,比较运算符按元素方式应用于整个数组。请注意,您必须使用&而不是and来组合布尔值,因为python不允许numpy重载and

答案 1 :(得分:1)

您不需要迭代图像数组的x和y位置。使用numpy数组检查数组是否高于感兴趣的阈值。下面是一些生成布尔(true / false)数组的代码作为黑白图像。

# use 4 different thresholds
thresholds = [50,100,150,200]

# create a 2x2 image array
fig, ax_arr = plt.subplots(2,2)

# iterate over the thresholds and image axes
for ax, th in zip(ax_arr.ravel(), thresholds):
    # bw is the black and white array with the same size and shape
    # as the original array.  the color map will interpret the 0.0 to 1.0 
    # float array as being either black or white.
    bw = 1.0*(image > th)
    ax.imshow(bw, cmap=plt.cm.gray)
    ax.axis('off')

# remove some of the extra white space
fig.tight_layout(h_pad=-1.5, w_pad=-6.5)

enter image description here

答案 2 :(得分:0)

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

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)

输入:

enter image description here

输出:

enter image description here