我可以制作图像并将其保存为文件:
Img1 = PIL.Image.new('RGB', (512,512))
display(newImg1)
Img1.save("img1.jpg","JPEG")
但此图像无法保存
import numpy as np
import PIL.Image
def makePic(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
result=PIL.Image.fromarray(a).save(f, fmt)
result=(Image(data=f.getvalue()))
return result
Img2 = np.float32(PIL.Image.new('RGB', (512,512)))
imag=makePic(Img2)
display(imag)
imag.save("img1.jpg","JPG")
----> 4 imag.save("img1.jpg","JPG")
AttributeError: 'Image' object has no attribute 'save'
display(imag)可以很好地显示图片,但是python认为它不是图片。为什么?
答案 0 :(得分:0)
该线程给了我线索: image does not display in ipython
不幸的是,现在不推荐使用“ scipy.misc.imsave”,我必须使用imageio
但是我不能简单地
pip install imageio
它给了我一些有关使用sudo和-H标志的技巧。好吧,我做到了,确实,当我启动python时,我可以做到这一点
>>>import imageio
>>>
但是当我启动jupyter-notebook时,笔记本很笨拙,并说“没有名为imageio的模块”
所以我尝试再次安装它并得到了
$pip install imageio
Requirement already satisfied: imageio in /usr/local/lib/python3.6/dist-packages (2.5.0)
Requirement already satisfied: pillow in /usr/lib/python3/dist-packages (from imageio) (5.1.0)
Requirement already satisfied: numpy in /usr/lib/python3/dist-packages (from imageio) (1.13.3)
它如何最终出现在python3目录中?所以我决定尝试一下
$python -m pip install imageio --user
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Requirement already satisfied: imageio in ./.local/lib/python2.7/site-packages (2.5.0)
Requirement already satisfied: futures in /usr/local/lib/python2.7/dist-packages (from imageio) (3.2.0)
Requirement already satisfied: numpy in /usr/lib/python2.7/dist-packages (from imageio) (1.13.3)
Requirement already satisfied: enum34 in /usr/lib/python2.7/dist-packages (from imageio) (1.1.6)
Requirement already satisfied: pillow in /usr/local/lib/python2.7/dist-packages (from imageio) (5.4.1)
我为什么要继续使用python 2.7?好吧,因为我有这些相当长的python程序,所以我不希望进行故障排除以使其在python3中工作。无论如何,现在当我打开jupyter-notebook时,我可以这样做
import numpy as np
import PIL.Image
import imageio
from IPython.display import clear_output, Image, display
img2 = np.float32(PIL.Image.new('RGB', (256,512)))
imageio.imwrite('test.jpg', img2[:, :, 0])
,它将正确的jpg保存到磁盘。但是,如果我尝试这样看待它
display(img2)
显然,我只是得到了numpy数组。所以要显示它,我必须像这样用makePic def转换数组:
img2 = np.float32(PIL.Image.new('RGB', (125,512)))
imageio.imwrite('test.jpg', img2[:, :, 0])
#display(img2)
image=makePic(img2)
display(image)
有趣的是,imageio.imwrite调用只是将numpy数组写入磁盘,但是当我转到该文件并在ubuntu中打开它时,很明显,图像查看器会将numpy数组转换为图像。