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

标签 python numpy

感谢您阅读我的问题。

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

最佳答案

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

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

关于python - 将图像(np.array)转换为二值图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449781/

相关文章:

python - 减少 python 中的循环

python - 用零替换 numpy 数组中低于阈值 # 的数字

numpy - 为向量矩阵 v 计算 "v^T A v"

numpy - 如何从 numpy 结构化数组中获取 dtypes 列表?

python - 将循环的结果分配给 Python 中的变量

python - 在 shell 中工作但不作为程序工作?

python - 带有隐藏窗口的跨平台子进程

python - CPP和Python CSV Precision

python - 查找与完整集具有相似均值的子集

python - 如何使用 Python 从电子邮件内容中获取附加的 eml 文件?