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

python – 将boolean numpy数组转换为枕头图像,第1张

概述我目前正在使用scikit-image库在 python中处理图像处理.我正在尝试使用索沃拉阈值使用以下代码制作二进制图像: from PIL import Imageimport numpyfrom skimage.color import rgb2grayfrom skimage.filters import threshold_sauvolaim = Image.open("tes 我目前正在使用scikit-image库在 python中处理图像处理.我正在尝试使用索沃拉阈值使用以下代码制作二进制图像:

from PIL import Imageimport numpyfrom skimage.color import rgb2grayfrom skimage.filters import threshold_sauvolaim = Image.open("test.jpg")pix = numpy.array(im)img = rgb2gray(pix)window_size = 25thresh_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 npfrom 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_greydef 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.

总结

以上是内存溢出为你收集整理的python – 将boolean numpy数组转换为枕头图像全部内容,希望文章能够帮你解决python – 将boolean numpy数组转换为枕头图像所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1192037.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存