python庫pillow(python 官方庫)

本文目錄一覽:

python的pillow庫怎麼使用

Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。

1)使用 Image 類

PIL最重要的類是 Image class, 你可以通過多種方法創建這個類的實例;你可以從文件載入圖像,或者處理其他圖像, 或者從 scratch 創建。

要從文件載入圖像,可以使用open( )函數,在Image模塊中:

[python] view plain copy

 from PIL import Image

 im = Image.open(“E:/photoshop/1.jpg”)

載入成功後,將返回一個Image對象,可以通過使用示例屬性查看文件內容:

[python] view plain copy

 print(im.format, im.size, im.mode)

(‘JPEG’, (600, 351), ‘RGB’)

format 這個屬性標識了圖像來源。如果圖像不是從文件讀取它的值就是None。size屬性是一個二元tuple,包含width和height(寬度和高度,單位都是px)。 mode 屬性定義了圖像bands的數量和名稱,以及像素類型和深度。常見的modes 有 「L」 (luminance) 表示灰度圖像, 「RGB」 表示真彩色圖像, and 「CMYK」 表示出版圖像。

如果文件打開錯誤,返回 IOError 錯誤。

只要你有了 Image 類的實例,你就可以通過類的方法處理圖像。比如,下列方法可以顯示圖像:

[python] view plain copy

im.show()

2)讀寫圖像

PIL 模塊支持大量圖片格式。使用在 Image 模塊的 open() 函數從磁碟讀取文件。你不需要知道文件格式就能打開它,這個庫能夠根據文件內容自動確定文件格式。要保存文件,使用 Image 類的 save() 方法。保存文件的時候文件名變得重要了。除非你指定格式,否則這個庫將會以文件名的擴展名作為格式保存。

載入文件,並轉化為png格式:

[python] view plain copy

“Python Image Library Test”

from PIL import Image

import os

import sys

for infile in sys.argv[1:]:

f,e = os.path.splitext(infile)

outfile = f +”.png”

if infile != outfile:

try:

Image.open(infile).save(outfile)

except IOError:

print(“Cannot convert”, infile)

save() 方法的第二個參數可以指定文件格式。

3)創建縮略圖

縮略圖是網路開發或圖像軟體預覽常用的一種基本技術,使用Python的Pillow圖像庫可以很方便的建立縮略圖,如下:

[python] view plain copy

# create thumbnail

size = (128,128)

