054-python庫Pillow

上一篇:053-python庫PIL(三)

前記

PIL:Python Imaging Library组题,已經(jīng)是Python平臺(tái)事實(shí)上的圖像處理標(biāo)準(zhǔn)庫了吧凉。PIL功能非常強(qiáng)大钧敞,但API卻非常簡(jiǎn)單易用满粗。

由于PIL僅支持到Python 2.7殖熟,加上年久失修帆谍,于是一群志愿者在PIL的基礎(chǔ)上創(chuàng)建了兼容的版本培己,名字叫Pillow巡揍,支持最新Python 3.x蘑斧,又加入了許多新特性,因此边翼,我們可以直接安裝使用Pillow鱼响。

一、安裝Pillow

如果安裝了Anaconda组底,Pillow就已經(jīng)可用了丈积。否則,需要在命令行下通過pip安裝:

$ pip install pillow

如果遇到Permission denied安裝失敗债鸡,請(qǐng)加上sudo重試桶癣。

操作圖像示例

from PIL import Image

# 打開一個(gè)jpg圖像文件,注意是當(dāng)前路徑:
im = Image.open('test.jpg')
# 獲得圖像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 縮放到50%:
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把縮放后的圖像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')

其他功能如切片娘锁、旋轉(zhuǎn)牙寞、濾鏡、輸出文字莫秆、調(diào)色板等一應(yīng)俱全间雀。

from PIL import Image, ImageFilter

# 打開一個(gè)jpg圖像文件,注意是當(dāng)前路徑:
im = Image.open('test.jpg')
# 應(yīng)用模糊濾鏡:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')

PIL的ImageDraw提供了一系列繪圖方法镊屎,讓我們可以直接繪圖惹挟。比如要生成字母驗(yàn)證碼圖片:

from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random

# 隨機(jī)字母:
def rndChar():
    return chr(random.randint(65, 90))

# 隨機(jī)顏色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 隨機(jī)顏色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 創(chuàng)建Font對(duì)象:
font = ImageFont.truetype('Arial.ttf', 36)
# 創(chuàng)建Draw對(duì)象:
draw = ImageDraw.Draw(image)
# 填充每個(gè)像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 輸出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

我們用隨機(jī)顏色填充背景,再畫上文字缝驳,最后對(duì)圖像進(jìn)行模糊连锯,得到驗(yàn)證碼圖片如下:

image.png

如果運(yùn)行的時(shí)候報(bào)錯(cuò):

IOError: cannot open resource

這是因?yàn)镻IL無法定位到字體文件的位置,可以根據(jù)操作系統(tǒng)提供絕對(duì)路徑用狱,比如:

'/Library/Fonts/Arial.ttf'

二运怖、官方文檔

pillow官方文檔

image.png
image.png
Warnings(需要特別注意)

Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.

Pillow庫和PIL庫不能在相同的環(huán)境中共存。在安裝Pillow庫之前,請(qǐng)卸載PIL庫夏伊。

Pillow >= 1.0 no longer supports “import Image”. Please use “from PIL import Image” instead.

Pillow庫> = 1.0不再支持“import Image”摇展。請(qǐng)使用“from PIL import Image”。

Pillow >= 2.1.0 no longer supports “import _imaging”. Please use “from PIL.Image import core as _imaging” instead.

Pillow庫> = 2.1.0不再支持“import _imaging”溺忧。請(qǐng)使用“from PIL.Image import core as _imaging”代替咏连。

版本支持列表:

image.png

三、細(xì)說安裝

The following instructions will install Pillow with support for most common image formats. See External Libraries for a full list of external libraries supported.

下面的說明將安裝Pillow庫支持最常用的圖像格式鲁森∷畹危看到外部庫的完整列表外部庫支持。

Install Pillow with pip:

$ pip install Pillow
  • Windows Installation(Windows安裝)

We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included except for raqm and libimagequant:

我們提供Pillow庫為Windows二進(jìn)制文件編譯支持矩陣的蟒蛇在32和64位版本輪,雞蛋,和可執(zhí)行的安裝程序歌溉。這些二進(jìn)制文件的所有可選庫包括除了raqm和libimagequant:

