首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将图像(np.array)转换为二进制图像

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

Stack Overflow用户
提问于 2016-11-06 21:18:58
回答 3查看 21.8K关注 0票数 4

感谢您阅读我的问题。

我是python的新手,开始对scipy感兴趣。我正在尝试弄清楚如何将Racoon的图像(在scipy misc中)转换为二进制一(黑色,白色)。在scipy-lecture教程中没有讲授这一点。

到目前为止,我的代码如下:

代码语言:javascript
复制
%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。有没有办法确定这一点?

EN

回答 3

Stack Overflow用户

发布于 2018-07-23 08:19:32

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

代码语言:javascript
复制
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)

输入:

输出:

票数 4
EN

Stack Overflow用户

发布于 2016-11-06 22:56:51

你想得太多了:

代码语言:javascript
复制
def to_binary(img, lower, upper):
    return (lower < img) & (img < upper)

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

票数 2
EN

Stack Overflow用户

发布于 2016-11-06 22:57:15

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

代码语言:javascript
复制
# 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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40449781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档