将图像(np.数组)转换为二进制imag

2024-09-25 00:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你阅读我的问题。

我是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。还有办法确定吗?


Tags: the图像imageimportimgmatplotlibas二进制
3条回答

不需要迭代图像数组的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

你想得太多了:

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

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

如果其他人正在寻找一个简单的例子来进行实验,下面是我用来对图像进行二值化的方法:

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

相关问题 更多 >