将boolean numpy数组转换为枕头图像

时间:2018-05-02 12:16:06

标签: python numpy image-processing python-imaging-library scikit-image

我目前正在使用scikit-image库在python中处理图像处理。我正在尝试使用索沃拉阈值使用以下代码制作二进制图像:

from PIL import Image
import numpy
from skimage.color import rgb2gray
from skimage.filters import threshold_sauvola

im = Image.open("test.jpg")
pix = numpy.array(im)
img = rgb2gray(pix)

window_size = 25
thresh_sauvola = threshold_sauvola(img, window_size=window_size)
binary_sauvola = img > thresh_sauvola

其中给出以下结果: enter image description here

输出是一个numpy数组,该图像的数据类型是bool

[[ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 ...
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]
 [ True  True  True ...  True  True  True]]

问题是我需要使用以下代码行将此数组转换回PIL图像:

image = Image.fromarray(binary_sauvola)

使图像看起来像这样:

enter image description here

我也尝试将数据类型从bool更改为uint8但是我会得到以下异常:

AttributeError: 'numpy.ndarray' object has no attribute 'mask'

到目前为止,我还没有找到一个解决方案来获取看起来像阈值结果的PIL图像。

2 个答案:

答案 0 :(得分:7)

PIL的Image.fromarray功能存在模式错误' 1'图片。 This Gist演示了该错误,并展示了一些解决方法。以下是最好的两种解决方法:

import numpy as np
from PIL import Image

# The standard work-around: first convert to greyscale 
def img_grey(data):
    return Image.fromarray(data * 255, mode='L').convert('1')

# Use .frombytes instead of .fromarray. 
# This is >2x faster than img_grey
def img_frombytes(data):
    size = data.shape[::-1]
    databytes = np.packbits(data, axis=1)
    return Image.frombytes(mode='1', size=size, data=databytes)

另见Error Converting PIL B&W images to Numpy Arrays

答案 1 :(得分:1)

此选项可能在 2018 年不可用,但目前

from skimage.io._plugins.pil_plugin import ndarray_to_pil, pil_to_ndarray
ndarray_to_pil(some_binary_image).convert("1")

似乎可以解决问题。