Bla*_*ren 12 python numpy python-imaging-library
假设我在0到1的范围内有一个2D Numpy值数组,它代表一个灰度图像.然后我如何将其转换为PIL图像对象?迄今为止的所有尝试都产生了极其奇怪的散乱像素或黑色图像.
for x in range(image.shape[0]):
for y in range(image.shape[1]):
image[y][x] = numpy.uint8(255 * (image[x][y] - min) / (max - min))
#Create a PIL image.
img = Image.fromarray(image, 'L')
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,numpy数组图像通过(image [x] [y] - min)/(max - min)进行归一化,因此每个值都在0到1的范围内.然后它乘以255并转换为8位整数.理论上,这应该通过具有模式L的Image.fromarray处理成灰度图像 - 但结果是一组分散的白色像素.
Nat*_*han 12
我认为答案是错误的.Image.fromarray(____,'L')函数似乎只能在0到255之间的整数数组中正常工作.我使用np.uint8函数.
如果您尝试制作渐变,则可以看到此演示.
import numpy as np
from PIL import Image
# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)
# reshape to 2d
mat = np.reshape(array,(256,256))
# Creates PIL image
img = Image.fromarray(np.uint8(mat * 255) , 'L')
img.show()
Run Code Online (Sandbox Code Playgroud)
做一个干净的渐变
VS
import numpy as np
from PIL import Image
# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)
# reshape to 2d
mat = np.reshape(array,(256,256))
# Creates PIL image
img = Image.fromarray( mat , 'L')
img.show()
Run Code Online (Sandbox Code Playgroud)
有同样的瑕疵.
如果我理解你的问题,你想使用 PIL 获得灰度图像。
如果是这种情况,则不需要将每个像素乘以 255。
以下对我有用
import numpy as np
from PIL import Image
# Creates a random image 100*100 pixels
mat = np.random.random((100,100))
# Creates PIL image
img = Image.fromarray(mat, 'L')
img.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29127 次 |
| 最近记录: |