如何使用PIL保存图像? [英] How can I save an image with PIL?

查看:207
本文介绍了如何使用PIL保存图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使用Python图像库(PIL)进行了一些图像处理,这是我之前发现的一篇文章,它执行图像的傅立叶变换,但是我无法使用save函数.整个代码可以正常工作,但不会保存生成的图像:

I have just done some image processing using the Python image library (PIL) using a post I found earlier to perform fourier transforms of images and I can't get the save function to work. The whole code works fine but it just wont save the resulting image:

from PIL import Image
import numpy as np

i = Image.open("C:/Users/User/Desktop/mesh.bmp")
i = i.convert("L")
a = np.asarray(i)
b = np.abs(np.fft.rfft2(a))
j = Image.fromarray(b)
j.save("C:/Users/User/Desktop/mesh_trans",".bmp")

我得到的错误如下:

save_handler = SAVE[string.upper(format)] # unknown format
    KeyError: '.BMP'

如何使用Pythons PIL保存图像?

How can I save an image with Pythons PIL?

推荐答案

已解决与文件扩展名有关的错误,您可以使用bmp(不带点),也可以将输出名称与扩展名一起传递.现在要处理该错误,您需要在频域中适当地修改数据以将其保存为整数图像,PIL告诉您它不接受将浮点数据保存为bmp.

The error regarding the file extension has been handled, you either use bmp (without the dot), or pass the output name with the extension already. Now to handle the error you need to properly modify your data in frequency domain to be saved as an integer image, PIL is telling you that it doesn't accept float data to save as bmp.

以下是进行转换以进行正确可视化的建议(进行了其他较小的修改,例如使用fftshiftnumpy.array而不是numpy.asarray)

Here is a suggestion (with other minor modifications, like using fftshift and numpy.array instead of numpy.asarray) for doing the conversion for proper visualization:

import sys
import numpy
from PIL import Image

img = Image.open(sys.argv[1]).convert('L')

im = numpy.array(img)
fft_mag = numpy.abs(numpy.fft.fftshift(numpy.fft.fft2(im)))

visual = numpy.log(fft_mag)
visual = (visual - visual.min()) / (visual.max() - visual.min())

result = Image.fromarray((visual * 255).astype(numpy.uint8))
result.save('out.bmp')

这篇关于如何使用PIL保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