> pip install Pillow
  • macOS Installation(macOS安裝)

We provide binaries for macOS for each of the supported Python versions in the wheel format. These include support for all optional libraries except libimagequant. Raqm support requires libraqm, fribidi, and harfbuzz to be installed separately:

我們提供二進(jìn)制文件為每個(gè)支持的macOS車輪格式的Python版本垄懂。這包括支持所有可選庫libimagequant除外。Raqm支持需要libraqm、fribidi harfbuzz單獨(dú)安裝:

$ pip install Pillow
  • Linux Installation(Linux安裝)

We provide binaries for Linux for each of the supported Python versions in the manylinux wheel format. These include support for all optional libraries except libimagequant. Raqm support requires libraqm, fribidi, and harfbuzz to be installed separately:

我們?yōu)長(zhǎng)inux提供二進(jìn)制文件為每個(gè)支持的Python版本manylinux輪格式埠偿。這包括支持所有可選庫libimagequant除外。Raqm支持需要libraqm榜晦、fribidi harfbuzz單獨(dú)安裝:

$ pip install Pillow

Most major Linux distributions, including Fedora, Debian/Ubuntu and ArchLinux also include Pillow in packages that previously contained PIL e.g. python-imaging.

大多數(shù)Linux發(fā)行版默認(rèn)包含Pillow庫,包括Fedora, Debian / Ubuntu和ArchLinux還包括以前包含PIL庫如python-imaging 包冠蒋。

FreeBSD Installation(FreeBSD安裝)

Pillow can be installed on FreeBSD via the official Ports or Packages systems:

Pillow庫可以通過官方的渠道或包系統(tǒng)安裝在FreeBSD系統(tǒng):

Ports:

$ cd /usr/ports/graphics/py-pillow && make install clean

Packages:

$ pkg install py27-pillow

The Pillow FreeBSD port and packages are tested by the ports team with all supported FreeBSD versions and against Python 2.7 and 3.x.

Pillow庫FreeBSD港口和包由端口測(cè)試團(tuán)隊(duì)與所有支持FreeBSD和Python 2.7版本和3.x版本。

Building From Source(從源代碼構(gòu)建)

Download and extract the compressed archive from PyPI.

從PyPI下載和提取壓縮存檔乾胶。

  • External Libraries(外部庫)

You do not need to install all supported external libraries to use Pillow’s basic features. Zlib and libjpeg are required by default.

你不需要安裝所有支持的外部庫使用Pillow庫的基本特性抖剿。Zlib和libjpeg默認(rèn)是必需的。

There are scripts to install the dependencies for some operating systems included in the depends directory. Also see the Dockerfiles in our docker images repo.

腳本安裝的依賴關(guān)系有一些操作系統(tǒng)包含在看目錄识窿。也在docker images repo看到Dockerfiles斩郎。

Pillow庫的許多特性需要外部庫:

libjpeg provides JPEG functionality.
Pillow has been tested with libjpeg versions 6b, 8, 9-9c and libjpeg-turbo version 8.
Starting with Pillow 3.0.0, libjpeg is required by default, but may be disabled with the --disable-jpeg flag.
zlib provides access to compressed PNGs
Starting with Pillow 3.0.0, zlib is required by default, but may be disabled with the --disable-zlib flag.
libtiff provides compressed TIFF functionality
Pillow has been tested with libtiff versions 3.x and 4.0
libfreetype provides type related services
littlecms provides color management
Pillow version 2.2.1 and below uses liblcms1, Pillow 2.3.0 and above uses liblcms2. Tested with 1.19 and 2.7-2.9.
libwebp provides the WebP format.
Pillow has been tested with version 0.1.3, which does not read transparent WebP files. Versions 0.3.0 and above support transparency.
tcl/tk provides support for tkinter bitmap and photo images.
openjpeg provides JPEG 2000 functionality.
Pillow has been tested with openjpeg 2.0.0 and 2.1.0.
Pillow does not support the earlier 1.5 series which ships with Ubuntu <= 14.04 and Debian Jessie.
libimagequant provides improved color quantization
Pillow has been tested with libimagequant 2.6-2.12.2
Libimagequant is licensed GPLv3, which is more restrictive than the Pillow license, therefore we will not be distributing binaries with libimagequant support enabled.
Windows support: Libimagequant requires VS2013/MSVC 18 to compile, so it is unlikely to work with Python 2.7 on Windows.
libraqm provides complex text layout support.
libraqm provides bidirectional text support (using FriBiDi), shaping (using HarfBuzz), and proper script itemization. As a result, Raqm can support most writing systems covered by Unicode.
libraqm depends on the following libraries: FreeType, HarfBuzz, FriBiDi, make sure that you install them before installing libraqm if not available as package in your system.
setting text direction or font features is not supported without libraqm.
libraqm is dynamically loaded in Pillow 5.0.0 and above, so support is available if all the libraries are installed.
Windows support: Raqm support is currently unsupported on Windows.

