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

我目前正在使用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

这给出了以下结果:

输出是一个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)

这使得图像看起来像这样:

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

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

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

最佳答案 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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值