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

6
感谢您阅读我的问题。
我是 Python 的新手,对 Scipy 很感兴趣。我正在尝试找出如何将 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。是否还有其他确定值的方法?


你为什么会期望 lowerthreshold > img[i,j] and img[i,j] > upperthreshold 会是 True 呢?这意味着 80 > 100 - Eric
3个回答

4

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

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)

输入:

输入图像描述

输出:

输出图像描述


3

你想得太多了:

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

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

啊,我还发现如果我想继续我的方向,我必须使用“或”。 - User12049279432

1
你不需要迭代图像数组的x和y位置。使用numpy数组检查数组是否在感兴趣的阈值之上或之下。这里是一些代码,产生一个布尔(真/假)数组作为黑白图像。
# 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接