詳見官方文檔查看

Once you have installed the prerequisites, run:

一旦你安裝了先決條件,運(yùn)行:

$ pip install Pillow

If the prerequisites are installed in the standard library locations for your machine (e.g. /usr or /usr/local), no additional configuration should be required. If they are installed in a non-standard location, you may need to configure setuptools to use those locations by editing setup.py or setup.cfg, or by adding environment variables on the command line:

如果前提是安裝在機(jī)器的標(biāo)準(zhǔn)庫的位置(例如,/ usr或/usr/local),不需要額外的配置。如果他們是安裝在標(biāo)準(zhǔn)位置,您可能需要配置使用setuptools這些位置通過編輯設(shè)置喻频。py或設(shè)置缩宜。cfg或在命令行上添加環(huán)境變量:

$ CFLAGS="-I/usr/pkg/include" pip install pillow

If Pillow has been previously built without the required prerequisites, it may be necessary to manually clear the pip cache or build without cache using the --no-cache-dir option to force a build with newly installed external libraries.

如果枕頭之前構(gòu)建沒有所需的先決條件,可能需要手動(dòng)清除pip緩存或構(gòu)建緩存使用——no-cache-dir選項(xiàng)強(qiáng)制建立和新安裝的外部庫。

  • Build Options(構(gòu)建選項(xiàng))

Environment variable: MAX_CONCURRENCY=n. By default, Pillow will use multiprocessing to build the extension on all available CPUs, but not more than 4. Setting MAX_CONCURRENCY to 1 will disable parallel building.

Build flags: --disable-zlib, --disable-jpeg, --disable-tiff, --disable-freetype, --disable-lcms, --disable-webp, --disable-webpmux, --disable-jpeg2000, --disable-imagequant. Disable building the corresponding feature even if the development libraries are present on the building machine.

Build flags: --enable-zlib, --enable-jpeg, --enable-tiff, --enable-freetype, --enable-lcms, --enable-webp, --enable-webpmux, --enable-jpeg2000, --enable-imagequant. Require that the corresponding feature is built. The build will raise an exception if the libraries are not found. Webpmux (WebP metadata) relies on WebP support. Tcl and Tk also must be used together.

Build flag: --disable-platform-guessing. Skips all of the platform dependent guessing of include and library directories for automated build systems that configure the proper paths in the environment variables (e.g. Buildroot).

Build flag: --debug. Adds a debugging flag to the include and library search process to dump all paths searched for and found to stdout.

Sample usage:

$ MAX_CONCURRENCY=1 python setup.py build_ext --enable-[feature] install

or using pip:

$ pip install pillow --global-option="build_ext" --global-option="--enable-[feature]"
Building on macOS(建立在macOS)

The Xcode command line tools are required to compile portions of Pillow. The tools are installed by running xcode-select --install from the command line. The command line tools are required even if you have the full Xcode package installed. It may be necessary to run sudo xcodebuild -license to accept the license prior to using the tools.

Xcode命令行工具需要編譯的部分枕頭甥温。安裝的工具運(yùn)行xcode-select——從命令行安裝锻煌。命令行工具是必需的,即使你有完整的Xcode包安裝∫鲵荆可能需要運(yùn)行sudo xcodebuild許可證之前接受許可使用的工具宋梧。

The easiest way to install external libraries is via Homebrew. After you install Homebrew, run:

