标签归档:python-imaging-library

适用于Python 3的图片库

问题:适用于Python 3的图片库

什么是python-3而不是PIL来处理图像?

What is python-3 using instead of PIL for manipulating Images?


回答 0

“友好的PIL叉子” 枕头可在Python 2和3上使用。请查看Github项目以获取支持矩阵等。

The “friendly PIL fork” Pillow works on Python 2 and 3. Check out the Github project for support matrix and so on.


回答 1

Christoph Gohlke设法为高达3.3的python版本构建了PIL(仅适用于Windows):http ://www.lfd.uci.edu/~gohlke/pythonlibs/

我用Python 3.2尝试了他的PIL版本,并且图像打开/创建/像素操作/保存了所有工作。

Christoph Gohlke managed to build PIL (for Windows only) for python versions up to 3.3: http://www.lfd.uci.edu/~gohlke/pythonlibs/

I tried his version of PIL with Python 3.2, and image open/create/pixel manipulation/save all work.


回答 2

Qt与图形效果很好。在我看来,它比PIL更通用。

您可以获得图形处理所需的所有功能,但也有矢量图形,甚至支持实际打印机。而所有这些都在一个统一的API中QPainter

要使用Qt,您需要一个Python绑定:PySidePyQt4
它们都支持Python 3。

这是一个简单的示例,该示例加载JPG图像,在坐标(20,20)处绘制半径为10的抗锯齿圆,并使用这些坐标处的像素颜色,并将修改后的图像另存为PNG文件:

from PySide.QtCore import *
from PySide.QtGui import *

app = QCoreApplication([])

img = QImage('input.jpg')

g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()

img.save('output.png')

但是请注意,此解决方案是“重量级”的,因为Qt是用于制作GUI应用程序的大型框架。

Qt works very well with graphics. In my opinion it is more versatile than PIL.

You get all the features you want for graphics manipulation, but there’s also vector graphics and even support for real printers. And all of that in one uniform API, QPainter.

To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.

Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:

from PySide.QtCore import *
from PySide.QtGui import *

app = QCoreApplication([])

img = QImage('input.jpg')

g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()

img.save('output.png')

But please note that this solution is quite ‘heavyweight’, because Qt is a large framework for making GUI applications.


回答 3

截至2012年3月30日,我尝试并未能在GitHub上使用sloonz fork打开图像。我把它编译好了,但是实际上没有用。我还尝试构建gohlke的库,它也进行了编译,但是无法打开任何图像。有人在上面提到过PythonMagick,但它只能在Windows上编译。请参阅wxPython Wiki上的PythonMagick

PIL的最新更新是在2009年,虽然它的网站说他们正在使用Python 3端口,但是已经过去了3年,并且邮件列表变得越来越冷。

为了解决我的Python 3图像处理问题,我正在使用subprocess.call()执行ImageMagick shell命令。此方法有效。

请参阅子流程模块文档

As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn’t actually work. I also tried building gohlke’s library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.

PIL was last updated in 2009, and while it’s website says they are working on a Python 3 port, it’s been 3 years, and the mailing list has gone cold.

To solve my Python 3 image manipulation problem, I am using subprocess.call() to execute ImageMagick shell commands. This method works.

See the subprocess module documentation.


回答 4

您可以在Python 3上使用我的软件包mahotas。它是基于numpy的,而不是基于PIL的。

You can use my package mahotas on Python 3. It is numpy-based rather than PIL based.


回答 5

您需要Pillow,这是在Python 3上安装它的方法:

pip3 install Pillow

如果那对您不起作用(应该),请尝试normal pip

pip install Pillow

You want the Pillow library, here is how to install it on Python 3:

pip3 install Pillow

If that does not work for you (it should), try normal pip:

pip install Pillow

回答 6

根据需要,scikit-image可能是最佳选择,其处理方式已经超越了PIL和当前版本的Pillow。保养得很好,至少和枕头一样多。而且,底层的数据结构来自Numpy和Scipy,这使其代码具有令人难以置信的互操作性。枕头无法处理的示例:

区域邻接图合并

on变换

定向梯度直方图

近似和细分多边形

您可以在图库中看到其力量。 本文提供了一个很好的介绍。祝好运!

Depending on what is needed, scikit-image may be the best choice, with manipulations going way beyond PIL and the current version of Pillow. Very well-maintained, at least as much as Pillow. Also, the underlying data structures are from Numpy and Scipy, which makes its code incredibly interoperable. Examples that pillow can’t handle:

Region Adjacency Graph Merging

Radon Transform

Histogram of oriented gradients

Approximate and subdivide polygons

You can see its power in the gallery. This paper provides a great intro to it. Good luck!


回答 7

如果您使用的是Python3,还可以使用库PILasOPENCV,该库可在Python 2和3中使用。函数api调用与PIL或pillow中的函数相同,但在内部它与OpenCV和numpy一起加载,保存和操作图像。看看https://github.com/bunkahle/PILasOPENCV或使用pip install PILasOPENCV进行安装。并非所有PIL功能都已被模拟,但是最常用的功能都可以工作。

If you are on Python3 you can also use the library PILasOPENCV which works in Python 2 and 3. Function api calls are the same as in PIL or pillow but internally it works with OpenCV and numpy to load, save and manipulate images. Have a look at https://github.com/bunkahle/PILasOPENCV or install it with pip install PILasOPENCV. Not all PIL functions have been simulated but the most common functions work.


如何使用PIL将透明png图像与另一个图像合并

问题:如何使用PIL将透明png图像与另一个图像合并

我有一个透明的png图像“ foo.png”,并且用

im = Image.open("foo2.png");

现在我需要将foo.png与foo2.png合并。

(foo.png包含一些文本,我想在foo2.png上打印该文本)

I have a transparent png image “foo.png” and I’ve opened another image with

im = Image.open("foo2.png");

now what i need is to merge foo.png with foo2.png.

( foo.png contains some text and I want to print that text on foo2.png )


回答 0

import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

的第一个参数.paste()是要粘贴的图像。第二个是坐标,秘密调味料是第三个参数。它表示将用于粘贴图像的遮罩。如果通过透明图像,则Alpha通道将用作遮罩。

检查文档

import Image

background = Image.open("test1.png")
foreground = Image.open("test2.png")

background.paste(foreground, (0, 0), foreground)
background.show()

First parameter to .paste() is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a mask that will be used to paste the image. If you pass a image with transparency, then the alpha channel is used as mask.

Check the docs.


回答 1

Image.paste当背景图像也包含透明度时,将无法正常工作。您需要使用真正的Alpha合成

枕头2.0包含alpha_composite执行此操作的功能。

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

编辑:两个图像都必须是RGBA类型。因此,convert('RGBA')如果它们带有调色板等,则需要调用。如果背景没有Alpha通道,则可以使用常规的粘贴方法(应该更快)。

Image.paste does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.

Pillow 2.0 contains an alpha_composite function that does this.

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA') if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).


回答 2

正如olt已经指出的那样,Image.paste当源目标都包含alpha 时,将无法正常工作。

请考虑以下情形:

两个测试图像都包含alpha:

在此处输入图片说明 在此处输入图片说明

layer1 = Image.open("layer1.png")
layer2 = Image.open("layer2.png")

Image.paste像这样合成图像:

final1 = Image.new("RGBA", layer1.size)
final1.paste(layer1, (0,0), layer1)
final1.paste(layer2, (0,0), layer2)

产生以下图像(红色像素的叠加部分完全取自第二层。像素未正确混合):

在此处输入图片说明

Image.alpha_composite像这样合成图像:

final2 = Image.new("RGBA", layer1.size)
final2 = Image.alpha_composite(final2, layer1)
final2 = Image.alpha_composite(final2, layer2)

产生以下(正确)图像:

在此处输入图片说明

As olt already pointed out, Image.paste doesn’t work properly, when source and destination both contain alpha.

Consider the following scenario:

Two test images, both contain alpha:

enter image description here enter image description here

layer1 = Image.open("layer1.png")
layer2 = Image.open("layer2.png")

Compositing image using Image.paste like so:

final1 = Image.new("RGBA", layer1.size)
final1.paste(layer1, (0,0), layer1)
final1.paste(layer2, (0,0), layer2)

produces the following image (the alpha part of the overlayed red pixels is completely taken from the 2nd layer. The pixels are not blended correctly):

enter image description here

Compositing image using Image.alpha_composite like so:

final2 = Image.new("RGBA", layer1.size)
final2 = Image.alpha_composite(final2, layer1)
final2 = Image.alpha_composite(final2, layer2)

produces the following (correct) image:

enter image description here


回答 3

也可以使用混合:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")

One can also use blending:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")

回答 4

def trans_paste(bg_img,fg_img,box=(0,0)):
    fg_img_trans = Image.new("RGBA",bg_img.size)
    fg_img_trans.paste(fg_img,box,mask=fg_img)
    new_img = Image.alpha_composite(bg_img,fg_img_trans)
    return new_img
def trans_paste(bg_img,fg_img,box=(0,0)):
    fg_img_trans = Image.new("RGBA",bg_img.size)
    fg_img_trans.paste(fg_img,box,mask=fg_img)
    new_img = Image.alpha_composite(bg_img,fg_img_trans)
    return new_img

回答 5

有类似的问题,很难找到答案。通过以下功能,您可以将具有透明度参数的图像以特定的偏移量粘贴到另一幅图像上。

import Image

def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
    fg_img_trans = Image.new("RGBA",fg_img.size)
    fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
    bg_img.paste(fg_img_trans,box,fg_img_trans)
    return bg_img

bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()

Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.

import Image

def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
    fg_img_trans = Image.new("RGBA",fg_img.size)
    fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
    bg_img.paste(fg_img_trans,box,fg_img_trans)
    return bg_img

bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()

回答 6

