A. 10 個 python 圖像編輯工具
以下提到的這些 Python 工具在編輯圖像、操作圖像底層數據方面都提供了簡單直接的方法。
-- Parul Pandey
當今的世界充滿了數據,而圖像數據就是其中很重要的一部分。但只有經過處理和分析,提高圖像的質量,從中提取出有效地信息,才能利用到這些圖像數據。
常見的圖像處理操作包括顯示圖像,基本的圖像操作,如裁剪、翻轉、旋轉;圖像的分割、分類、特徵提取;圖像恢復;以及圖像識別等等。Python 作為一種日益風靡的科學編程語言,是這些圖像處理操作的最佳選擇。同時,在 Python 生態當中也有很多可以免費使用的優秀的圖像處理工具。
下文將介紹 10 個可以用於圖像處理任務的 Python 庫,它們在編輯圖像、查看圖像底層數據方面都提供了簡單直接的方法。
scikit-image 是一個結合 NumPy 數組使用的開源 Python 工具,它實現了可用於研究、教育、工業應用的演算法和應用程序。即使是對於剛剛接觸 Python 生態圈的新手來說,它也是一個在使用上足夠簡單的庫。同時它的代碼質量也很高,因為它是由一個活躍的志願者社區開發的,並且通過了 同行評審(peer review)。
scikit-image 的 文檔 非常完善,其中包含了豐富的用例。
可以通過導入 skimage 使用,大部分的功能都可以在它的子模塊中找到。
圖像濾波(image filtering):
使用 match_template() 方法實現 模板匹配(template matching):
在 展示頁面 可以看到更多相關的例子。
NumPy 提供了對數組的支持,是 Python 編程的一個核心庫。圖像的本質其實也是一個包含像素數據點的標准 NumPy 數組,因此可以通過一些基本的 NumPy 操作(例如切片、 掩膜(mask)、 花式索引(fancy indexing)等),就可以從像素級別對圖像進行編輯。通過 NumPy 數組存儲的圖像也可以被 skimage 載入並使用 matplotlib 顯示。
在 NumPy 的 官方文檔 中提供了完整的代碼文檔和資源列表。
使用 NumPy 對圖像進行 掩膜(mask)操作:
像 NumPy 一樣, SciPy 是 Python 的一個核心科學計算模塊,也可以用於圖像的基本操作和處理。尤其是 SciPy v1.1.0 中的 scipy.ndimage 子模塊,它提供了在 n 維 NumPy 數組上的運行的函數。SciPy 目前還提供了 線性和非線性濾波(linear and non-linear filtering)、 二值形態學(binary morphology)、 B 樣條插值(B-spline interpolation)、 對象測量(object measurements)等方面的函數。
在 官方文檔 中可以查閱到 scipy.ndimage 的完整函數列表。
使用 SciPy 的 高斯濾波 對圖像進行模糊處理:
PIL (Python Imaging Library) 是一個免費 Python 編程庫,它提供了對多種格式圖像文件的打開、編輯、保存的支持。但在 2009 年之後 PIL 就停止發布新版本了。幸運的是,還有一個 PIL 的積極開發的分支 Pillow ,它的安裝過程比 PIL 更加簡單,支持大部分主流的操作系統,並且還支持 Python 3。Pillow 包含了圖像的基礎處理功能,包括像素點操作、使用內置卷積內核進行濾波、顏色空間轉換等等。
Pillow 的 官方文檔 提供了 Pillow 的安裝說明自己代碼庫中每一個模塊的示例。
使用 Pillow 中的 ImageFilter 模塊實現圖像增強:
OpenCV(Open Source Computer Vision 庫)是計算機視覺領域最廣泛使用的庫之一, OpenCV-Python 則是 OpenCV 的 Python API。OpenCV-Python 的運行速度很快,這歸功於它使用 C/C++ 編寫的後台代碼,同時由於它使用了 Python 進行封裝,因此調用和部署的難度也不大。這些優點讓 OpenCV-Python 成為了計算密集型計算機視覺應用程序的一個不錯的選擇。
入門之前最好先閱讀 OpenCV2-Python-Guide 這份文檔。
使用 OpenCV-Python 中的 金字塔融合(Pyramid Blending)將蘋果和橘子融合到一起:
SimpleCV 是一個開源的計算機視覺框架。它支持包括 OpenCV 在內的一些高性能計算機視覺庫,同時不需要去了解 位深度(bit depth)、文件格式、 色彩空間(color space)之類的概念,因此 SimpleCV 的學習曲線要比 OpenCV 平緩得多,正如它的口號所說,「將計算機視覺變得更簡單」。SimpleCV 的優點還有:
官方文檔 簡單易懂,同時也附有大量的學慣用例。
文檔 包含了安裝介紹、示例以及一些 Mahotas 的入門教程。
Mahotas 力求使用少量的代碼來實現功能。例如這個 Finding Wally 游戲 :
ITK (Insight Segmentation and Registration Toolkit)是一個為開發者提供普適性圖像分析功能的開源、跨平台工具套件, SimpleITK 則是基於 ITK 構建出來的一個簡化層,旨在促進 ITK 在快速原型設計、教育、解釋語言中的應用。SimpleITK 作為一個圖像分析工具包,它也帶有 大量的組件 ,可以支持常規的濾波、圖像分割、 圖像配准(registration)功能。盡管 SimpleITK 使用 C++ 編寫,但它也支持包括 Python 在內的大部分編程語言。
有很多 Jupyter Notebooks 用例可以展示 SimpleITK 在教育和科研領域中的應用,通過這些用例可以看到如何使用 Python 和 R 利用 SimpleITK 來實現互動式圖像分析。
使用 Python + SimpleITK 實現的 CT/MR 圖像配准過程:
pgmagick 是使用 Python 封裝的 GraphicsMagick 庫。 GraphicsMagick 通常被認為是圖像處理界的瑞士軍刀,因為它強大而又高效的工具包支持對多達 88 種主流格式圖像文件的讀寫操作,包括 DPX、GIF、JPEG、JPEG-2000、PNG、PDF、PNM、TIFF 等等。
pgmagick 的 GitHub 倉庫 中有相關的安裝說明、依賴列表,以及詳細的 使用指引 。
圖像縮放:
邊緣提取:
Cairo 是一個用於繪制矢量圖的二維圖形庫,而 Pycairo 是用於 Cairo 的一組 Python 綁定。矢量圖的優點在於做大小縮放的過程中不會丟失圖像的清晰度。使用 Pycairo 可以在 Python 中調用 Cairo 的相關命令。
Pycairo 的 GitHub 倉庫 提供了關於安裝和使用的詳細說明,以及一份簡要介紹 Pycairo 的 入門指南 。
使用 Pycairo 繪制線段、基本圖形、 徑向漸變(radial gradients):
以上就是 Python 中的一些有用的圖像處理庫,無論你有沒有聽說過、有沒有使用過,都值得試用一下並了解它們。
via: https://opensource.com/article/19/3/python-image-manipulation-tools
作者: Parul Pandey 選題: lujun9972 譯者: HankChow 校對: wxy
B. python的pillow庫怎麼使用
Pillow是Python里的圖像處理庫(PIL:Python Image Library),提供了了廣泛的文件格式支持,強大的圖像處理能力,主要包括圖像儲存、圖像顯示、格式轉換以及基本的圖像處理操作等。
1)使用 Image 類
PIL最重要的類是 Image class, 你可以通過多種方法創建這個類的實例;你可以從文件載入圖像,或者處理其他圖像, 或者從 scratch 創建。
要從文件載入圖像,可以使用open( )函數,在Image模塊中:
[python]view plain
>>>fromPILimportImage
>>>im=Image.open("E:/photoshop/1.jpg")
載入成功後,將返回一個Image對象,可以通過使用示例屬性查看文件內容:
[python]view plain
>>>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
im.show()
2)讀寫圖像
PIL 模塊支持大量圖片格式。使用在 Image 模塊的 open() 函數從磁碟讀取文件。你不需要知道文件格式就能打開它,這個庫能夠根據文件內容自動確定文件格式。要保存文件,使用 Image 類的 save() 方法。保存文件的時候文件名變得重要了。除非你指定格式,否則這個庫將會以文件名的擴展名作為格式保存。
載入文件,並轉化為png格式:
[python]view plain
"PythonImageLibraryTest"
fromPILimportImage
importos
importsys
forinfileinsys.argv[1:]:
f,e=os.path.splitext(infile)
outfile=f+".png"
ifinfile!=outfile:
try:
Image.open(infile).save(outfile)
exceptIOError:
print("Cannotconvert",infile)
save() 方法的第二個參數可以指定文件格式。
3)創建縮略圖
縮略圖是網路開發或圖像軟體預覽常用的一種基本技術,使用Python的Pillow圖像庫可以很方便的建立縮略圖,如下:
[python]view plain
#createthumbnail
size=(128,128)
forinfileinglob.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
#crop,pasteandmerge
im=Image.open("E:/photoshop/lena.jpg")
box=(100,100,300,300)
region=im.crop(box)
矩形選區有一個4元元組定義,分別表示左、上、右、下的坐標。這個庫以左上角為坐標原點,單位是px,所以上訴代碼復制了一個 200x200 pixels 的矩形選區。這個選區現在可以被處理並且粘貼到原圖。
[python]view plain
region=region.transpose(Image.ROTATE_180)
im.paste(region,box)
當你粘貼矩形選區的時候必須保證尺寸一致。此外,矩形選區不能在圖像外。然而你不必保證矩形選區和原圖的顏色模式一致,因為矩形選區會被自動轉換顏色。
5)分離和合並顏色通道
對於多通道圖像,有時候在處理時希望能夠分別對每個通道處理,處理完成後重新合成多通道,在Pillow中,很簡單,如下:
[python]view plain
r,g,b=im.split()
im=Image.merge("RGB",(r,g,b))
對於split( )函數,如果是單通道的,則返回其本身,否則,返回各個通道。
6)幾何變換
對圖像進行幾何變換是一種基本處理,在Pillow中包括resize( )和rotate( ),如用法如下:
[python]view plain
out=im.resize((128,128))
out=im.rotate(45)#degreeconter-clockwise
其中,resize( )函數的參數是一個新圖像大小的元祖,而rotate( )則需要輸入順時針的旋轉角度。在Pillow中,對於一些常見的旋轉作了專門的定義:
[python]view plain
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
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
fromPILimportImageFilter
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模塊還包括一些擴展性強的濾波器:
classPIL.ImageFilter.GaussianBlur(radius=2)
Gaussian blur filter.
參數:
radius– Blur radius.classPIL.ImageFilter.UnsharpMask(radius=2,percent=150,threshold=3)
Unsharp mask filter.
See Wikipedia』s entry ondigital unsharp maskingfor an explanation of the parameters.
classPIL.ImageFilter.Kernel(size,kernel,scale=None,offset=0)
Create a convolution kernel. The current version only supports 3x3 and 5x5 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.
classPIL.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/2for a median filter,size*size-1for a max filter, etc.
classPIL.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.classPIL.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.classPIL.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.classPIL.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
fromPILimportImageEnhance
imgE=Image.open("E:/photoshop/lena.jpg")
imgEH=ImageEnhance.Contrast(imgE)
imgEH.enhance(1.3).show("30%morecontrast")
圖像增強:
classPIL.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.
classPIL.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.
classPIL.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.
classPIL.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)
C. 如何安裝python的第三方模塊
在Python中,安裝第三方模塊,是通過setuptools這個工具完成的。Python有兩個封裝了setuptools的包管理工具:easy_install和pip。目前官方推薦使用pip。
如果你正在使用Mac或Linux,安裝pip本身這個步驟就可以跳過了。
如果你正在使用Windows,請參考安裝Python一節的內容,確保安裝時勾選了pip和Add python.exe to Path。
在命令提示符窗口下嘗試運行pip,如果Windows提示未找到命令,可以重新運行安裝程序添加pip。
現在,讓我們來安裝一個第三方庫——Python Imaging Library,這是Python下非常強大的處理圖像的工具庫。一般來說,第三方庫都會在Python官方的pypi.python.org網站注冊,要安裝一個第三方庫,必須先知道該庫的名稱,可以在官網或者pypi上搜索,比如Python Imaging Library的名稱叫PIL,因此,安裝Python Imaging Library的命令就是:
pip install PIL
耐心等待下載並安裝後,就可以使用PIL了。
有了PIL,處理圖片易如反掌。隨便找個圖片生成縮略圖:
>>> import Image
>>> im = Image.open('test.png')
>>> print im.format, im.size, im.mode
PNG (400, 300) RGB
>>> im.thumbnail((200, 100))
>>> im.save('thumb.jpg', 'JPEG')
其他常用的第三方庫還有MySQL的驅動:MySQL-python,用於科學計算的NumPy庫:numpy,用於生成文本的模板工具Jinja2,等等。
模塊搜索路徑
當我們試圖載入一個模塊時,Python會在指定的路徑下搜索對應的.py文件,如果找不到,就會報錯:
>>> import mymole
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
ImportError: No mole named mymole
默認情況下,Python解釋器會搜索當前目錄、所有已安裝的內置模塊和第三方模塊,搜索路徑存放在sys模塊的path變數中:
>>> import sys
>>> sys.path
['', '/Library/Python/2.7/site-packages/pycrypto-2.6.1-py2.7-macosx-10.9-intel.egg', '/Library/Python/2.7/site-packages/PIL-1.1.7-py2.7-macosx-10.9-intel.egg', ...]
如果我們要添加自己的搜索目錄,有兩種方法:
一是直接修改sys.path,添加要搜索的目錄:
>>> import sys
>>> sys.path.append('/Users/michael/my_py_scripts')
這種方法是在運行時修改,運行結束後失效。
第二種方法是設置環境變數PYTHONPATH,該環境變數的內容會被自動添加到模塊搜索路徑中。設置方式與設置Path環境變數類似。注意只需要添加你自己的搜索路徑,Python自己本身的搜索路徑不受影響。