安裝外部庫最簡(jiǎn)單的方法是通過自制程序。你安裝自制程序后,運(yùn)行:

$ brew install libtiff libjpeg webp little-cms2

To install libraqm on macOS use Homebrew to install its dependencies:

安裝libraqm macOS使用自制程序來安裝它的依賴關(guān)系:

$ brew install freetype harfbuzz fribidi

Then see depends/install_raqm_cmake.sh to install libraqm.

然后看depends/install_raqm_cmake.sh狰挡。安裝libraqm捂龄。

Now install Pillow with:

現(xiàn)在安裝枕頭:

$ pip install Pillow

or from within the uncompressed source directory:

或在未壓縮的源目錄:

$ python setup.py install
Building on Windows(Windows上)

We don’t recommend trying to build on Windows. It is a maze of twisty passages, mostly dead ends. There are build scripts and notes for the Windows build in the winbuild directory.

我們不建議試圖建立在Windows。彎彎曲曲的通道是一個(gè)迷宮,大多是死胡同加叁。有構(gòu)建腳本和筆記的Windows建立winbuild目錄倦沧。

Building on FreeBSD

Only FreeBSD 10 and 11 tested

只有FreeBSD 10和11測(cè)試過

Make sure you have Python’s development libraries installed.:

確保您已經(jīng)安裝了Python的開發(fā)庫。

$ sudo pkg install python2

Or for Python 3:

$ sudo pkg install python3

Prerequisites are installed on FreeBSD 10 or 11 with:

先決條件是安裝在FreeBSD 10或11:

$ sudo pkg install jpeg-turbo tiff webp lcms2 freetype2 openjpeg harfbuzz fribidi

Then see depends/install_raqm_cmake.sh to install libraqm.

然后看depends/install_raqm_cmake.sh它匕。安裝libraqm刀脏。

Building on Linux

If you didn’t build Python from source, make sure you have Python’s development libraries installed.

如果你沒有從源代碼構(gòu)建Python,確保您已經(jīng)安裝了Python的開發(fā)庫。

In Debian or Ubuntu:

$ sudo apt-get install python-dev python-setuptools

Or for Python 3:

$ sudo apt-get install python3-dev python3-setuptools

In Fedora, the command is:

$ sudo dnf install python-devel redhat-rpm-config

Or for Python 3:

$ sudo dnf install python3-devel redhat-rpm-config

redhat-rpm-config is required on Fedora 23, but not earlier versions.

redhat-rpm-config在Fedora 23是必需的,但不是早期版本超凳。

Prerequisites are installed on Ubuntu 14.04 LTS with:

Ubuntu 14.04 LTS上安裝先決條件:

$ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev \
    libfreetype6-dev liblcms2-dev libwebp-dev libharfbuzz-dev libfribidi-dev \
    tcl8.6-dev tk8.6-dev python-tk

Then see depends/install_raqm.sh to install libraqm.

Prerequisites are installed on recent RedHat Centos or Fedora with:

最近RedHat Centos或Fedora上安裝先決條件:

$ sudo dnf install libtiff-devel libjpeg-devel zlib-devel freetype-devel \
    lcms2-devel libwebp-devel tcl-devel tk-devel libraqm-devel \
    libimagequant-devel

Note that the package manager may be yum or dnf, depending on the exact distribution.

注意,包管理器可能是百勝或dnf,取決于具體的分布愈污。