我结束了自己的编码的建议此评论用户@ P.Melch一个项目我正在做,并建议通过@Mithril。

我也编码了安全性,这是它的代码。(我链接了一个特定的提交,因为在此存储库的将来情况可能会发生变化)

注意:我希望图像中有numpy数组,例如np.array(Image.open(...)),输入A和B copy_from以及此链接的函数overlay参数。

依赖项是位于其之前的函数,copy_from方法和numpy数组,它们是要切片的PIL图像内容。

尽管该文件是非常面向类的,但是如果要使用该函数overlay_transparent,请确保将重命名self.frame为背景图像numpy数组。

或者,您可以仅复制整个文件(可能删除一些导入和Utils类),然后与此Frame类进行交互,如下所示:

# Assuming you named the file frame.py in the same directory
from frame import Frame

background = Frame()
overlay = Frame()

background.load_from_path("your path here")
overlay.load_from_path("your path here")

background.overlay_transparent(overlay.frame, x=300, y=200)

然后,您将其background.frame作为叠加和alpha合成数组,可以使用overlayed = Image.fromarray(background.frame)或类似的东西从中获取PIL图像:

overlayed = Frame()
overlayed.load_from_array(background.frame)

或者就像background.save("save path")直接取自alpha复合内部self.frame变量一样。

您可以读取该文件,并找到其它的一些功能,这个实现我喜欢的编码方法get_rgb_frame_arrayresize_by_ratioresize_to_resolutionrotategaussian_blurtransparencyvignetting:)

您可能想要删除该resolve_pending项目专用的方法。

很高兴能为您提供帮助,请务必查看我正在谈论的项目的回购协议,该问题和线程对我的发展大有帮助:)

I ended up coding myself the suggestion of this comment made by the user @P.Melch and suggested by @Mithril on a project I’m working on.

I coded out of bounds safety as well, here’s the code for it. (I linked a specific commit because things can change in the future of this repository)

Note: I expect numpy arrays from the images like so np.array(Image.open(...)) as the inputs A and B from copy_from and this linked function overlay arguments.

The dependencies are the function right before it, the copy_from method, and numpy arrays as the PIL Image content for slicing.

Though the file is very class oriented, if you want to use that function overlay_transparent, be sure to rename the self.frame to your background image numpy array.

Or you can just copy the whole file (probably remove some imports and the Utils class) and interact with this Frame class like so:

# Assuming you named the file frame.py in the same directory
from frame import Frame

background = Frame()
overlay = Frame()

background.load_from_path("your path here")
overlay.load_from_path("your path here")

background.overlay_transparent(overlay.frame, x=300, y=200)

Then you have your background.frame as the overlayed and alpha composited array, you can get a PIL image from it with overlayed = Image.fromarray(background.frame) or something like:

overlayed = Frame()
overlayed.load_from_array(background.frame)

Or just background.save("save path") as that takes directly from the alpha composited internal self.frame variable.

You can read the file and find some other nice functions with this implementation I coded like the methods get_rgb_frame_array, resize_by_ratio, resize_to_resolution, rotate, gaussian_blur, transparency, vignetting :)

You’d probably want to remove the resolve_pending method as that is specific for that project.

Glad if I helped you, be sure to check out the repo of the project I’m talking about, this question and thread helped me a lot on the development :)


ImportError:没有名为PIL的模块

问题:ImportError:没有名为PIL的模块

我在外壳中使用以下命令来安装PIL:

easy_install PIL

然后我运行python,并输入:import PIL。但是我得到这个错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named PIL

我从来没有遇到过这样的问题,您怎么看?

I use this command in the shell to install PIL:

easy_install PIL

then I run python and type this: import PIL. But I get this error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
ImportError: No module named PIL

I’ve never had such problem, what do you think?


回答 0

在某些PIL安装中,您必须执行

import Image

而不是import PIL(实际上并非总是以这种方式导入PIL)。由于import Image对您有用,因此实际上您已经安装了PIL。

为库和Python模块使用不同的名称是不寻常的,但这是为PIL(某些版本)选择的。

您可以从官方教程中获得有关如何使用此模块的更多信息。

PS:实际上,在某些安装上import PIL 确实可以工作,这增加了混乱。这可以通过@JanneKarila发现的文档中示例以及MacPorts PIL软件包的某些最新版本(1.1.7)加以确认。

On some installs of PIL, You must do

import Image

instead of import PIL (PIL is in fact not always imported this way). Since import Image works for you, this means that you have in fact installed PIL.

Having a different name for the library and the Python module is unusual, but this is what was chosen for (some versions of) PIL.

You can get more information about how to use this module from the official tutorial.

PS: In fact, on some installs, import PIL does work, which adds to the confusion. This is confirmed by an example from the documentation, as @JanneKarila found out, and also by some more recent versions of the MacPorts PIL package (1.1.7).


回答 1

在外壳中,运行:

pip install Pillow

注意:已弃用PIL,后继枕头

In shell, run:

pip install Pillow

Attention: PIL is deprecated, and pillow is the successor.


回答 2

另一方面,我强烈建议您使用与PIL向后兼容并且可以更好地维护/在较新的系统上使用的Pillow

安装后即可

import PIL 

要么

from PIL import Image

等等..

On a different note, I can highly recommend the use of Pillow which is backwards compatible with PIL and is better maintained/will work on newer systems.

When that is installed you can do

import PIL 

or

from PIL import Image

etc..


回答 3

首先安装枕头

pip install Pillow

或如下

c:\Python35>python -m pip install Pillow

然后在python代码中,您可以调用

from PIL import Image

“ Pillow是PIL(Python映像库)的一个分支,不再维护。但是,为了保持向后兼容性,将使用旧的模块名称。” 从枕头安装,但“没有模块命名为枕头”-python2.7-Windows 7-python -m安装枕头

At first install Pillow with

pip install Pillow

or as follows

c:\Python35>python -m pip install Pillow

Then in python code you may call

from PIL import Image

“Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. However, to maintain backwards compatibility, the old module name is used.” From pillow installed, but “no module named pillow” – python2.7 – Windows 7 – python -m install pillow


回答 4

有时我会在python中运行Unitest时遇到此类错误。解决方案是在虚拟环境中卸载并安装相同的软件包。

使用此命令:

pip uninstall PIL

pip install  PIL 

如果由于任何原因出现错误,请在命令开头添加sudo,然后按Enter键输入密码。

Sometimes I get this type of error running a Unitest in python. The solution is to uninstall and install the same package on your virtual environment.

Using this commands:

pip uninstall PIL

and

pip install  PIL 

If for any reason you get an error, add sudo at the beginning of the command and after hitting enter type your password.


回答 5

这在Ubuntu 16.04上对我有用:

sudo apt-get install python-imaging

经过大约半小时的搜索,我在Wikibooks上找到了它。

This worked for me on Ubuntu 16.04:

sudo apt-get install python-imaging

I found this on Wikibooks after searching for about half an hour.


回答 6

我用了:

pip install Pillow 

和pip在Lib \ site-packages中安装了PIL。当我将PIL移至Lib时,一切正常。我在Windows 10上。

I used:

pip install Pillow 

and pip installed PIL in Lib\site-packages. When I moved PIL to Lib everything worked fine. I’m on Windows 10.


回答 7

在Windows 10上,我设法达到了:

cd "C:\Users\<your username>\AppData\Local\Programs\Python\Python37-32" 
python -m pip install --upgrade pip     <-- upgrading from 10.something to 19.2.2.
pip3 uninstall pillow
pip3 uninstall PIL
pip3 install image

之后在python中(在我的情况下是python 3.7),这很好用…

import PIL
from PIL import image

On windows 10 I managed to get there with:

cd "C:\Users\<your username>\AppData\Local\Programs\Python\Python37-32" 
python -m pip install --upgrade pip     <-- upgrading from 10.something to 19.2.2.
pip3 uninstall pillow
pip3 uninstall PIL
pip3 install image

after which in python (python 3.7 in my case) this works fine…

import PIL
from PIL import image

回答 8

您必须使用python软件包安装Image和pillow。

类型

python -m pip install image 

或运行命令提示符(在Windows中),然后导航到scripts文件夹

cd C:\Python27\Scripts

然后在命令下面运行

pip install image

you have to install Image and pillow with your python package.

type

python -m pip install image 

or run command prompt (in windows), then navigate to the scripts folder

cd C:\Python27\Scripts

then run below command

pip install image

回答 9

如果您使用水蟒:

conda install pillow

if you use anaconda:

conda install pillow

回答 10

在Windows上,尝试检查PIL库位置的路径。在我的系统上,我注意到路径是

\Python26\Lib\site-packages\pil instead of \Python26\Lib\site-packages\PIL  

pil文件夹重命名为后PIL,我可以加载PIL模块。

On windows, try checking the path to the location of the PIL library. On my system, I noticed the path was

\Python26\Lib\site-packages\pil instead of \Python26\Lib\site-packages\PIL  

after renaming the pil folder to PIL, I was able to load the PIL module.


回答 11

您将需要使用python软件包安装Image和pillow。放心,命令行将为您处理一切。

击中

python -m pip安装映像

You will need to install Image and pillow with your python package. Rest assured, the command line will take care of everything for you.

Hit

python -m pip install image


回答 12

而不是PIL使用枕头它有效

easy_install Pillow

要么

pip install Pillow

instead of PIL use Pillow it works

easy_install Pillow

or

pip install Pillow

回答 13

在Windows上,您需要下载并安装.exe

https://pypi.python.org/pypi/Pillow/2.7.0

On Windows, you need to download it and install the .exe

https://pypi.python.org/pypi/Pillow/2.7.0


回答 14

我使用conda-forge安装了枕头版本5,这似乎对我有用:

conda install --channel conda-forge pillow=5

普通的conda安装枕头对我不起作用。

I used conda-forge to install pillow version 5, and that seemed to work for me:

