我刚刚使用 Python 图像库 (PIL) 进行了一些图像处理,使用我之前找到的一篇文章来执行图像的傅立叶变换,但我无法使用保存功能.整个代码工作正常,但它只是不会保存结果图像:
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 the frequency domain to be saved as an integer image, PIL
is telling you that it doesn't accept float data to save as BMP.
这是一个建议(进行其他小的修改,例如使用 fftshift
和 numpy.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 保存图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!