See also the Dockerfiles in the Test Infrastructure repo (https://github.com/python-pillow/docker-images) for a known working install process for other tested distros.

參見測(cè)試基礎(chǔ)設(shè)施中的Dockerfiles回購(gòu)(https://github.com/python-pillow/docker-images)一個(gè)已知的工作為其他測(cè)試發(fā)行版安裝過程。

Building on Android

Basic Android support has been added for compilation within the Termux environment. The dependencies can be installed by:

基本的Android支持Termux中已經(jīng)添加了編譯環(huán)境轮傍≡荼ⅲ可以安裝的依賴關(guān)系:

$ pkg -y install python python-dev ndk-sysroot clang make \
    libjpeg-turbo-dev

這是測(cè)試在Termux應(yīng)用ChromeOS,在x86上。

Platform Support(平臺(tái)支持)

Current platform support for Pillow. Binary distributions are contributed for each release on a volunteer basis, but the source should compile and run everywhere platform support is listed. In general, we aim to support all current versions of Linux, macOS, and Windows.

當(dāng)前平臺(tái)支持庫Pillow创夜。二進(jìn)制發(fā)行版提供志愿者的基礎(chǔ)上為每一個(gè)版本,但源應(yīng)該編譯和運(yùn)行平臺(tái)支持上市杭跪。一般來說,我們的目標(biāo)是支持所有當(dāng)前版本的Linux, macOS和Windows。

  • Continuous Integration Targets(持續(xù)集成的目標(biāo))

These platforms are built and tested for every change.

這些平臺(tái)構(gòu)建和測(cè)試每一個(gè)變化。

image.png

Mac OS X CI is not run for every commit, but is run for every release.

Mac OS X CI不是運(yùn)行每一個(gè)提交,但每個(gè)發(fā)布版本都可運(yùn)行涧尿。

Other Platforms

These platforms have been reported to work at the versions mentioned.

這些平臺(tái)在提到的版本已報(bào)告工作系奉。

Contributors please test Pillow on your platform then update this document and send a pull request.

投稿者請(qǐng)測(cè)試枕在你的平臺(tái)上然后更新這個(gè)文檔和發(fā)送一個(gè)請(qǐng)求。

image.png
Old Versions

You can download old distributions from the release history at PyPI and by direct URL access eg. https://pypi.org/project/Pillow/1.0/.

您可以下載舊的分布在PyPI釋放歷史和直接的URL訪問姑廉。https://pypi.org/project/Pillow/1.0/缺亮。

附:Handbook手冊(cè)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市桥言,隨后出現(xiàn)的幾起案子萌踱,更是在濱河造成了極大的恐慌,老刑警劉巖号阿,帶你破解...
    沈念sama閱讀 216,651評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件并鸵,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡扔涧,警方通過查閱死者的電腦和手機(jī)园担,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枯夜,“玉大人粉铐,你說我怎么就攤上這事÷钡担” “怎么了蝙泼?”我有些...
    開封第一講書人閱讀 162,931評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)劝枣。 經(jīng)常有香客問我汤踏,道長(zhǎng),這世上最難降的妖魔是什么舔腾? 我笑而不...
    開封第一講書人閱讀 58,218評(píng)論 1 292
  • 正文 為了忘掉前任溪胶,我火速辦了婚禮,結(jié)果婚禮上稳诚,老公的妹妹穿的比我還像新娘哗脖。我一直安慰自己,他們只是感情好扳还,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評(píng)論 6 388
  • 文/花漫 我一把揭開白布才避。 她就那樣靜靜地躺著,像睡著了一般氨距。 火紅的嫁衣襯著肌膚如雪桑逝。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,198評(píng)論 1 299
  • 那天俏让,我揣著相機(jī)與錄音楞遏,去河邊找鬼茬暇。 笑死,一個(gè)胖子當(dāng)著我的面吹牛寡喝,可吹牛的內(nèi)容都是我干的糙俗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,084評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼预鬓,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼巧骚!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起珊皿,我...
    開封第一講書人閱讀 38,926評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎巨税,沒想到半個(gè)月后蟋定,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評(píng)論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡草添,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評(píng)論 2 333
  • 正文 我和宋清朗相戀三年驶兜,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片远寸。...
    茶點(diǎn)故事閱讀 39,731評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡抄淑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出驰后,到底是詐尸還是另有隱情肆资,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評(píng)論 5 343
  • 正文 年R本政府宣布灶芝,位于F島的核電站郑原,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏夜涕。R本人自食惡果不足惜犯犁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評(píng)論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望女器。 院中可真熱鬧酸役,春花似錦、人聲如沸驾胆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丧诺。三九已至暑塑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間锅必,已是汗流浹背事格。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工惕艳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人驹愚。 一個(gè)月前我還...
    沈念sama閱讀 47,743評(píng)論 2 368
  • 正文 我出身青樓远搪,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親逢捺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子谁鳍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容