conda install --channel conda-forge pillow=5

the normal conda install pillow did NOT work for me.


回答 15

导入PIL并进一步导入ImageTk和Image模块时,我遇到了相同的问题。我也尝试直接通过pip安装PIL。但无法成功。由于介于两者之间,因此已建议不要使用PIL,因此,尝试仅通过点子安装枕头。枕头已成功安装,此外,PIL软件包位于以下路径中:python27 / Lib / site-packages /。

现在可以导入Image和ImageTk。

I had the same issue while importing PIL and further importing the ImageTk and Image modules. I also tried installing PIL directly through pip. but not success could be achieved. As in between it has been suggested that PIL has been deprectaed, thus, tried to install pillow through pip only. pillow was successfully installed, further, the PIL package was made under the path : python27/Lib/site-packages/.

Now both Image and ImageTk could be imported.


回答 16

我最近安装了Leap。我尝试了openshot,但没有开始。于是来到这里,发现了一个建议从终端开始,看看是否有任何错误。

我的错误是error missing mlt。所以我python-mlt从Yast 安装了模块并导入了它,尝试启动,但是下一个openshot说missing pil.

我按照枕头建议安装,因为Yast找不到任何pil和导入的pil。没关系,但没有开始显示Error missing goocanvas

我安装goocanvas了Yast,用python导入了它,然后Openshot启动了!

随着大量的终端这样的错误的missing Vimeoclient和大量的attributeerrors。好吧,看看是否有任何影响。

I recently installed Leap. I Tried openshot and it didn’t start. So came here and found a suggestion to start from the Terminal to see if there were any error.

The error I had was error missing mlt. So I installed the python-mlt module from Yast and imported it, tried to start but next openshot said missing pil.

I Followed the Pillow suggestion to install because Yast couldn’t find any pil and imported pil. That went ok but did not start and showed Error missing goocanvas.

The I installed goocanvas with Yast, imported it in python, and Openshot fired up !!

With a lot of errors in the terminal like missing Vimeoclient and lots of attributeerrors. Well, will see if it is of any influence working with it.


回答 17

我遇到了同样的问题,我通过检查pip(pip3 --version)是什么版本来解决了这个问题,然后意识到我输入的python<uncorrect version> filename.py不是python<correct version> filename.py

I had the same problem and i fixed it by checking what version pip (pip3 --version) is, then realizing I’m typing python<uncorrect version> filename.py instead of python<correct version> filename.py


回答 18

您可能缺少构建pil的python标头。如果您使用的是ubuntu或类似功能,它将类似于

apt-get install python-dev

You are probably missing the python headers to build pil. If you’re using ubuntu or the likes it’ll be something like

apt-get install python-dev

如何从Python中的URL读取图像数据?

问题:如何从Python中的URL读取图像数据?

当我们处理本地文件时,我想做的事情很简单,但是当我尝试使用远程URL时,问题就来了。

基本上,我试图从URL提取的文件中创建一个PIL图像对象。当然,我总是可以仅获取URL并将其存储在临时文件中,然后将其打开到图像对象中,但这感觉效率很低。

这是我所拥有的:

Image.open(urlopen(url))

它抱怨seek()说不可用,所以我尝试了这个:

Image.open(urlopen(url).read())

但这也不起作用。有没有更好的方法可以执行此操作,还是可以将这种方式写入临时文件?

What I’m trying to do is fairly simple when we’re dealing with a local file, but the problem comes when I try to do this with a remote URL.

Basically, I’m trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image object, but that feels very inefficient.

Here’s what I have:

Image.open(urlopen(url))

It flakes out complaining that seek() isn’t available, so then I tried this:

Image.open(urlopen(url).read())

But that didn’t work either. Is there a Better Way to do this, or is writing to a temporary file the accepted way of doing this sort of thing?


回答 0

在Python3中,StringIO和cStringIO模块不见了。

在Python3中,您应该使用:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

In Python3 the StringIO and cStringIO modules are gone.

In Python3 you should use:

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

回答 1

你可以尝试使用StringIO

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)

you could try using a StringIO

import urllib, cStringIO

file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)

回答 2

我使用请求库。它似乎更强大。

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

I use the requests library. It seems to be more robust.

from PIL import Image
import requests
from StringIO import StringIO

response = requests.get(url)
img = Image.open(StringIO(response.content))

回答 3

对于使用Pillow的用户,从2.8.0版开始,您可以:

from PIL import Image
import urllib2

im = Image.open(urllib2.urlopen(url))

或者,如果您使用requests

from PIL import Image
import requests

im = Image.open(requests.get(url, stream=True).raw)

参考文献:

For those of you who use Pillow, from version 2.8.0 you can:

from PIL import Image
import urllib2

im = Image.open(urllib2.urlopen(url))

or if you use requests:

from PIL import Image
import requests

im = Image.open(requests.get(url, stream=True).raw)

References:


回答 4

使用StringIO转读字符串转换为一个类文件对象:

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))

Use StringIO to turn the read string into a file-like object:

from StringIO import StringIO
import urllib

Image.open(StringIO(urllib.requests.urlopen(url).read()))

回答 5

对于进行某些sklearn / numpy后处理(即深度学习)的用户,可以使用np.array()包装PIL对象。这样可以避免您像我一样去过Google:

from PIL import Image
import requests
import numpy as np
from StringIO import StringIO

response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))

For those doing some sklearn/numpy post processing (i.e. Deep learning) you can wrap the PIL object with np.array(). This might save you from having to Google it like I did:

from PIL import Image
import requests
import numpy as np
from StringIO import StringIO

response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))

回答 6

Python 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook和IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

与其他方法不同,此方法还可以在for循环中使用!

Python 3

from urllib.request import urlopen
from PIL import Image

img = Image.open(urlopen(url))
img

Jupyter Notebook and IPython

import IPython
url = 'https://newevolutiondesigns.com/images/freebies/colorful-background-14.jpg'
IPython.display.Image(url, width = 250)

Unlike other methods, this method also works in a for loop!


回答 7

如今,可以建议使用的图像输入/输出方法是使用专用的软件包ImageIO。可以使用以下简单代码行直接从URL读取图像数据:

from imageio import imread
image = imread('https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png')

此页面上的许多答案早于该软件包的发布,因此没有提及。ImageIO最初是Scikit-Image工具箱的组件。除了流行的图像处理库PILlow提供的格式外,它还支持多种科学格式。它将所有内容包装在仅关注图像输入/输出的干净API中。实际上,SciPy 取消了自己的图像读取器/写入器,转而使用ImageIO

The arguably recommended way to do image input/output these days is to use the dedicated package ImageIO. Image data can be read directly from a URL with one simple line of code:

from imageio import imread
image = imread('https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png')

Many answers on this page predate the release of that package and therefore do not mention it. ImageIO started out as component of the Scikit-Image toolkit. It supports a number of scientific formats on top of the ones provided by the popular image-processing library PILlow. It wraps it all in a clean API solely focused on image input/output. In fact, SciPy removed its own image reader/writer in favor of ImageIO.


回答 8

选择chrome图像,右键单击它,单击Copy image address,将其粘贴到str变量(my_url)中以读取图像:

import shutil
import requests

my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
    shutil.copyfileobj(response.raw, file)
del response

打开它;

from PIL import Image

img = Image.open('my_image.png')
img.show()

select the image in chrome, right click on it, click on Copy image address, paste it into a str variable (my_url) to read the image:

import shutil
import requests

my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
    shutil.copyfileobj(response.raw, file)
del response

open it;

from PIL import Image

img = Image.open('my_image.png')
img.show()

如何将PIL图像转换为numpy数组?

问题:如何将PIL图像转换为numpy数组?

好吧,我想将PIL图像对象来回转换为numpy数组,因此我可以比PIL PixelAccess对象所允许的更快地进行逐像素转换。我已经找到了如何通过以下方式将像素信息放置在有用的3D numpy数组中:

pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)

但是,在完成所有出色的转换之后,我似乎无法弄清楚如何将其重新加载到PIL对象中。我知道该putdata()方法,但似乎无法使其正常工作。

Alright, I’m toying around with converting a PIL image object back and forth to a numpy array so I can do some faster pixel by pixel transformations than PIL’s PixelAccess object would allow. I’ve figured out how to place the pixel information in a useful 3D numpy array by way of:

pic = Image.open("foo.jpg")
pix = numpy.array(pic.getdata()).reshape(pic.size[0], pic.size[1], 3)

But I can’t seem to figure out how to load it back into the PIL object after I’ve done all my awesome transforms. I’m aware of the putdata() method, but can’t quite seem to get it to behave.


回答 0

您并不是在说putdata()行为方式到底有多精确。我假设你在做

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

这是因为putdata需要一个元组序列,并且您要给它一个numpy数组。这个

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

可以工作,但是非常慢。

从PIL 1.1.6开始,在图像和numpy数组之间进行转换“正确”方法很简单

>>> pix = numpy.array(pic)

尽管结果数组的格式与您的格式不同(在这种情况下为3维数组或行/列/ rgb)。

然后,在对阵列进行更改之后,您应该可以执行任一操作pic.putdata(pix)或使用创建新图像Image.fromarray(pix)

You’re not saying how exactly putdata() is not behaving. I’m assuming you’re doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you’re giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the “proper” way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).


回答 1

I以数组形式打开:

>>> I = numpy.asarray(PIL.Image.open('test.jpg'))

对进行一些处理I,然后将其转换回图像:

>>> im = PIL.Image.fromarray(numpy.uint8(I))

使用FFT,Python过滤numpy图像

如果出于某种原因要明确地执行此操作,则此页面上的correlation.zip中有使用getdata()的pil2array()和array2pil()函数。

Open I as an array:

>>> I = numpy.asarray(PIL.Image.open('test.jpg'))

