无法在python中保存PIL图片

时间:2019-02-20 19:55:55

标签: python image-processing python-imaging-library pytorch

我正在尝试从此处https://github.com/pytorch/examples/tree/master/fast_neural_style运行代码,我从终端python neural_style/neural_style.py eval --content-image ./images/content-images/amber.jpg --model ./saved_models/mosaic.pth --output-image a.jpg --cuda 0运行以下命令,其中a.jpg是输出图像,但是每次遇到错误时:

Traceback (most recent call last):
  File "neural_style/neural_style.py", line 240, in <module>
    main()
  File "neural_style/neural_style.py", line 236, in main
    stylize(args)
  File "neural_style/neural_style.py", line 150, in stylize
    utils.save_image(args.output_image, output[0])
  File "C:\Users\Lenovo\Documents\fast_neural_style\neural_style\utils.py", line 19, in save_image
    img.save(filename)
  File "C:\Users\Lenovo\Anaconda3\lib\site-packages\PIL\Image.py", line 1991, in save
    fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: 'a.jpg'

我尝试在a.jpg前用斜杠和反斜杠规定完整路径,但是每次此错误仍然出现时。

我从终端通过命令python test.py启动了以下脚本:

from PIL import Image, ImageDraw
text = "test image"
color = (0, 0, 120)
img = Image.new('RGB', (100, 50), color)
imgDrawer = ImageDraw.Draw(img)
imgDrawer.text((10, 20), text)
img.save("pil-example.png")

再次出现错误

Traceback (most recent call last):
  File "test.py", line 7, in <module>
    img.save("pil-example.png")
  File "C:\Users\Lenovo\Anaconda3\lib\site-packages\PIL\Image.py", line 1966, in save
    fp = builtins.open(filename, "w+b")
FileNotFoundError: [Errno 2] No such file or directory: 'pil-example.png'

但是,当我在jupiter-notebook中启动此脚本时,它可以正常工作。

我使用:Windows 10,Python 3.7.1,Pillow 5.3.0。

对于解决此问题的任何建议,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果您使用的是Windows 10,请确保关闭Ransomware Protection下的文件系统访问设置。该设置应位于 Windows安全性> 病毒和威胁防护> 勒索软件防护>关闭受控文件系统访问

该设置禁止任何未经授权的程序或脚本更改系统上的文件。从理论上讲,以管理员身份运行脚本还应该解决当前的问题。但是,关闭设置也会使您免于将来的麻烦。