将布尔值numpy数组转换为枕头图像 [英] Convert boolean numpy array to pillow image
问题描述
我目前正在使用scikit-image库在python中进行图像处理.我正在尝试使用sauvola阈值并通过以下代码制作二进制图像:
I'm currently working with image processing in python using the scikit-image library. I'm trying to make a binary image using sauvola thresholding with the following code:
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
给出以下结果:
输出是一个numpy数组,该图像的数据类型是布尔
the output is a numpy array with data type of this image is a 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图像:
The problem is that I need to convert this array back to a PIL image using the following line of code:
image = Image.fromarray(binary_sauvola)
这使图像看起来像这样:
which makes the image look like this:
我还尝试将数据类型从bool更改为uint8,但随后会出现以下异常:
I also tried to change the data type from bool to uint8 but then I'll get the following exception:
AttributeError: 'numpy.ndarray' object has no attribute 'mask'
到目前为止,我还没有找到获得类似于阈值结果的PIL图像的解决方案.
So far I haven't found a solution to get a PIL image which looks like the result of the thresholding.
推荐答案
更新
此错误现已在Pillow == 6.2.0中解决. GitHub上该问题的链接是此处.
如果您无法更新到新版本的Pillow,请参见下文.
If you cannot update to the new version of Pillow, please see below.
PIL的Image.fromarray
函数存在模式为"1"图像的错误. 此要点演示了该错误,并给出了一些解决方法.以下是最佳的两种解决方法:
PIL's Image.fromarray
function has a bug with mode '1' images. This Gist demonstrates the bug, and shows a few workarounds. Here are the best two workarounds:
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)
这篇关于将布尔值numpy数组转换为枕头图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!