Do some stuff to I, then, convert it back to an image:

>>> im = PIL.Image.fromarray(numpy.uint8(I))

Filter numpy images with FFT, Python

If you want to do it explicitly for some reason, there are pil2array() and array2pil() functions using getdata() on this page in correlation.zip.


回答 2

我在Python 3.5中使用Pillow 4.1.1(PIL的后继产品)。枕头和numpy之间的转换非常简单。

from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)

需要注意的一件事是,枕头样式im是专栏为主的,而numpy 样式是专栏的im2arr。但是,该功能Image.fromarray已经考虑了这一点。即,arr2im.size == im.sizearr2im.mode == im.mode在上面的例子。

在处理转换后的numpy数组时,例如在进行转换im2arr = np.rollaxis(im2arr, 2, 0)im2arr = np.transpose(im2arr, (2, 0, 1))转换为CxHxW格式时,我们应注意HxWxC数据格式。

I am using Pillow 4.1.1 (the successor of PIL) in Python 3.5. The conversion between Pillow and numpy is straightforward.

from PIL import Image
import numpy as np
im = Image.open('1.jpg')
im2arr = np.array(im) # im2arr.shape: height x width x channel
arr2im = Image.fromarray(im2arr)

One thing that needs noticing is that Pillow-style im is column-major while numpy-style im2arr is row-major. However, the function Image.fromarray already takes this into consideration. That is, arr2im.size == im.size and arr2im.mode == im.mode in the above example.

We should take care of the HxWxC data format when processing the transformed numpy arrays, e.g. do the transform im2arr = np.rollaxis(im2arr, 2, 0) or im2arr = np.transpose(im2arr, (2, 0, 1)) into CxHxW format.


回答 3

您需要通过以下方式将图像转换为numpy数组:

import numpy
import PIL

img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img) 

You need to convert your image to a numpy array this way:

import numpy
import PIL

img = PIL.Image.open("foo.jpg").convert("L")
imgarr = numpy.array(img) 

回答 4

我今天使用的示例:

import PIL
import numpy
from PIL import Image

def resize_image(numpy_array_image, new_height):
    # convert nympy array image to PIL.Image
    image = Image.fromarray(numpy.uint8(numpy_array_image))
    old_width = float(image.size[0])
    old_height = float(image.size[1])
    ratio = float( new_height / old_height)
    new_width = int(old_width * ratio)
    image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
    # convert PIL.Image into nympy array back again
    return array(image)

The example, I have used today:

import PIL
import numpy
from PIL import Image

def resize_image(numpy_array_image, new_height):
    # convert nympy array image to PIL.Image
    image = Image.fromarray(numpy.uint8(numpy_array_image))
    old_width = float(image.size[0])
    old_height = float(image.size[1])
    ratio = float( new_height / old_height)
    new_width = int(old_width * ratio)
    image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
    # convert PIL.Image into nympy array back again
    return array(image)

回答 5

如果图像以Blob格式(即数据库)存储,则可以使用Billal Begueradj解释的相同技术将图像从Blob转换为字节数组。

就我而言,我需要将图像存储在db表的blob列中:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

然后,我创建了一个辅助函数,将我的数据集更改为np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

之后,我可以在神经网络中使用byteArrays了。

plt.imshow(imagesList[0])

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

回答 6

转换Numpy to PIL图像并PIL to Numpy

import numpy as np
from PIL import Image

def pilToNumpy(img):
    return np.array(img)

def NumpyToPil(img):
    return Image.fromarray(img)

Convert Numpy to PIL image and PIL to Numpy

import numpy as np
from PIL import Image

def pilToNumpy(img):
    return np.array(img)

def NumpyToPil(img):
    return Image.fromarray(img)

回答 7

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

您可以通过在压缩特征后将图像解析为numpy()函数来将图像转换为numpy(非规范化)

def imshow(img):
    img = img / 2 + 0.5     # unnormalize
    npimg = img.numpy()
    plt.imshow(np.transpose(npimg, (1, 2, 0)))
    plt.show()

You can transform the image into numpy by parsing the image into numpy() function after squishing out the features( unnormalization)


如何使用PIL获取图片尺寸?

问题:如何使用PIL获取图片尺寸?

如何使用PIL或任何其他Python库获取图片边的大小?

How do I get a size of a pictures sides with PIL or any other Python library?


回答 0

from PIL import Image

im = Image.open('whatever.png')
width, height = im.size

根据文档

from PIL import Image

im = Image.open('whatever.png')
width, height = im.size

According to the documentation.


回答 1

您可以使用Pillow(网站文档GitHubPyPI)。Pillow与PIL具有相同的界面,但可与Python 3一起使用。

安装

$ pip install Pillow

如果您没有管理员权限(在Debian上为sudo),则可以使用

$ pip install --user Pillow

有关安装的其他说明在这里

from PIL import Image
with Image.open(filepath) as img:
    width, height = img.size

速度

这需要3.21秒才能获得30336张图像(JPG从31×21到424×428,来自Kaggle 国家数据科学碗的训练数据)

这可能是使用枕头而不是自己写的东西的最重要的原因。而且您应该使用Pillow而不是PIL(python-imaging),因为它可以在Python 3中使用。

备选方案1:Numpy(已弃用)

我坚持scipy.ndimage.imread认为信息仍然存在,但请记住:

不推荐使用imread!在SciPy 1.0.0中不推荐使用imread,而在1.2.0中已删除了[read]。

import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape

备选方案2:Pygame

import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()

You can use Pillow (Website, Documentation, GitHub, PyPI). Pillow has the same interface as PIL, but works with Python 3.

Installation

$ pip install Pillow

If you don’t have administrator rights (sudo on Debian), you can use

$ pip install --user Pillow

Other notes regarding the installation are here.

Code

from PIL import Image
with Image.open(filepath) as img:
    width, height = img.size

Speed

This needed 3.21 seconds for 30336 images (JPGs from 31×21 to 424×428, training data from National Data Science Bowl on Kaggle)

This is probably the most important reason to use Pillow instead of something self-written. And you should use Pillow instead of PIL (python-imaging), because it works with Python 3.

Alternative #1: Numpy (deprecated)

I keep scipy.ndimage.imread as the information is still out there, but keep in mind:

imread is deprecated! imread is deprecated in SciPy 1.0.0, and [was] removed in 1.2.0.

import scipy.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape

Alternative #2: Pygame

import pygame
img = pygame.image.load(filepath)
width = img.get_width()
height = img.get_height()

回答 2

由于scipyimread已过时,使用imageio.imread

  1. 安装- pip install imageio
  2. height, width, channels = imageio.imread(filepath).shape

Since scipy‘s imread is deprecated, use imageio.imread.

  1. Install – pip install imageio
  2. Use height, width, channels = imageio.imread(filepath).shape

回答 3

这是一个完整的示例,从URL加载图像,使用PIL创建,打印尺寸并调整大小…

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

This is a complete example loading image from URL, creating with PIL, printing the size and resizing…

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

回答 4

这是从Python 3中的给定URL获取图像大小的方法:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

Here’s how you get the image size from the given URL in Python 3:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

回答 5

以下给出尺寸和通道:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

Followings gives dimensions as well as channels:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

Python图像库失败,并显示消息“解码器JPEG不可用”-PIL

问题:Python图像库失败,并显示消息“解码器JPEG不可用”-PIL

PIL在我的系统中确实支持JPEG。

每当我上传时,我的代码都会失败并显示以下内容:

File "PIL/Image.py", line 375, in _getdecoder
    raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available

我该如何解决?

PIL does support JPEG in my system.

Whenever I do an upload, my code is failing with:

File "PIL/Image.py", line 375, in _getdecoder
    raise IOError("decoder %s not available" % decoder_name)
IOError: decoder jpeg not available

How can I resolve this?


回答 0

需要libjpeg-dev才能处理带有枕头(或PIL)的jpeg,因此您需要先安装它,然后重新编译枕头。在Ubuntu 14.04上似乎还需要libjpeg8-dev

如果您仍在使用PIL,那么这些天确实应该使用枕头,因此pip uninstall PIL请先遵循以下说明进行切换,或者如果您有充分的理由坚持使用PIL,请在下面将“枕头”替换为“ PIL” )。

在Ubuntu上:

# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev

# reinstall pillow
pip install --no-cache-dir -I pillow

如果这不起作用,请根据您使用的是64位还是32位Ubuntu,尝试以下操作之一。

对于Ubuntu x64:

sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

或对于Ubuntu 32位:

sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/

然后重新安装枕头:

pip install --no-cache-dir -I pillow

(进行编辑以包含来自评论的反馈。感谢Charles Offenbacher指出32位版本存在差异,而t-mart建议使用--no-cache-dir)。

libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04

If you’re still using PIL then you should really be using pillow these days though, so first pip uninstall PIL before following these instructions to switch, or if you have a good reason for sticking with PIL then replace “pillow” with “PIL” in the below).

On Ubuntu:

# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev

# reinstall pillow
pip install --no-cache-dir -I pillow

If that doesn’t work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu.

For Ubuntu x64:

sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

Or for Ubuntu 32bit:

sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/

Then reinstall pillow:

pip install --no-cache-dir -I pillow

(Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir).


回答 1

对于OSX上的操作系统,我使用以下二进制文件来在系统范围内安装libpng和libjpeg:

适用于OSX的libpng和libjpeg

因为我已经安装了PIL(通过virtualenv上的pip),所以运行:

pip uninstall PIL
pip install PIL --upgrade

decoder JPEG not available为我解决了错误。

更新(4/24/14)

较新版本的pip需要附加标志才能从外部源下载库(包括PIL)。请尝试以下操作:

pip install PIL --allow-external PIL --allow-unverified PIL

有关其他信息,请参见以下答案:pip install PIL不要安装到virtualenv中

更新2

