python – 将boolean numpy数组转换为枕头图像
发布时间:2020-12-20 11:04:19 所属栏目:Python 来源:网络整理
导读:我目前正在使用scikit-image库在 python中处理图像处理.我正在尝试使用索沃拉阈值使用以下代码制作二进制图像: from PIL import Imageimport numpyfrom skimage.color import rgb2grayfrom skimage.filters import threshold_sauvolaim = Image.open("test.
我目前正在使用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) 另见Error Converting PIL B&W images to Numpy Arrays. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |