本文介绍了奇怪的PIL.Image.fromarray行为,在模式='1'中具有numpy零和1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该有些困惑.

根据PIL文档,它具有不同的图像模式(如1,L,8,RGB,RGBA等),但是我对模式'1'(1位像素,黑白)存储有兴趣每字节一个像素).

我创建了2个尺寸为100乘100的矩阵:第一个只有零(np.zeros),第二个只有一个(np.ones),在模式'1'下,期望全黑图像带有1,白色图像带有零.仅限黑白图像.

结果图片

问题:我在做什么错了?

UPD.我试过使用np.dtype uint8,但没有成功:

最终可接受的UPD:似乎有一个PIL错误,有一段时间没有修复,因此您应该使用工作区以这种方式创建白色矩形.奇怪,但现在我什至不知道什么模式'1'甚至意味着:D

解决方案

关于原始问题,这是适用于我的最短版本:

  Image.fromarray(255 * np.ones((100,100),np.uint8),'1') 

我得到了正确的全白图像.

当足够小时,抖动图像看起来很像普通的灰度图像.禁用抖动后(右图),您实际上会得到一个阈值图像,其中所有> = 128的值都设置为白色,否则设置为黑色.

希望有帮助!

  -----------------------系统信息-----------------------的Python:3.8.1Matplotlib:3.2.0rc1装箱数:1.18.1枕头:7.0.0----------------------- 

There should be some kinda puzzle for me.

Accordingly to PIL documentation it has different image modes (as 1, L, 8, RGB, RGBA, and so on), but I was interested about mode '1' (1-bit pixels, black and white, stored with one pixel per byte).

I've created 2 matrices size 100 by 100: first only zeroes (np.zeros) and second only ones (np.ones), expecting totally black image with ones, and white image with zeros in mode '1' for Black and White image only.

Picture of result

Question: what I'm doing wrong?

UPD. i've tried using np.dtype uint8, didn't worked:

Final acceptable UPD:Seem there is a PIL bug, what wasn't fixed for some time, so then you should be using a workarond to create a white rectangle that way. Strange but now I'm not even sure what mode '1' is even meant for :D

解决方案

Regarding the original issue, this is the shortest version, which works for me:

Image.fromarray(255 * np.ones((100, 100), np.uint8), '1')

I get a proper all white image.

As pointed out earlier, when converting to mode "1", dithering is activated by default. So, maybe the intention of mode "1" is exactly that: Providing a fast way to create dithered images. Let's see this short example:

from matplotlib import pyplot as plt
import numpy as np
from PIL import Image

plt.figure(1, figsize=(15, 5))

# Open some image
img = Image.open('path/to/your/image.png')
plt.subplot(1, 3, 1), plt.imshow(img)

# Convert to '1'; dithering activated by default
plt.subplot(1, 3, 2), plt.imshow(img.convert('1'))

# Convert to '1'; dithering deactivated
plt.subplot(1, 3, 3), plt.imshow(img.convert('1', dither=Image.NONE))

plt.tight_layout()
plt.show()

That'd be the output:

The dithered image quite looks like a usual grayscale image when small enough. When dithering is deactivated (right image), you actually get a thresholded image, where all values >= 128 are set to white, or black otherwise.

Hope that helps!

-----------------------
System information
-----------------------
Python:      3.8.1
Matplotlib:  3.2.0rc1
NumPy:       1.18.1
Pillow:      7.0.0
-----------------------

这篇关于奇怪的PIL.Image.fromarray行为,在模式='1'中具有numpy零和1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:52