如果在OSX Mavericks上,则需要将ARCHFLAGS标志设置为@RicardoGonzales注释,如下所示

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install PIL --allow-external PIL --allow-unverified PIL

For those on OSX, I used the following binary to get libpng and libjpeg installed systemwide:

libpng & libjpeg for OSX

Because I already had PIL installed (via pip on a virtualenv), I ran:

pip uninstall PIL
pip install PIL --upgrade

This resolved the decoder JPEG not available error for me.

UPDATE (4/24/14):

Newer versions of pip require additional flags to download libraries (including PIL) from external sources. Try the following:

pip install PIL --allow-external PIL --allow-unverified PIL

See the following answer for additional info: pip install PIL dont install into virtualenv

UPDATE 2:

If on OSX Mavericks, you’ll want to set the ARCHFLAGS flag as @RicardoGonzales comments below:

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install PIL --allow-external PIL --allow-unverified PIL

回答 2

这是对我有用的唯一方法。安装软件包和重新安装PIL无效。

在ubuntu上,安装所需的软件包:

sudo apt-get install libjpeg-dev

(您可能还需要安装libfreetype6 libfreetype6-dev zlib1g-dev以启用其他解码器)。

然后用枕头更换PIL:

pip uninstall PIL
pip install pillow

This is the only way that worked for me. Installing packages and reinstalling PIL didn’t work.

On ubuntu, install the required package:

sudo apt-get install libjpeg-dev

(you may also want to install libfreetype6 libfreetype6-dev zlib1g-dev to enable other decoders).

Then replace PIL with pillow:

pip uninstall PIL
pip install pillow

回答 3

以下是在Ubuntu 12.04上的工作:

pip uninstall PIL
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev
pip install PIL --upgrade

当您看到“-JPEG支持可用”时,表明它可以工作。

但是,如果在编辑jpeg图像时仍然不起作用,请检查python路径!我的python路径未命中/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/,因此我~/.bashrc将以下代码添加到该文件中:

编辑: export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/

然后,终于可以了!!

The followed works on ubuntu 12.04:

pip uninstall PIL
apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev
pip install PIL --upgrade

when your see “– JPEG support avaliable” that means it works.

But, if it still doesn’t work when your edit your jpeg image, check the python path !! my python path missed /usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/, so I edit the ~/.bashrc add the following code to this file:

Edit: export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/PIL-1.1.7-py2.7-linux-x86_64.egg/

then, finally, it works!!


回答 4

在Fedora 17上,我必须先安装libjpeg-devel然后重新安装PIL

sudo yum install --assumeyes libjpeg-devel
sudo pip-python install --upgrade PIL

On Fedora 17 I had to install libjpeg-devel and afterwards reinstall PIL:

sudo yum install --assumeyes libjpeg-devel
sudo pip-python install --upgrade PIL

回答 5

Rolo的回答非常好,但是我不得不绕过pip缓存(pip 7引入)来重新安装Pillow,否则它将无法正确地重新编译!!!该命令是:

pip install -I --no-cache-dir -v Pillow

您可以通过在日志中读取以下内容来查看是否已正确配置枕头:

PIL SETUP SUMMARY
    --------------------------------------------------------------------
    version      Pillow 2.8.2
    platform     linux 3.4.3 (default, May 25 2015, 15:44:26)
                 [GCC 4.8.2]
    --------------------------------------------------------------------
    *** TKINTER support not available
    --- JPEG support available
    *** OPENJPEG (JPEG2000) support not available
    --- ZLIB (PNG/ZIP) support available
    --- LIBTIFF support available
    --- FREETYPE2 support available
    *** LITTLECMS2 support not available
    *** WEBP support not available
    *** WEBPMUX support not available
    --------------------------------------------------------------------

如您所见,启用了对jpg,tiff等的支持,因为我以前通过apt(libjpeg-dev libpng12-dev libfreetype6-dev libtiff-dev)安装了所需的库。

Rolo’s answer is excellent, however I had to reinstall Pillow by bypassing pip cache (introduced with pip 7) otherwise it won’t get properly recompiled!!! The command is:

pip install -I --no-cache-dir -v Pillow

and you can see if Pillow has been properly configured by reading in the logs this:

PIL SETUP SUMMARY
    --------------------------------------------------------------------
    version      Pillow 2.8.2
    platform     linux 3.4.3 (default, May 25 2015, 15:44:26)
                 [GCC 4.8.2]
    --------------------------------------------------------------------
    *** TKINTER support not available
    --- JPEG support available
    *** OPENJPEG (JPEG2000) support not available
    --- ZLIB (PNG/ZIP) support available
    --- LIBTIFF support available
    --- FREETYPE2 support available
    *** LITTLECMS2 support not available
    *** WEBP support not available
    *** WEBPMUX support not available
    --------------------------------------------------------------------

as you can see the support for jpg, tiff and so on is enabled, because I previously installed the required libraries via apt (libjpeg-dev libpng12-dev libfreetype6-dev libtiff-dev)


回答 6

在Mac OS X Mavericks(10.9.3)上,我通过执行以下操作解决了此问题:

通过brew安装libjpeg (软件包管理系统)

酿造安装libjpeg

重新安装枕头(我用枕头代替PIL)

点安装-我枕头

On Mac OS X Mavericks (10.9.3), I solved this by doing the follows:

Install libjpeg by brew (package management system)

brew install libjpeg

reinstall pillow (I use pillow instead of PIL)

pip install -I pillow


回答 7

apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev

安装这些文件并确保使用pip安装PIL,因为我是从源代码编译它的,由于某种原因它不起作用

apt-get install libjpeg-dev
apt-get install libfreetype6-dev
apt-get install zlib1g-dev
apt-get install libpng12-dev

Install these and be sure to install PIL with pip because I compiled it from source and for some reason it didn’t work


回答 8

我已经在使用Pillow并且遇到了同样的错误。尝试安装libjpeglibjpeg-dev按照其他人的建议进行安装,但被告知已经安装了(较新的)版本。

最后只需要重新安装Pillow

sudo pip uninstall Pillow
sudo pip install Pillow

I was already using Pillow and got the same error. Tried installing libjpeg or libjpeg-dev as suggested by others but was told that a (newer) version was already installed.

In the end all it took was reinstalling Pillow:

sudo pip uninstall Pillow
sudo pip install Pillow

回答 9

我太新手,无法评论zeantsoi post;(。因此,这里他需要做的工作才能在10.9.1上的OSX上解决

IOError:解码器jpeg不可用

1)安装Xcode工具(打开您的终端并执行: xcode-select --install)-摘自本文:Mac OS X 10.9之后无法安装PIL

2)从此链接安装libpng和libjpeg软件包(组合安装程序):http : //ethan.tira-thompson.com/Mac_OS_X_Ports.html

3)重新启动(不确定是否是强制性的)

4)使用run 重新安装PILpip install -I PIL(就像我在出现问题之前最初安装PIL一样)

希望有帮助,不要混淆更多…

_oho

I’m too newbie to comment zeantsoi post ;(. So here his what I needed to do to solved on OSX on 10.9.1 the

IOError: decoder jpeg not available

1) install Xcode tools (open your terminal and execute: xcode-select --install) – taken from this post: Can’t install PIL after Mac OS X 10.9

2) install libpng and libjpeg package (combo installer) from this link: http://ethan.tira-thompson.com/Mac_OS_X_Ports.html

3) reboot (not sure it was mandatory)

4) Re-install PIL with run pip install -I PIL (as I had initially installed PIL before having the issue)

Hope this help and don’t confuse more …

_oho


回答 10

这个问题是在很久以前发布的,而且大多数答案也很老。因此,当我花数小时试图弄清楚这一点时,没有任何效果,并且我尝试了本文中的所有建议。

尝试以Django头像形式上载JPG时,我仍然遇到标准JPEG错误:

raise IOError("decoder %s not available" % decoder_name)
OSError: decoder jpeg not available

然后,我检查了Ubuntu 12.04的存储库,发现有一些额外的软件包libjpeg。我安装了这些,问题就解决了:

sudo apt-get install libjpeg62 libjpeg62-dev

安装这些去掉libjpeg-devlibjpeg-turbo8-devlibjpeg8-dev

希望这对2015年及以后的人有所帮助!

干杯

This question was posted quite a while ago and most of the answers are quite old too. So when I spent hours trying to figure this out, nothing worked, and I tried all suggestions in this post.

I was still getting the standard JPEG errors when trying to upload a JPG in my Django avatar form:

raise IOError("decoder %s not available" % decoder_name)
OSError: decoder jpeg not available

Then I checked the repository for Ubuntu 12.04 and noticed some extra packages for libjpeg. I installed these and my problem was solved:

sudo apt-get install libjpeg62 libjpeg62-dev

Installing these removed libjpeg-dev, libjpeg-turbo8-dev, and libjpeg8-dev.

Hope this helps someone in the year 2015 and beyond!

Cheers


回答 11

同样的问题在这里,JPEG support available但是仍然得到了IOError: decoder/encoder jpeg not available,除了我使用枕头而不是PIL。

我尝试了以上所有方法,但经过多个小时,我意识到与结合使用sudo pip install不能按预期工作virtualenv。傻我

使用sudo有效在未激活virtualenv 的新外壳中启动命令(我的理解可能并不完全正确),这意味着这些软件包将安装在全局环境中。(这把事情弄糟了,我想我有2个不同的Pillow安装。)

我清理了所有内容,将用户更改为root,然后将其重新安装在virtualenv中,现在可以使用了。
希望这会帮助某人!

Same problem here, JPEG support available but still got IOError: decoder/encoder jpeg not available, except I use Pillow and not PIL.

I tried all of the above and more, but after many hours I realized that using sudo pip install does not work as I expected, in combination with virtualenv. Silly me.

Using sudo effectively launches the command in a new shell (my understanding of this may not be entirely correct) where the virtualenv is not activated, meaning that the packages will be installed in the global environment instead. (This messed things up, I think I had 2 different installations of Pillow.)

I cleaned things up, changed user to root and reinstalled in the virtualenv and now it works.
Hopefully this will help someone!


回答 12

对于Fedora

安装必备组件
sudo dnf install make automake gcc gcc-c++ kernel-devel rpm-build libjpeg-devel zlib-devel python-devel
现在安装枕头

sudo pip install pillow

注意-对于libjpeg和zlib,我们在Fedora / CentOS / Red Hat 中安装libjpeg-develzlib-devel软件包。

For Fedora

Install pre-requisite
sudo dnf install make automake gcc gcc-c++ kernel-devel rpm-build libjpeg-devel zlib-devel python-devel
Now install Pillow

sudo pip install pillow

Note – For libjpeg and zlib we are installing libjpeg-devel and zlib-devel packages in Fedora/CentOS/Red Hat


回答 13

首先,除了卸载Python之外,我还必须删除隐藏文件夹user / appData中的python文件夹(这很麻烦)。然后,我安装了WinPython发行版:http : //code.google.com/p/winpython/,其中包含PIL

First I had to delete the python folders in hidden folder user/appData (that was creating huge headaches), in addition to uninstalling Python. Then I installed WinPython Distribution: http://code.google.com/p/winpython/ which includes PIL


回答 14

对于Mac OS Mountain Lion上的用户,我遵循了zeantsoi的提示,但是它不起作用。

我最终以这篇文章的解决方案结束:http : //appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-__jpeg_resync_to_restart/

现在,我很高兴为jpeg运行脚本!

For those on Mac OS Mountain Lion, I followed the anwser of zeantsoi, but it doesn’t work.

I finally ended up with the solution of this post: http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/

Now, I’m happily running my script for jpeg !


用pip安装PIL

问题:用pip安装PIL

我正在尝试使用以下命令安装PIL(Python Imaging Library):

sudo pip install pil

但我收到以下消息:

Downloading/unpacking PIL
  You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files.
  Downloading PIL-1.1.7.tar.gz (506kB): 506kB downloaded
  Running setup.py egg_info for package PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

Installing collected packages: PIL
  Running setup.py install for PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py
    --- using frameworks at /System/Library/Frameworks
    building '_imaging' extension
    clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
    unable to execute clang: No such file or directory
    error: command 'clang' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/private/tmp/pip_build_root/PIL/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-AYrxVD-record/install-record.txt --single-version-externally-managed:
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

running install

running build

.
.
.
.

copying PIL/XVThumbImagePlugin.py -> build/lib.macosx-10.8-intel-2.7

running build_ext

--- using frameworks at /System/Library/Frameworks

building '_imaging' extension

creating build/temp.macosx-10.8-intel-2.7

creating build/temp.macosx-10.8-intel-2.7/libImaging

clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o

unable to execute clang: No such file or directory

error: command 'clang' failed with exit status 1

----------------------------------------
Cleaning up

您能帮我安装PIL吗?

I am trying to install PIL (the Python Imaging Library) using the command:

sudo pip install pil

but I get the following message:

Downloading/unpacking PIL
  You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files.
  Downloading PIL-1.1.7.tar.gz (506kB): 506kB downloaded
  Running setup.py egg_info for package PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

Installing collected packages: PIL
  Running setup.py install for PIL
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py
    --- using frameworks at /System/Library/Frameworks
    building '_imaging' extension
    clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o
    unable to execute clang: No such file or directory
    error: command 'clang' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools;__file__='/private/tmp/pip_build_root/PIL/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-AYrxVD-record/install-record.txt --single-version-externally-managed:
    WARNING: '' not a valid package name; please use only.-separated package names in setup.py

running install

running build

.
.
.
.

copying PIL/XVThumbImagePlugin.py -> build/lib.macosx-10.8-intel-2.7

running build_ext

--- using frameworks at /System/Library/Frameworks

building '_imaging' extension

creating build/temp.macosx-10.8-intel-2.7

creating build/temp.macosx-10.8-intel-2.7/libImaging

clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -IlibImaging -I/System/Library/Frameworks/Python.framework/Versions/2.7/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _imaging.c -o build/temp.macosx-10.8-intel-2.7/_imaging.o

unable to execute clang: No such file or directory

error: command 'clang' failed with exit status 1

----------------------------------------
Cleaning up…

Could you please help me to install PIL??


回答 0

  1. 如上所述安装Xcode和Xcode命令行工具。
  2. 请改用Pillow,因为PIL基本已失效。枕头是PIL的保养品。

https://pypi.python.org/pypi/Pillow/2.2.1

pip install Pillow

如果您同时安装了两个Python,并且想为Python3安装此代码,请执行以下操作:

python3 -m pip install Pillow
  1. Install Xcode and Xcode Command Line Tools as mentioned.
  2. Use Pillow instead, as PIL is basically dead. Pillow is a maintained fork of PIL.

https://pypi.python.org/pypi/Pillow/2.2.1

pip install Pillow

If you have both Pythons installed and want to install this for Python3:

python3 -m pip install Pillow

回答 1

这对我有用:

apt-get install python-dev
apt-get install libjpeg-dev
apt-get install libjpeg8-dev
apt-get install libpng3
apt-get install libfreetype6-dev
ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib

pip install PIL  --allow-unverified PIL --allow-all-external

This works for me:

apt-get install python-dev
apt-get install libjpeg-dev
apt-get install libjpeg8-dev
apt-get install libpng3
apt-get install libfreetype6-dev
ln -s /usr/lib/i386-linux-gnu/libfreetype.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib
ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib

pip install PIL  --allow-unverified PIL --allow-all-external

回答 2

使用apt install非常简单,使用此命令即可完成

sudo apt-get install python-PIL

要么

sudo pip install pillow

要么

sudo easy_install pillow

It is very simple using apt install use this command to get it done

sudo apt-get install python-PIL

or

sudo pip install pillow

or

sudo easy_install pillow

回答 3

在Mac OS X上,使用以下命令:

sudo pip install https://effbot.org/media/downloads/Imaging-1.1.7.tar.gz

On Mac OS X, use this command:

sudo pip install https://effbot.org/media/downloads/Imaging-1.1.7.tar.gz

回答 4

您应该描述安装在这里

pip install image

You should install as described here:

pip install image

回答 5

我从这里的讨论中得到了答案:

我试过了

pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL

而且有效。

I got the answer from a discussion here:

I tried

pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL

and it worked.


回答 6

安装

pip install Pillow

然后,只需导入文件,例如

from PIL import Image

我正在使用Windows。它为我工作。

注意

Pillow是Python Imaging Library的功能替代品。要使用Pillow运行现有的PIL兼容代码,需要对其进行修改以从PIL命名空间而不是全局命名空间导入Imaging模块。

即更改:

import Image

至:

from PIL import Image

https://pypi.org/project/枕头/2.2.1/

Install

pip install Pillow

Then, Just import in your file like,

from PIL import Image

I am using windows. It is working for me.

NOTE:

Pillow is a functional drop-in replacement for the Python Imaging Library. To run your existing PIL-compatible code with Pillow, it needs to be modified to import the Imaging module from the PIL namespace instead of the global namespace.

i.e. change:

import Image

to:

from PIL import Image

https://pypi.org/project/Pillow/2.2.1/


回答 7

我认为您在Mac上。请参阅如何在Mac OS X 10.7.2 Lion上安装PIL

如果使用[homebrew] [],则可以使用just安装PIL brew install pil。然后,您可能需要将安装目录($(brew --prefix)/lib/python2.7/site-packages)添加到PYTHONPATH中,或者将PIL目录本身的位置添加到PIL.pth任何site-packages目录中名为file的文件中,内容如下:

/usr/local/lib/python2.7/site-packages/PIL

(假设brew --prefix/usr/local)。

另外,您也可以从源代码下载/构建/安装它:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

我刚刚(在OSX 10.7.2,XCode 4.2.1和System Python 2.7.1上)运行了上面的代码,尽管在我的环境中某些内容可能不是默认值,但它的构建还不错。

[homebrew]:http : //mxcl.github.com/homebrew/ “ Homebrew”

I take it you’re on Mac. See How can I install PIL on mac os x 10.7.2 Lion

If you use [homebrew][], you can install the PIL with just brew install pil. You may then need to add the install directory ($(brew --prefix)/lib/python2.7/site-packages) to your PYTHONPATH, or add the location of PIL directory itself in a file called PIL.pth file in any of your site-packages directories, with the contents:

/usr/local/lib/python2.7/site-packages/PIL

(assuming brew --prefix is /usr/local).

Alternatively, you can just download/build/install it from source:

# download
curl -O -L http://effbot.org/media/downloads/Imaging-1.1.7.tar.gz
# extract
tar -xzf Imaging-1.1.7.tar.gz
cd Imaging-1.1.7
# build and install
python setup.py build
sudo python setup.py install
# or install it for just you without requiring admin permissions:
# python setup.py install --user

I ran the above just now (on OSX 10.7.2, with XCode 4.2.1 and System Python 2.7.1) and it built just fine, though there is a possibility that something in my environment is non-default.

[homebrew]: http://mxcl.github.com/homebrew/ “Homebrew”


回答 8

如今,每个人都在PIL上使用友好的PIL叉子Pillow。

代替: sudo pip install pil

做: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

These days, everyone uses Pillow, a friendly PIL fork, over PIL.

Instead of: sudo pip install pil

Do: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

回答 9

对于Ubuntu,PIL不再起作用。我总是得到:

找不到与PIL匹配的分布

因此,安装python-imaging:

sudo apt-get install python-imaging

For Ubuntu, PIL is not working any more. I always get:

No matching distribution found for PIL

So install python-imaging:

sudo apt-get install python-imaging

回答 10

我遇到了同样的问题,但是通过安装 python-dev

在安装PIL之前,请运行以下命令:

sudo apt-get install python-dev

然后安装PIL:

pip install PIL

I’m having the same problem, but it gets solved with installation of python-dev.

Before installing PIL, run following command:

sudo apt-get install python-dev

Then install PIL:

pip install PIL

回答 11

安装过程中出现了一些错误。以防万一有人也有这个。尽管我已经是管理员用户,但不是root用户。

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'

Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log

添加“ sudo”解决了问题,使用sudo可以解决问题:

~/Documents/mv-server: $ sudo pip install Pillow

I had some errors during installation. Just in case somebody has this too. Despite that I already was sitting under admin user, but not root.

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'

Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log

Adding “sudo” solved the problem, with sudo it worked:

~/Documents/mv-server: $ sudo pip install Pillow

回答 12

对于CentOS:

yum install python-imaging

For CentOS:

yum install python-imaging

回答 13

我尝试了所有答案,但失败了。直接从官方站点获取源代码,然后构建安装成功。

  1. 前往网站 http://www.pythonware.com/products/pil/#pil117
  2. 单击“ Python Imaging Library 1.1.7源工具包”以下载源
  3. tar xf Imaging-1.1.7.tar.gz
  4. cd Imaging-1.1.7
  5. sudo python setup.py install

I tried all the answers, but failed. Directly get the source from the official site and then build install success.

  1. Go to the site http://www.pythonware.com/products/pil/#pil117
  2. Click “Python Imaging Library 1.1.7 Source Kit” to download the source
  3. tar xf Imaging-1.1.7.tar.gz
  4. cd Imaging-1.1.7
  5. sudo python setup.py install

回答 14

我用 sudo port install py27-Pillow

I nailed it by using sudo port install py27-Pillow


回答 15

尝试这个:

sudo pip install PIL --allow-external PIL --allow-unverified PIL

Try this:

sudo pip install PIL --allow-external PIL --allow-unverified PIL

回答 16

(窗口)如果Pilow不起作用,请尝试从http://www.pythonware.com/products/pil/下载pil

(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/


回答 17

  • 首先,您应该运行此程序sudo apt-get build-dep python-imaging,它将为您提供可能需要的所有依赖项

  • 然后跑 sudo apt-get update && sudo apt-get -y upgrade

  • 其次是 sudo apt-get install python-pip

  • 然后最后安装Pil pip install pillow

  • First you should run this sudo apt-get build-dep python-imaging which will give you all the dependencies that you might need

  • Then run sudo apt-get update && sudo apt-get -y upgrade

  • Followed by sudo apt-get install python-pip

  • And then finally install Pil pip install pillow


回答 18

使用之前,请先搜索软件包管理器pip。在Arch Linux上,您可以通过以下方式获取PIL:pacman -S python2-pillow

Search on package manager before using pip. On Arch linux you can get PIL by pacman -S python2-pillow


回答 19

还有另一个名为的Python打包工具conda。当某些库需要安装C ++和其他非纯Python的绑定时,Conda优于pip(我认为)。Conda的安装中还包括点子,因此您仍然可以使用点子,但您也可以从conda中受益。

默认情况下,Conda还安装IPython,pil和许多其他库。我想你会喜欢的。

There’s another Python package tool called conda. Conda is preferred (I believe) over pip when there are libraries that need to install C++ and other bindings that aren’t pure Python. Conda includes pip in its installation as well so you can still use pip, but you also get the benefits of conda.

Conda also installs IPython, pil, and many other libraries by default. I think you’ll like it.


如何使用PIL调整图像大小并保持其纵横比?

问题:如何使用PIL调整图像大小并保持其纵横比?

有什么明显的方法可以实现我所缺少的吗?我只是想制作缩略图。

Is there an obvious way to do this that I’m missing? I’m just trying to make thumbnails.


回答 0

定义最大大小。然后,通过计算调整大小比例min(maxwidth/width, maxheight/height)

适当的大小是oldsize*ratio

当然,还有一个库方法可以做到这一点:method Image.thumbnail
以下是PIL文档中的一个(经过编辑的)示例。

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile

Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

The proper size is oldsize*ratio.

There is of course also a library method to do this: the method Image.thumbnail.
Below is an (edited) example from the PIL documentation.

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile

回答 1

该脚本将使用PIL(Python影像库)将图像(somepic.jpg)调整为300像素的宽度,并且高度与新宽度成比例。它通过确定原始宽度(img.size [0])的300个像素的百分比,然后将原始高度(img.size [1])乘以该百分比,来实现此目的。将“ basewidth”更改为任何其他数字以更改图像的默认宽度。

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('sompic.jpg') 

This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. Change “basewidth” to any other number to change the default width of your images.

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
img.save('sompic.jpg') 

回答 2

我还建议使用PIL的缩略图方法,因为它可以消除您的所有比率麻烦。

不过,有一个重要提示:替换

im.thumbnail(size)

im.thumbnail(size,Image.ANTIALIAS)

默认情况下,PIL使用Image.NEAREST过滤器来调整大小,这会导致性能良好但质量较差。

I also recommend using PIL’s thumbnail method, because it removes all the ratio hassles from you.

One important hint, though: Replace

im.thumbnail(size)

with

im.thumbnail(size,Image.ANTIALIAS)

by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor quality.


回答 3

基于@tomvon,我完成了以下操作(选择您的情况):

a)调整高度我知道新的宽度,所以我需要新的高度

new_width  = 680
new_height = new_width * height / width 

b)调整宽度我知道新的高度,所以我需要新的宽度

new_height = 680
new_width  = new_height * width / height

然后:

img = img.resize((new_width, new_height), Image.ANTIALIAS)

Based in @tomvon, I finished using the following (pick your case):

a) Resizing height (I know the new width, so I need the new height)

new_width  = 680
new_height = new_width * height / width 

b) Resizing width (I know the new height, so I need the new width)

new_height = 680
new_width  = new_height * width / height

Then just:

img = img.resize((new_width, new_height), Image.ANTIALIAS)

回答 4

PIL已经可以选择裁剪图像

img = ImageOps.fit(img, size, Image.ANTIALIAS)

PIL already has the option to crop an image

img = ImageOps.fit(img, size, Image.ANTIALIAS)

回答 5

from PIL import Image

img = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg
new_width  = 200
new_height = 300
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save('output image name.png') # format may what you want *.png, *jpg, *.gif
from PIL import Image

img = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg
new_width  = 200
new_height = 300
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save('output image name.png') # format may what you want *.png, *jpg, *.gif

回答 6

如果您尝试保持相同的宽高比,那么是否不按原始尺寸的某个百分比调整尺寸?

例如,原始尺寸的一半

half = 0.5
out = im.resize( [int(half * s) for s in im.size] )

If you are trying to maintain the same aspect ratio, then wouldn’t you resize by some percentage of the original size?

For example, half the original size

half = 0.5
out = im.resize( [int(half * s) for s in im.size] )

回答 7

from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))

我使用这个库:

pip install python-resize-image
from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))

I use this library:

pip install python-resize-image

回答 8

如果您不希望/不需要使用枕头打开图像,请使用以下命令:

from PIL import Image

new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))

If you don’t want / don’t have a need to open image with Pillow, use this:

from PIL import Image

new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))

回答 9

只需使用更现代的包装器更新此问题,该库即可包装Pillow(PIL的一个分支) https://pypi.org/project/python-resize-image/

允许你做这样的事情:

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()

在上面的链接中堆了更多示例。

Just updating this question with a more modern wrapper This library wraps Pillow (a fork of PIL) https://pypi.org/project/python-resize-image/

Allowing you to do something like this :-

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()

Heaps more examples in the above link.


回答 10

我试图调整幻灯片视频的某些图像的大小,因此,我不仅要一个最大尺寸,而且要一个最大宽度一个最大高度(视频帧的大小)。
总是有可能拍摄人像视频…
Image.thumbnail方法很有前途,但我无法将其放大到较小的图像。

因此,在找不到在此处(或其他位置)执行此操作的明显方法之后,我编写了此函数并将其放在此处以供以后使用:

from PIL import Image

def get_resized_img(img_path, video_size):
    img = Image.open(img_path)
    width, height = video_size  # these are the MAX dimensions
    video_ratio = width / height
    img_ratio = img.size[0] / img.size[1]
    if video_ratio >= 1:  # the video is wide
        if img_ratio <= video_ratio:  # image is not wide enough
            width_new = int(height * img_ratio)
            size_new = width_new, height
        else:  # image is wider than video
            height_new = int(width / img_ratio)
            size_new = width, height_new
    else:  # the video is tall
        if img_ratio >= video_ratio:  # image is not tall enough
            height_new = int(width / img_ratio)
            size_new = width, height_new
        else:  # image is taller than video
            width_new = int(height * img_ratio)
            size_new = width_new, height
    return img.resize(size_new, resample=Image.LANCZOS)

I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width and a max height (the size of the video frame).
And there was always the possibility of a portrait video…
The Image.thumbnail method was promising, but I could not make it upscale a smaller image.

So after I couldn’t find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:

from PIL import Image

def get_resized_img(img_path, video_size):
    img = Image.open(img_path)
    width, height = video_size  # these are the MAX dimensions
    video_ratio = width / height
    img_ratio = img.size[0] / img.size[1]
    if video_ratio >= 1:  # the video is wide
        if img_ratio <= video_ratio:  # image is not wide enough
            width_new = int(height * img_ratio)
            size_new = width_new, height
        else:  # image is wider than video
            height_new = int(width / img_ratio)
            size_new = width, height_new
    else:  # the video is tall
        if img_ratio >= video_ratio:  # image is not tall enough
            height_new = int(width / img_ratio)
            size_new = width, height_new
        else:  # image is taller than video
            width_new = int(height * img_ratio)
            size_new = width_new, height
    return img.resize(size_new, resample=Image.LANCZOS)

回答 11

一种用于保持约束比率并通过最大宽度/高度的简单方法。不是最漂亮的,但是可以完成工作并且很容易理解:

def resize(img_path, max_px_size, output_folder):
    with Image.open(img_path) as img:
        width_0, height_0 = img.size
        out_f_name = os.path.split(img_path)[-1]
        out_f_path = os.path.join(output_folder, out_f_name)

        if max((width_0, height_0)) <= max_px_size:
            print('writing {} to disk (no change from original)'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 > height_0:
            wpercent = max_px_size / float(width_0)
            hsize = int(float(height_0) * float(wpercent))
            img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 < height_0:
            hpercent = max_px_size / float(height_0)
            wsize = int(float(width_0) * float(hpercent))
            img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

这是一个使用此功能运行批处理图像大小调整的python脚本

A simple method for keeping constrained ratios and passing a max width / height. Not the prettiest but gets the job done and is easy to understand:

def resize(img_path, max_px_size, output_folder):
    with Image.open(img_path) as img:
        width_0, height_0 = img.size
        out_f_name = os.path.split(img_path)[-1]
        out_f_path = os.path.join(output_folder, out_f_name)

        if max((width_0, height_0)) <= max_px_size:
            print('writing {} to disk (no change from original)'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 > height_0:
            wpercent = max_px_size / float(width_0)
            hsize = int(float(height_0) * float(wpercent))
            img = img.resize((max_px_size, hsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

        if width_0 < height_0:
            hpercent = max_px_size / float(height_0)
            wsize = int(float(width_0) * float(hpercent))
            img = img.resize((max_px_size, wsize), Image.ANTIALIAS)
            print('writing {} to disk'.format(out_f_path))
            img.save(out_f_path)
            return

Here’s a python script that uses this function to run batch image resizing.


回答 12

已通过“ tomvon”更新了以上答案

from PIL import Image

img = Image.open(image_path)

width, height = img.size[:2]

if height > width:
    baseheight = 64
    hpercent = (baseheight/float(img.size[1]))
    wsize = int((float(img.size[0])*float(hpercent)))
    img = img.resize((wsize, baseheight), Image.ANTIALIAS)
    img.save('resized.jpg')
else:
    basewidth = 64
    wpercent = (basewidth/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((basewidth,hsize), Image.ANTIALIAS)
    img.save('resized.jpg')

Have updated the answer above by “tomvon”

from PIL import Image

img = Image.open(image_path)

width, height = img.size[:2]

if height > width:
    baseheight = 64
    hpercent = (baseheight/float(img.size[1]))
    wsize = int((float(img.size[0])*float(hpercent)))
    img = img.resize((wsize, baseheight), Image.ANTIALIAS)
    img.save('resized.jpg')
else:
    basewidth = 64
    wpercent = (basewidth/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((basewidth,hsize), Image.ANTIALIAS)
    img.save('resized.jpg')

回答 13

我的丑陋例子。

函数获取文件,例如:“ pic [0-9a-z]。[extension]”,将其大小调整为120×120,将节移动到中心并保存到“ ico [0-9a-z]。[extension]”,使用纵向和景观:

def imageResize(filepath):
    from PIL import Image
    file_dir=os.path.split(filepath)
    img = Image.open(filepath)

    if img.size[0] > img.size[1]:
        aspect = img.size[1]/120
        new_size = (img.size[0]/aspect, 120)
    else:
        aspect = img.size[0]/120
        new_size = (120, img.size[1]/aspect)
    img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
    img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])

    if img.size[0] > img.size[1]:
        new_img = img.crop( (
            (((img.size[0])-120)/2),
            0,
            120+(((img.size[0])-120)/2),
            120
        ) )
    else:
        new_img = img.crop( (
            0,
            (((img.size[1])-120)/2),
            120,
            120+(((img.size[1])-120)/2)
        ) )

    new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])

My ugly example.

Function get file like: “pic[0-9a-z].[extension]”, resize them to 120×120, moves section to center and save to “ico[0-9a-z].[extension]”, works with portrait and landscape:

def imageResize(filepath):
    from PIL import Image
    file_dir=os.path.split(filepath)
    img = Image.open(filepath)

    if img.size[0] > img.size[1]:
        aspect = img.size[1]/120
        new_size = (img.size[0]/aspect, 120)
    else:
        aspect = img.size[0]/120
        new_size = (120, img.size[1]/aspect)
    img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
    img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])

    if img.size[0] > img.size[1]:
        new_img = img.crop( (
            (((img.size[0])-120)/2),
            0,
            120+(((img.size[0])-120)/2),
            120
        ) )
    else:
        new_img = img.crop( (
            0,
            (((img.size[1])-120)/2),
            120,
            120+(((img.size[1])-120)/2)
        ) )

    new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])

回答 14

我以这种方式调整了图像的大小,并且效果很好

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image


def imageResize(image):
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) 
    imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') 
    outputIoStream.seek(0)
    uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)

    ## For upload local folder
    fs = FileSystemStorage()
    filename = fs.save(uploadedImage.name, uploadedImage)

I resizeed the image in such a way and it’s working very well

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image


def imageResize(image):
    outputIoStream = BytesIO()
    imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) 
    imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') 
    outputIoStream.seek(0)
    uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)

    ## For upload local folder
    fs = FileSystemStorage()
    filename = fs.save(uploadedImage.name, uploadedImage)

回答 15

我还将添加一个调整大小的版本,以保持宽高比固定。在这种情况下,它将根据初始宽高比asp_rat(为float(!))调整高度以匹配新图像的宽度。但是,要将宽度调整为高度,您只需要注释一条线,然后在else循环中取消注释另一条线即可。您会在哪里看到。

您不需要分号(;),我保留它们只是为了提醒自己我经常使用的语言的语法。

from PIL import Image

img_path = "filename.png";
img = Image.open(img_path);     # puts our image to the buffer of the PIL.Image object

width, height = img.size;
asp_rat = width/height;

# Enter new width (in pixels)
new_width = 50;

# Enter new height (in pixels)
new_height = 54;

new_rat = new_width/new_height;

if (new_rat == asp_rat):
    img = img.resize((new_width, new_height), Image.ANTIALIAS); 

# adjusts the height to match the width
# NOTE: if you want to adjust the width to the height, instead -> 
# uncomment the second line (new_width) and comment the first one (new_height)
else:
    new_height = round(new_width / asp_rat);
    #new_width = round(new_height * asp_rat);
    img = img.resize((new_width, new_height), Image.ANTIALIAS);

# usage: resize((x,y), resample)
# resample filter -> PIL.Image.BILINEAR, PIL.Image.NEAREST (default), PIL.Image.BICUBIC, etc..
# https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize

# Enter the name under which you would like to save the new image
img.save("outputname.png");

并且,它完成了。我尽力将其记录在案,因此很明显。

我希望这可能对那里的人有帮助!

I will also add a version of the resize that keeps the aspect ratio fixed. In this case, it will adjust the height to match the width of the new image, based on the initial aspect ratio, asp_rat, which is float (!). But, to adjust the width to the height, instead, you just need to comment one line and uncomment the other in the else loop. You will see, where.

You do not need the semicolons (;), I keep them just to remind myself of syntax of languages I use more often.

from PIL import Image

img_path = "filename.png";
img = Image.open(img_path);     # puts our image to the buffer of the PIL.Image object

width, height = img.size;
asp_rat = width/height;

# Enter new width (in pixels)
new_width = 50;

# Enter new height (in pixels)
new_height = 54;

new_rat = new_width/new_height;

if (new_rat == asp_rat):
    img = img.resize((new_width, new_height), Image.ANTIALIAS); 

# adjusts the height to match the width
# NOTE: if you want to adjust the width to the height, instead -> 
# uncomment the second line (new_width) and comment the first one (new_height)
else:
    new_height = round(new_width / asp_rat);
    #new_width = round(new_height * asp_rat);
    img = img.resize((new_width, new_height), Image.ANTIALIAS);

# usage: resize((x,y), resample)
# resample filter -> PIL.Image.BILINEAR, PIL.Image.NEAREST (default), PIL.Image.BICUBIC, etc..
# https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize

# Enter the name under which you would like to save the new image
img.save("outputname.png");

And, it is done. I tried to document it as much as I can, so it is clear.

I hope it might be helpful to someone out there!


回答 16

打开你的图片文件

from PIL import Image
im = Image.open("image.png")

使用PIL Image.resize(size,resample = 0)方法,在其中用图像的(宽度,高度)替换大小为2元组。

这将以原始尺寸显示图像:

display(im.resize((int(im.size[0]),int(im.size[1])), 0) )

这将以1/2尺寸显示图像:

display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )

这将以1/3的大小显示图像:

display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )

这将以1/4的大小显示图像:

display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )

Open your image file

from PIL import Image
im = Image.open("image.png")

Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

This will display your image at original size:

display(im.resize((int(im.size[0]),int(im.size[1])), 0) )

This will display your image at 1/2 the size:

display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )

This will display your image at 1/3 the size:

display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )

This will display your image at 1/4 the size:

display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )

etc etc


回答 17

from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))
from PIL import Image
from resizeimage import resizeimage

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

resize_file('foo.tif', 'foo_small.jpg', (256, 256))

回答 18

您可以通过以下代码调整图片大小:

From PIL import Image
img=Image.open('Filename.jpg') # paste image in python folder
print(img.size())
new_img=img.resize((400,400))
new_img.save('new_filename.jpg')

You can resize image by below code:

From PIL import Image
img=Image.open('Filename.jpg') # paste image in python folder
print(img.size())
new_img=img.resize((400,400))
new_img.save('new_filename.jpg')