for infile in glob.glob(“E:/photoshop/*.jpg”):

f, ext = os.path.splitext(infile)

img = Image.open(infile)

img.thumbnail(size,Image.ANTIALIAS)

img.save(f+”.thumbnail”,”JPEG”)

上段代碼對photoshop下的jpg圖像文件全部創建縮略圖,並保存,glob模塊是一種智能化的文件名匹配技術,在批圖像處理中經常會用到。

注意:Pillow庫不會直接解碼或者載入圖像柵格數據。當你打開一個文件,只會讀取文件頭信息用來確定格式,顏色模式,大小等等,文件的剩餘部分不會主動處理。這意味著打開一個圖像文件的操作十分快速,跟圖片大小和壓縮方式無關。

4)圖像的剪切、粘貼與合併操作

Image 類包含的方法允許你操作圖像部分選區,PIL.Image.Image.crop 方法獲取圖像的一個子矩形選區,如:

[python] view plain copy

# crop, paste and merge

im = Image.open(“E:/photoshop/lena.jpg”)

box = (100,100,300,300)

region = im.crop(box)

矩形選區有一個4元元組定義,分別表示左、上、右、下的坐標。這個庫以左上角為坐標原點,單位是px,所以上訴代碼複製了一個 200×200 pixels 的矩形選區。這個選區現在可以被處理並且粘貼到原圖。

[python] view plain copy

region = region.transpose(Image.ROTATE_180)

im.paste(region, box)

當你粘貼矩形選區的時候必須保證尺寸一致。此外,矩形選區不能在圖像外。然而你不必保證矩形選區和原圖的顏色模式一致,因為矩形選區會被自動轉換顏色。

5)分離和合併顏色通道

對於多通道圖像,有時候在處理時希望能夠分別對每個通道處理,處理完成後重新合成多通道,在Pillow中,很簡單,如下:

[python] view plain copy

r,g,b = im.split()

im = Image.merge(“RGB”, (r,g,b))

對於split( )函數,如果是單通道的,則返回其本身,否則,返回各個通道。

6)幾何變換

對圖像進行幾何變換是一種基本處理,在Pillow中包括resize( )和rotate( ),如用法如下:

[python] view plain copy

out = im.resize((128,128))

out = im.rotate(45)  # degree conter-clockwise

其中,resize( )函數的參數是一個新圖像大小的元祖,而rotate( )則需要輸入順時針的旋轉角度。在Pillow中,對於一些常見的旋轉作了專門的定義:

[python] view plain copy

out = im.transpose(Image.FLIP_LEFT_RIGHT)

out = im.transpose(Image.FLIP_TOP_BOTTOM)

out = im.transpose(Image.ROTATE_90)

out = im.transpose(Image.ROTATE_180)

out = im.transpose(Image.ROTATE_270)

7)顏色空間變換

在處理圖像時,根據需要進行顏色空間的轉換,如將彩色轉換為灰度:

[python] view plain copy

cmyk = im.convert(“CMYK”)

gray = im.convert(“L”)

8)圖像濾波

圖像濾波在ImageFilter 模塊中,在該模塊中,預先定義了很多增強濾波器,可以通過filter( )函數使用,預定義濾波器包括:

BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。其中BLUR就是均值濾波,CONTOUR找輪廓,FIND_EDGES邊緣檢測,使用該模塊時,需先導入,使用方法如下:

[python] view plain copy

from PIL import ImageFilter

imgF = Image.open(“E:/photoshop/lena.jpg”)

outF = imgF.filter(ImageFilter.DETAIL)

conF = imgF.filter(ImageFilter.CONTOUR)

edgeF = imgF.filter(ImageFilter.FIND_EDGES)

imgF.show()

outF.show()

conF.show()

edgeF.show()

除此以外,ImageFilter模塊還包括一些擴展性強的濾波器:

class PIL.ImageFilter.GaussianBlur(radius=2)

Gaussian blur filter.

參數:

radius – Blur radius.    

class PIL.ImageFilter.UnsharpMask(radius=2, percent=150, threshold=3)

Unsharp mask filter.

See Wikipedia』s entry on digital unsharp masking for an explanation of the parameters.

class PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)

Create a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels.

In the current version, kernels can only be applied to 「L」 and 「RGB」 images.

參數:

size – Kernel size, given as (width, height). In the current version, this must be (3,3) or (5,5).

kernel – A sequence containing kernel weights.

scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.

offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor.

class PIL.ImageFilter.RankFilter(size, rank)

Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns therank『th value.

參數:

size – The kernel size, in pixels.

rank – What pixel value to pick. Use 0 for a min filter, size * size / 2 for a median filter, size * size – 1 for a max filter, etc.

class PIL.ImageFilter.MedianFilter(size=3)

Create a median filter. Picks the median pixel value in a window with the given size.

參數:

size – The kernel size, in pixels.    

class PIL.ImageFilter.MinFilter(size=3)

Create a min filter. Picks the lowest pixel value in a window with the given size.

參數:

size – The kernel size, in pixels.    

class PIL.ImageFilter.MaxFilter(size=3)

Create a max filter. Picks the largest pixel value in a window with the given size.

參數:

size – The kernel size, in pixels.    

class PIL.ImageFilter.ModeFilter(size=3)

Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved.

參數:

size – The kernel size, in pixels.    

更多詳細內容可以參考:PIL/ImageFilter

9)圖像增強

圖像增強也是圖像預處理中的一個基本技術,Pillow中的圖像增強函數主要在ImageEnhance模塊下,通過該模塊可以調節圖像的顏色、對比度和飽和度和銳化等:

[python] view plain copy

from PIL import ImageEnhance

imgE = Image.open(“E:/photoshop/lena.jpg”)

imgEH = ImageEnhance.Contrast(imgE)

imgEH.enhance(1.3).show(“30% more contrast”)

圖像增強:

class PIL.ImageEnhance.Color(image)

Adjust image color balance.

This class can be used to adjust the colour balance of an image, in a manner similar to the controls on a colour TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Contrast(image)

Adjust image contrast.

This class can be used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Brightness(image)

Adjust image brightness.

This class can be used to control the brighntess of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image.

class PIL.ImageEnhance.Sharpness(image)

Adjust image sharpness.

This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image.

圖像增強的詳細內容可以參考:PIL/ImageEnhance

除了以上介紹的內容外,Pillow還有很多強大的功能:

PIL.Image.alpha_composite(im1, im2)

PIL.Image.blend(im1, im2, alpha)

PIL.Image.composite(image1, image2, mask)

PIL.Image.eval(image, *args)

PIL.Image.fromarray(obj, mode=None)

PIL.Image.frombuffer(mode, size, data, decoder_name=’raw’, *args)

怎樣安裝python的圖像處理庫pillow

找到easy_install.exe工具。在windows下安裝Python後,在其安裝路徑下的scripts文件中默認安裝好了easy_install工具。完整路徑如下例:D:\Python27\Scripts\easy_install.exe;其中為我python的安裝路徑,大家可以根據自己的安裝路徑更改。

使用easy_install.exe工具一鍵安裝pip.打開cmd,輸入安裝命令。操作命令如下圖所示:

pip安裝成功後,在cmd下執行pip,將會有如下提示。

再通過pip進行一鍵安裝Pillow。pip類似RedHat裡面的yum,安裝Python包非常方便。操作命令如下圖所示:

5

到這一步就安裝好了。馬上用起來吧,下圖是用這個庫將圖片轉換的字元畫。轉換後有點大,分割成兩張了。

python3 pillow有哪些功能

安裝剛接觸Pillow的朋友先來看一下Pillow的安裝方法,在這裡我們以Mac OS環境為例: (1)、使用 pip 安裝 Python 庫。pip 是 Python 的包管理工具,安裝後就可以直接在命令行一站式地安裝/管理各種庫了(pip 文檔)。

$ wget

tar xzf pip-0.7.2.tar.gz$ cd pip-0.7.2$ python setup.py install

(2)、使用 pip 下載獲取 Pillow:

$ pip install pillow

(3)、安裝過程中命令行出現錯誤提示:」error: command 『clang’ failed with exit status

1」。上網查閱,發現需要通過 Xcode 更新 Command Line Tool。於是打開

Xcode-Preferences-Downloads-Components選項卡。咦?竟然沒了 Command Line

Tools。再查,發現 Xcode 5 以上現在需要用命令行安裝:

$ xcode-select —install

系統會彈出安裝命令行工具的提示,點擊安裝即可。

此時再 pip install pillow,就安裝成功了。

pip freeze 命令查看已經安裝的 Python 包,Pillow 已經乖乖躺那兒了。

好了,下面開始進入教程~

Image類

Pillow中最重要的類就是Image,該類存在於同名的模塊中。可以通過以下幾種方式實例化:從文件中讀取圖片,處理其他圖片得到,或者直接創建一個圖片。

使用Image模塊中的open函數打開一張圖片:

from PIL import Image im = Image.open(“lena.ppm”)

如果打開成功,返回一個Image對象,可以通過對象屬性檢查文件內容

python的pillow庫怎麼處理灰度圖像

Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。

1)使用 Image 類

PIL最重要的類是 Image class, 你可以通過多種方法創建這個類的實例;你可以從文件載入圖像,或者處理其他圖像, 或者從 scratch 創建。

要從文件載入圖像,可以使用open( )函數,在Image模塊中:

from PIL import Image

im = Image.open(“E:/photoshop/1.jpg”)

載入成功後,將返回一個Image對象,可以通過使用示例屬性查看文件內容:

print(im.format, im.size, im.mode)

(‘JPEG’, (600, 351), ‘RGB’)

format 這個屬性標識了圖像來源。如果圖像不是從文件讀取它的值就是None。size屬性是一個二元tuple,包含width和height(寬度和高度,單位都是px)。 mode 屬性定義了圖像bands的數量和名稱,以及像素類型和深度。常見的modes 有 「L」 (luminance) 表示灰度圖像, 「RGB」 表示真彩色圖像, and 「CMYK」 表示出版圖像。

如果文件打開錯誤,返回 IOError 錯誤。

只要你有了 Image 類的實例,你就可以通過類的方法處理圖像。比如,下列方法可以顯示圖像:

im.show()

2)讀寫圖像

PIL 模塊支持大量圖片格式。使用在 Image 模塊的 open() 函數從磁碟讀取文件。你不需要知道文件格式就能打開它,這個庫能夠根據文件內容自動確定文件格式。要保存文件,使用 Image 類的 save() 方法。保存文件的時候文件名變得重要了。除非你指定格式,否則這個庫將會以文件名的擴展名作為格式保存。

載入文件,並轉化為png格式:

“Python Image Library Test”

from PIL import Image

import os

import sys

for infile in sys.argv[1:]:

f,e = os.path.splitext(infile)

outfile = f +”.png”

if infile != outfile:

try:

Image.open(infile).save(outfile)

except IOError:

print(“Cannot convert”, infile)

save() 方法的第二個參數可以指定文件格式。

3)創建縮略圖

縮略圖是網路開發或圖像軟體預覽常用的一種基本技術,使用Python的Pillow圖像庫可以很方便的建立縮略圖,如下:

# create thumbnail

size = (128,128)

for infile in glob.glob(“E:/photoshop/*.jpg”):

f, ext = os.path.splitext(infile)

img = Image.open(infile)

img.thumbnail(size,Image.ANTIALIAS)

img.save(f+”.thumbnail”,”JPEG”)

上段代碼對photoshop下的jpg圖像文件全部創建縮略圖,並保存,glob模塊是一種智能化的文件名匹配技術,在批圖像處理中經常會用到。

注意:Pillow庫不會直接解碼或者載入圖像柵格數據。當你打開一個文件,只會讀取文件頭信息用來確定格式,顏色模式,大小等等,文件的剩餘部分不會主動處理。這意味著打開一個圖像文件的操作十分快速,跟圖片大小和壓縮方式無關。

4)圖像的剪切、粘貼與合併操作

Image 類包含的方法允許你操作圖像部分選區,PIL.Image.Image.crop 方法獲取圖像的一個子矩形選區,如:

# crop, paste and merge

im = Image.open(“E:/photoshop/lena.jpg”)

box = (100,100,300,300)

region = im.crop(box)

矩形選區有一個4元元組定義,分別表示左、上、右、下的坐標。這個庫以左上角為坐標原點,單位是px,所以上訴代碼複製了一個 200×200 pixels 的矩形選區。這個選區現在可以被處理並且粘貼到原圖。

region = region.transpose(Image.ROTATE_180)

im.paste(region, box)

當你粘貼矩形選區的時候必須保證尺寸一致。此外,矩形選區不能在圖像外。然而你不必保證矩形選區和原圖的顏色模式一致,因為矩形選區會被自動轉換顏色。

5)分離和合併顏色通道

對於多通道圖像,有時候在處理時希望能夠分別對每個通道處理,處理完成後重新合成多通道,在Pillow中,很簡單,如下:

r,g,b = im.split()

im = Image.merge(“RGB”, (r,g,b))

對於split( )函數,如果是單通道的,則返回其本身,否則,返回各個通道。

6)幾何變換

對圖像進行幾何變換是一種基本處理,在Pillow中包括resize( )和rotate( ),如用法如下:

out = im.resize((128,128))

out = im.rotate(45) # degree conter-clockwise

其中,resize( )函數的參數是一個新圖像大小的元祖,而rotate( )則需要輸入順時針的旋轉角度。在Pillow中,對於一些常見的旋轉作了專門的定義:

out = im.transpose(Image.FLIP_LEFT_RIGHT)

out = im.transpose(Image.FLIP_TOP_BOTTOM)

out = im.transpose(Image.ROTATE_90)

out = im.transpose(Image.ROTATE_180)

out = im.transpose(Image.ROTATE_270)

7)顏色空間變換

在處理圖像時,根據需要進行顏色空間的轉換,如將彩色轉換為灰度:

cmyk = im.convert(“CMYK”)

gray = im.convert(“L”)

8)圖像濾波

圖像濾波在ImageFilter 模塊中,在該模塊中,預先定義了很多增強濾波器,可以通過filter( )函數使用,預定義濾波器包括:

BLUR、CONTOUR、DETAIL、EDGE_ENHANCE、EDGE_ENHANCE_MORE、EMBOSS、FIND_EDGES、SMOOTH、SMOOTH_MORE、SHARPEN。其中BLUR就是均值濾波,CONTOUR找輪廓,FIND_EDGES邊緣檢測,使用該模塊時,需先導入,使用方法如下:

from PIL import ImageFilter

imgF = Image.open(“E:/photoshop/lena.jpg”)

outF = imgF.filter(ImageFilter.DETAIL)

conF = imgF.filter(ImageFilter.CONTOUR)

edgeF = imgF.filter(ImageFilter.FIND_EDGES)

imgF.show()

outF.show()

conF.show()

edgeF.show()

除此以外,ImageFilter模塊還包括一些擴展性強的濾波器:

class PIL.ImageFilter.GaussianBlur(radius=2)

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/252893.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-14 02:15
下一篇 2024-12-14 02:15

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29

發表回復

登錄後才能評論