【问题标题】:Convert boolean numpy array to pillow image将布尔 numpy 数组转换为枕头图像
【发布时间】:2020-12-21 15:11:04
【问题描述】:

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

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 图像。

【问题讨论】:

  • “我也尝试将数据类型从 bool 更改为 uint8”,请展示一下尝试。它显然没有使用viewastype,所以真的不确定你做了什么。
  • 我尝试了以下行将 dtype 更改为 uint8 image = Image.fromarray(binary_sauvola.astype('uint8'))
  • 然后显示堆栈跟踪。这个错误似乎很奇怪。请编辑问题。如果可以避免,请不要将牛和错误放入 cmets。

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


【解决方案1】:

更新

此错误现已在 Pillow==6.2.0 中得到解决。 GitHub上问题的链接是here

如果您无法更新到 Pillow 的新版本,请参阅下文。


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

【讨论】:

  • img_grey 没有给我正确的结果,但 img_frombytes 可以。非常感谢您的回答
  • @R.hagens 我的荣幸!有趣的是img_grey 对你的行为不端。我不确定为什么会发生这种情况,大约一年前我对这个主题进行了研究,但我忘记了细节。但我更喜欢img_frombytes,因为我写了它。 :)
  • 如果你有兴趣,img_grey 给了我以下结果imgur.com/a/VC3yqs4
  • @R.hagens 谢谢。它本质上是相同的错误,但我必须考虑为什么尽管img_grey 进行了灰度转换,它仍然会发生。
  • 这个问题已经在最新的pillow==6.2.0中解决了。 github上问题的链接:github.com/python-pillow/Pillow/issues/3109
【解决方案2】:

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

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

似乎可以解决问题。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 2022-01-20
    • 2014-12-20
    • 1970-01-01
    • 2018-08-22
    • 2017-06-25
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多