當前位置:首頁 » 編程語言 » pillowpython27

pillowpython27

發布時間: 2023-07-19 16:49:37

① 如何在Windows下安裝配置python介面的caffe

整了一晚上加一上午。網上關於python的記錄較少,這里寫一下。
這里的環境是WIN10+cuda v7.5 +cudnn v4 + opencv + pycharm+VS2013
使用的是GPU,我的GPU是titan16G+內存32G
首先是caffe的文件以及第三方庫的編譯,這里提供一個已經編譯好的的連接,我就是從那裡下好然後編譯完畢的。
點擊打開鏈接 happynear的
然後就是如何編譯python介面。
1、首先先生成兩個python文件,在src/caffe/proto/extract_proto.bat 里生成caffe_pb2.py 這個之後有用。
2、然後打開已經給好的caffe/buildVS2013,打開裡面已經有的工程文件,正常的情況下應該是有7個工程,選中pycaffee單獨作為要編譯的項目。如圖所示:

把pycaffe作為單啟動。注意需要在release x64位下編譯。
如果沒有這個的話,就將這個文件夾里python文件夾中的項目加入即可。如果沒有python項目,就自己建一個,將python文件夾里的cpp文件加入就可以了。
3、選擇pycaffe的屬性,將配置屬性下的VC++目錄中的包含目錄和庫目錄填上你python所在的include和libs 再在C/C++的目錄下的附加包含目錄一項中添加
以我的python為例。D:/python27/Lib;D:/python/include/ 以及D:/Python27/Lib/site-packages/numpy/core/include 如果你安裝了CUDNN這里可以在預處理器那裡把USE_CUDNN加上,同時在LINKER的輸入目錄下的附加依賴庫中加入cudnn的lib文件。

3、開始編譯即可。這里要注意一定要和caffe、caffelib在一個項目里編譯,否則會報錯。
4、編譯成功後會在caffe/python/caffe下生成_caffe.pyd 是打不開的
5、配置python環境:需要幾個額外庫
Cython>=0.19.2
numpy>=1.7.1
scipy>=0.13.2
scikit-image>=0.9.3
matplotlib>=1.3.1
ipython>=3.0.0
h5py>=2.2.0
leveldb>=0.191
networkx>=1.8.1
nose>=1.3.0
pandas>=0.12.0
python-dateutil>=1.4,<2
protobuf>=2.5.0
python-gflags>=2.0
pyyaml>=3.10
Pillow>=2.3.0
six>=1.1.0
其中numpy要裝MKL版本的,不然scipy裝上了BLAS不能用
leveldb沒有windows版本的,不過我找到了可以使用的辦法。見這個博客:
點擊打開鏈接
如果有pip install 裝不上的,可以上這個網站找 wheel文件安裝就可以了
點擊打開鏈接
6、最後把目錄中python下的caffe文件夾復制到python27/Lib/site-packages就可以了。
測試的時候只需要在控制台下輸入import caffe 看能載入就知道成功了:)

② ❤️【Python從入門到精通】(二十七)更進一步的了解Pillow吧!

本文是接上一篇 ❤️【Python從入門到精通】(二十六)用Python的PIL庫(Pillow)處理圖像真的得心應手❤️ 進一步介紹Pillow庫的使用, 本文將重點介紹一些高級特性:比如如何利用Pillow畫圖形(圓形,正方形),介紹通過Pillow庫給圖片添加水印;同時對上一篇文章未介紹的常用知識點進行補充說明。希望對讀者朋友們有所幫助。

上一篇文章已經介紹了Image模塊,但是介紹的還不夠全面,例如如何從網頁中讀取圖片沒有介紹到,如何裁剪圖片都沒有介紹到。

讀取網頁中的圖片的基本實現方式是:首先利用requests庫讀取當前圖片鏈接的內容,接著將內容轉成二進制數據,在通過open方法將該二進制數據,最後通過save方法進行保存。

讀取結果是:

通過crop方法可以從圖片中裁剪出一個指定大小的區域。裁取的區域范圍是 (left, upper, right, lower) 比如從某個寬高都是400的圖片中裁剪一個是寬高都是100的正方形區域,只需要指定裁剪區域的坐標是: (0, 0, 100, 100)

有裁剪還有一個方法就是重新設置圖片大小的方法 resize,比如將前面400 400的圖片 修改成 300 200,只需要調用resize方法

通過 convert方法進行圖片模式的轉換

前面介紹的ImageDraw庫,只是介紹了利用它來向圖片寫入文本,其實ImageDraw模塊還有一個更有用的途徑,就是可以通過它來畫各種圖形。

首先創建一個600*600的畫布。然後再畫布中畫出一個正方形,畫直線的方法是 line方法。
ImageDraw.line(xy, fill=None, width=0, joint=None)

在xy的坐標之間畫一條直線
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
fill--> 直線的顏色
width--> 直線的寬度

畫一個邊框寬度為2px,顏色為藍色的,面積為400*400的正方形。

ImageDraw.arc(xy, start, end, fill=None, width=0)

在給定的區域范圍內,從開始角到結束角之間繪制一條圓弧
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度為單位,從3點鍾開始順時針增加
end--> 結束角度,以度為單位
fill--> 弧線的顏色
width-->弧線的寬度

這里就是畫了一個半圓,如果結束角度是360度的話則就會畫一個完整的圓。

畫圓通過ImageDraw.ellipse(xy, fill=None, outline=None, width=1) 方法,該方法可以畫出一個給定范圍的圓

xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 輪廓的顏色
fill ---> 填充顏色
width--> 輪廓的寬度

ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1) 方法用來畫半圓,跟arc()方法不同的是它會用直線將起始點和結束點連接起來

xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
outline--> 輪廓的顏色
fill ---> 填充顏色
width--> 輪廓的寬度

ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1)
類似於arc()方法,不過他會在端點和圓點之間畫直線
xy--> 定義邊界框的兩個點,傳入的格式是[ (x0, y0), (x1, y1)] 或者 [x0, y0, x1, y1] ,其中 x1>=x0,y1>=y0
start --> 起始角度,以度為單位,從3點鍾開始順時針增加
end--> 結束角度,以度為單位
fill--> 弧線的顏色
width-->弧線的寬度

ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
outline--> 輪廓的顏色
fill--> 填充的顏色
width--> 輪廓線的寬度

ImageDraw.rounded_rectangle(xy, radius=0, fill=None, outline=None, width=1) 該方法可以畫一個圓角矩形
xy--> 在兩個坐標點之間畫一條直線,坐標點的傳入方式是[(x, y), (x, y), ...]或者[x, y, x, y, ...]
radius--> 角的半徑
outline--> 輪廓的顏色
fill--> 填充的顏色
width--> 輪廓線的寬度

這里有個問題,就是畫好的圖形如何從Image中扣出來呢?

ImageEnhance模塊主要是用於設置圖片的顏色對比度亮度銳度等啥的,增強圖像。

原始圖像

ImageFilter模塊主要用於對圖像進行過濾,增強邊緣,模糊處理,該模塊的使用方式是 im.filter(ImageFilter) 。
其中ImageFilter按照需求傳入指定的過濾值。

下面一個個試下效果

4.邊緣增強

ImageGrab模塊主要用於對屏幕進行截圖,通過grab方法進行截取,如果不傳入任何參數則表示全屏幕截圖,否則是截取指定區域的圖像。其中box格式是:(x1,x2,y1,y2)

利用Pillow庫可以輕易的對圖像增加水印
首先,用PIL的Image函數讀取圖片
接著,新建一張圖(尺寸和原圖一樣)
然後,在新建的圖象上用PIL的ImageDraw把字給畫上去,字的顏色從原圖處獲取。

原圖

添加文字後的效果圖

本文詳細介紹了Pillow庫的使用,希望對讀者朋友們有所幫助。

Pillow官方文檔

需要獲取源碼的小夥伴可以關注下方的公眾號,回復【python】

③ python 怎麼安裝pillow

1. 安裝pip

[plain] view plain
sudo easy_install pip

pip 安裝成功就可以直接安裝pil或者pillow

2. 通過命令pip install pil

[plain] view plain
pip install Pil
Downloading/unpacking Pil
Could not find any downloads that satisfy the requirement Pil
Some externally hosted files were ignored (use --allow-external Pil to allow).
Cleaning up...
No distributions at all found for Pil
Storing debug log for failure in /Users/macbook/Library/Logs/pip.log

3. 所以就安裝pillow

[plain] view plain
pip install --use-wheel Pillow
Downloading/unpacking Pillow
Downloading Pillow-2.4.0.zip (6.5MB): 5.0MB downloaded
Cleaning up...

弄了會別的回來發現還沒有下載完,這叫一個慢呀,於是放棄
4. 通過Git下載源碼地址https://github.com/python-imaging/Pillow

[plain] view plain
git clone https://github.com/python-imaging/Pillow.git

然後開始編譯安裝
4.1

[plain] view plain
python setup.py build_ext -i

編譯完之後會提示運行測試例子,並且發現JPEG support not available

[plain] view plain
--------------------------------------------------------------------
version Pillow 2.4.0
platform darwin 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
--------------------------------------------------------------------
--- TKINTER support available
*** JPEG support not available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library, and set the corresponding ROOT variable in the
setup.py script.

To check the build, run the selftest.py script.

4.2 因為JPEG support not available,運行python selftest.py報告錯誤

[plain] view plain
1 tests of 57 failed.

於是只好卸載pillow

可以通過pip命令來卸載

[plain] view plain
pip uninstall pillow
sudo pip uninstall pillow
Password:
Uninstalling Pillow:
/Library/Python/2.7/site-packages/Pillow-2.4.0-py2.7-macosx-10.9-intel.egg
/usr/local/bin/pilconvert.py
/usr/local/bin/pildriver.py
/usr/local/bin/pilfile.py
/usr/local/bin/pilfont.py
/usr/local/bin/pilprint.py
Proceed (y/n)? y
Successfully uninstalled Pillow

成功之後需要安裝libjpeg的支持

[plain] view plain
brew install libjpeg

安裝成功之後重新編譯pillow

[plain] view plain
--------------------------------------------------------------------
version Pillow 2.4.0
platform darwin 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)]
--------------------------------------------------------------------
--- TKINTER support available
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------

[plain] view plain
python selftest.py

[plain] view plain
--------------------------------------------------------------------
Pillow 2.4.0 TEST SUMMARY
--------------------------------------------------------------------
Python moles loaded from /Users/macbook/yyang/app-devel-source/python/Pillow/PIL
Binary moles loaded from /Users/macbook/yyang/app-devel-source/python/Pillow/PIL
--------------------------------------------------------------------
--- PIL CORE support ok
--- TKINTER support ok
--- JPEG support ok
*** JPEG 2000 support not installed
--- ZLIB (PNG/ZIP) support ok
*** LIBTIFF support not installed
--- FREETYPE2 support ok
*** LITTLECMS2 support not installed
*** WEBP support not installed
--------------------------------------------------------------------
Running selftest:
--- 57 tests passed.

最後執行安裝

[plain] view plain
sudo python setup.py install

④ 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)

⑤ 怎麼樣在Python編程中使用Pillow來處理圖像

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

$ wget http://pypi.python.org/packages/source/p/pip/pip-0.7.2.tar.gz$ 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對象,可以通過對象屬性檢查文件內容

>>> from __future__ import print_function>>> print(im.format, im.size, im.mode)

PPM (512, 512) RGB

format屬性定義了圖像的格式,如果圖像不是從文件打開的,那麼該屬性值為None;size屬性是一個tuple,表示圖像的寬和高(單位為像素);mode屬性為表示圖像的模式,常用的模式為:L為灰度圖,RGB為真彩色,CMYK為pre-press圖像。
如果文件不能打開,則拋出IOError異常。
當有一個Image對象時,可以用Image類的各個方法進行處理和操作圖像,例如顯示圖片:

>>> im.show()

ps:標准版本的show()方法不是很有效率,因為它先將圖像保存為一個臨時文件,然後使用xv進行顯示。如果沒有安裝xv,該函數甚至不能工作。但是該方法非常便於debug和test。(windows中應該調用默認圖片查看器打開)
讀寫圖片
Pillow庫支持相當多的圖片格式。直接使用Image模塊中的open()函數讀取圖片,而不必先處理圖片的格式,Pillow庫自動根據文件決定格式。
Image模塊中的save()函數可以保存圖片,除非你指定文件格式,那麼文件名中的擴展名用來指定文件格式。
圖片轉成jpg格式

from __future__ import print_functionimport os, sysfrom PIL import Imagefor infile in sys.argv[1:]: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except IOError: print("cannot convert", infile)

save函數的第二個參數可以用來指定圖片格式,如果文件名中沒有給出一個標準的圖像格式,那麼第二個參數是必須的。
創建縮略圖

from __future__ import print_functionimport os, sysfrom PIL import Imagesize = (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) im.save(outfile, "JPEG") except IOError: print("cannot create thumbnail for", infile)

必須指出的是除非必須,Pillow不會解碼或raster數據。當你打開一個文件,Pillow通過文件頭確定文件格式,大小,mode等數據,餘下數據直到需要時才處理。
這意味著打開文件非常快,與文件大小和壓縮格式無關。下面的程序用來快速確定圖片屬性:
確定圖片屬性

from __future__ import print_functionimport sysfrom PIL import Imagefor infile in sys.argv[1:]: try: with Image.open(infile) as im: print(infile, im.format, "%dx%d" % im.size, im.mode) except IOError: pass

裁剪、粘貼、與合並圖片
Image類包含還多操作圖片區域的方法。如crop()方法可以從圖片中提取一個子矩形
從圖片中復制子圖像

box = im.() #直接復制圖像box = (100, 100, 400, 400)region = im.crop(box)

區域由4-tuple決定,該tuple中信息為(left, upper, right, lower)。 Pillow左邊系統的原點(0,0)為圖片的左上角。坐標中的數字單位為像素點,所以上例中截取的圖片大小為300*300像素^2。
處理子圖,粘貼回原圖

region = region.transpose(Image.ROTATE_180)im.paste(region, box)

將子圖paste回原圖時,子圖的region必須和給定box的region吻合。該region不能超過原圖。而原圖和region的mode不需要匹配,Pillow會自動處理。
另一個例子

Rolling an imagedef roll(image, delta): "Roll an image sideways" image = image.() #復制圖像 xsize, ysize = image.size delta = delta % xsize if delta == 0: return image part1 = image.crop((0, 0, delta, ysize)) part2 = image.crop((delta, 0, xsize, ysize)) image.paste(part2, (0, 0, xsize-delta, ysize)) image.paste(part1, (xsize-delta, 0, xsize, ysize)) return image

分離和合並通道

r, g, b = im.split()im = Image.merge("RGB", (b, g, r))

對於單通道圖片,split()返回圖像本身。為了處理單通道圖片,必須先將圖片轉成RGB。
幾何變換
Image類有resize()、rotate()和transpose()、transform()方法進行幾何變換。
簡單幾何變換

out = im.resize((128, 128))out = im.rotate(45) # 順時針角度表示

置換圖像

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)

transpose()和象的rotate()沒有性能差別。
更通用的圖像變換方法可以使用transform()
模式轉換
convert()方法
模式轉換

im = Image.open('lena.ppm').convert('L')

圖像增強
Filter ImageFilter模塊包含很多預定義的增強filters,通過filter()方法使用
應用filters

from PIL import ImageFilterout = im.filter(ImageFilter.DETAIL)

像素點處理
point()方法通過一個函數或者查詢表對圖像中的像素點進行處理(例如對比度操作)。
像素點變換

# multiply each pixel by 1.2out = im.point(lambda i: i * 1.2)

上述方法可以利用簡單的表達式進行圖像處理,通過組合point()和paste()還能選擇性地處理圖片的某一區域。
處理單獨通道

# split the image into indivial bandssource = im.split()R, G, B = 0, 1, 2# select regions where red is less than 100mask = source[R].point(lambda i: i < 100 and 255)# process the green bandout = source[G].point(lambda i: i * 0.7)# paste the processed band back, but only where red was < 100source[G].paste(out, None, mask)# build a new multiband imageim = Image.merge(im.mode, source)

注意到創建mask的語句:

mask = source[R].point(lambda i: i < 100 and 255)

該句可以用下句表示

imout = im.point(lambda i: expression and 255)

如果expression為假則返回expression的值為0(因為and語句已經可以得出結果了),否則返回255。(mask參數用法:當為0時,保留當前值,255為使用paste進來的值,中間則用於transparency效果)
高級圖片增強
對其他高級圖片增強,應該使用ImageEnhance模塊 。一旦有一個Image對象,應用ImageEnhance對象就能快速地進行設置。 可以使用以下方法調整對比度、亮度、色平衡和銳利度。
圖像增強

from PIL import ImageEnhanceenh = ImageEnhance.Contrast(im)enh.enhance(1.3).show("30% more contrast")

動態圖
Pillow支持一些動態圖片的格式如FLI/FLC,GIF和其他一些處於實驗階段的格式。TIFF文件同樣可以包含數幀圖像。
當讀取動態圖時,PIL自動讀取動態圖的第一幀,可以使用seek和tell方法讀取不同鄭

from PIL import Imageim = Image.open("animation.gif")im.seek(1) # skip to the second frametry: while 1: im.seek(im.tell()+1) # do something to imexcept EOFError: pass # end of sequence

當讀取到最後一幀時,Pillow拋出EOFError異常。
當前版本只允許seek到下一鄭為了倒回之前,必須重新打開文件。
或者可以使用下述迭代器類
動態圖迭代器類

class ImageSequence: def __init__(self, im): self.im = im def __getitem__(self, ix): try: if ix: self.im.seek(ix) return self.im except EOFError: raise IndexError # end of sequencefor frame in ImageSequence(im): # ...do something to frame...Postscript Printing

Pillow允許通過Postscript Printer在圖片上添加images、text、graphics。

Drawing Postscriptfrom PIL import Imagefrom PIL import PSDrawim = Image.open("lena.ppm")title = "lena"box = (1*72, 2*72, 7*72, 10*72) # in pointsps = PSDraw.PSDraw() # default is sys.stdoutps.begin_document(title)# draw the image (75 dpi)ps.image(box, im, 75)ps.rectangle(box)# draw centered titleps.setfont("HelveticaNarrow-Bold", 36)w, h, b = ps.textsize(title)ps.text((4*72-w/2, 1*72-h), title)ps.end_document()

更多讀取圖片方法
之前說到Image模塊的open()函數已經足夠日常使用。該函數的參數也可以是一個文件對象。
從string中讀取

import StringIOim = Image.open(StringIO.StringIO(buffer))

從tar文件中讀取

from PIL import TarIOfp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm")im = Image.open(fp)

草稿模式
draft()方法允許在不讀取文件內容的情況下盡可能(可能不會完全等於給定的參數)地將圖片轉成給定模式和大小,這在生成縮略圖的時候非常有效(速度要求比質量高的場合)。
draft模式

from __future__ import print_functionim = Image.open(file)print("original =", im.mode, im.size)im.draft("L", (100, 100))print("draft =", im.mode, im.size)

⑥ 求助.python使用matplotlib出錯

為了避免各種問題,請使用最新的2.7.13安裝文件

1、先設置好環境變數
在path變數中設置好以下路徑:
C:\Python27\Scripts
C:\Python27

2、大部分報錯問題都是因為庫與庫之間存在依賴關系
matplotlib依賴dateutil和pyparsing,如果Python裡面沒有安裝dateutil和pyparsing,那麼後續使用matplotlib的時候很可能會遇到依賴問題。所以需要安裝dateutil。
進入下面網址,找到matplotlib,可以看到所需要的各種包的描述。
http://www.lfd.uci.e/~gohlke/pythonlibs/#python-dateutil
http://www.lfd.uci.e/~gohlke/pythonlibs/#pyparsing
Matplotlib, a 2D plotting library.
Requires numpy, dateutil, pytz, pyparsing, cycler, setuptools, and optionally pillow, pycairo, tornado, wxpython, pyside, pyqt4, ghostscript, miktex, ffmpeg, mencoder, avconv, or imagemagick.
所以上面這些包肯定是都需要有的,如果沒有遇到問題,可能是因為代碼中沒有引用這些包而已;或者已經安裝了。

2.1、使用easy_install.exe來安裝所需要依賴的包
現在dateutil使用easy_install命令來安裝,(easy_install會自己從網路上需要最新的合適的包來安裝,所以不需要你自己去尋找和下載)
只需要輸入 easy_install python-dateutil 命令就可以。
如果找不到easy_install 命令,要麼是你的環境變數沒有設置好,請參考1。要麼是你的python包太老,沒有預裝easy_install,那就參考3,先安裝easy_install

3、安裝easy_install.exe, 手動下載安裝包到本地安裝
https://pypi.python.org/pypi/setuptools
找到ez_setup.py文件,下載到本地E:\iso\VisualStudio2010\ (我是下載到這里,你自己就隨意吧)
在cmd窗口下面,輸入:
Python E:\iso\VisualStudio2010\ez_setup.py
成功後,C:\Python27\Scripts\目錄下會多了easy_install.exe

4、使用easy_install.exe安裝dateutil和pyparsing。。
反正根據提示,缺啥就用easy_install安裝啥,這個easy_install是按照關鍵字來搜索安裝包的。
easy_install python-dateutil
easy_install pyparsing
easy_install pip

4.1、如果不用easy_install.exe安裝,也可以使用pip通過本地安裝或者網路安裝
使用pip安裝 的命令是: pip install numpy
如果要手動把包下載到本地再安裝,請參考6

5、把路徑如:C:\Python27\Lib\site-packages\scipy\lib中的six.py six.pyc six.pyo三個文件拷貝到C:\Python27\Lib\site-packages目錄下。

6、使用下載到本地的whl來安裝各種包
在下面頁面下載所對應的32bit或者64bit,區分python2.7還是python3的
http://www.lfd.uci.e/~gohlke/pythonlibs/#numpy
numpy-1.11.1+mkl-cp27-cp27m-win_amd64.whl
pandas-0.18.1-cp27-cp27m-win_amd64.whl
scipy-0.17.1-cp27-cp27m-win_amd64.whl
matplotlib-1.5.2-cp27-cp27m-win_amd64.whl
把上面這些需要的whl放到python的scripts目錄下,然後用下面的命令來安裝即可
c:\Python27-x64\Scripts>
pip install pandas-0.18.1-cp27-cp27m-win_amd64.whl

⑦ python如何安裝pil庫

PIL:Python Imaging Library,已經是Python平台事實上的圖像處理標准庫了。
由於PIL僅支持到Python 2.7,加上年久失修,於是一群志願者在PIL的基礎上創建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了許多新特性,因此,我們可以直接安裝使用Pillow。
安裝Python時已經把pip3也備好了,可以直接使用pip3安裝PIL
命令行:pip3 install pillow
注意:
1.PIL安裝包名字的pillow
2.使用pip3命令時,是要在pip3.exe所在路徑下才能執行。一般pip3.exe是在python安裝目錄下的Script文件夾中。
更多Python相關技術文章,請訪問Python教程欄目進行學習!以上就是小編分享的關於python如何安裝pil庫的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!

⑧ 怎麼安裝python模塊,如何安裝python模塊,常用安裝方式

.
直接
下載的模塊文件中已經有了模塊的文件,有些模塊只有一個文件,比如較早版本的BeautifulSoup,有些是一個文件夾,比如新版本BeautifulSoup就是一個叫做bs4的文件夾。

把這些文件直接到你的python路徑下的/Lib/site-packages文件夾中,比如C:/Python27/Lib/site-packages。之後就可以在程序里直接引用了:
import BeautifulSoup
或者
from bs4 import BeautifulSoup

這是根據你放置的文件位置不同而決定的。

網上有人說直接放在Lib文件夾中就可以了。的確這樣也行,但Lib文件夾中都是自帶的模塊,看一下就會發現我們用過的random、re等模塊的代碼文件。而外部模塊一般放在site-packages文件夾中。

2.
setup.py
很多模塊里都附帶了setup.py文件,有同學直接雙擊了,然後發現沒有用。

它的使用方法是從命令行去到setup.py所在的路徑下,運行
python setup.py install

仔細看一下安裝時輸出的信息可以發現,在線學習這個命令做的事情其實也就是幫你把模塊的代碼到site-packages文件夾。

3.
setuptools
使用setuptools可以直接根據模塊名稱來自動下載安裝,不需要自己再去尋找模塊的安裝文件。不過在使用之前,你得先安裝setuptools自身。

windows平台的32位python,可以直接下載setuptools的exe文件安裝。(去搜索setuptools windows可以找到,我也上傳了一份在論壇本帖後面)

Linux用戶可以從包管理器中安裝,比如ubuntu:
apt-get install python-setuptools

windows平台64位python得用ez_setup.py進行安裝(文件我也上傳了)。這種方式也適用於所有平台。

在ez_setup.py所在文件夾下運行:
python ez_setup.py

setuptools會被安裝在python路徑\Scripts下。之後,你可以把這個路徑添加到環境變數path中,也可以直接從命令行進入到Scripts文件夾下,執行easy_install,看看是否安裝成功了。

之後,你就可以直接用它來安裝你想要的模塊,比如PIL:
easy_install PIL

視頻教程程序就會幫你自動下載安裝到site-packages里。

最後,介紹幾個不錯的模塊,供大家參考使用。
PIL - 圖形處理
PyXML - 解析和處理XML文件
MySQLdb - 連接MySQL資料庫
Tkinter - 圖形界面介面,python自帶
smtplib - 發送電子郵件
ftplib - ftp編程
PyMedia - 多媒體操作
PyOpenGL - OpenGL介面
BeautifulSoup - HTML/XML的解析器

熱點內容
外網訪問黑群暉 發布:2025-02-08 05:45:59 瀏覽:557
中央存儲伺服器公司地址 發布:2025-02-08 05:38:48 瀏覽:821
伺服器如何查詢表空間的文件路徑 發布:2025-02-08 05:38:00 瀏覽:162
宏基4741g哪個配置好 發布:2025-02-08 05:37:56 瀏覽:809
混合料運輸車的配置是如何計算的 發布:2025-02-08 05:31:35 瀏覽:293
android紅包插件 發布:2025-02-08 05:31:34 瀏覽:365
ea伺服器怎麼連接 發布:2025-02-08 05:16:45 瀏覽:463
更加密更改 發布:2025-02-08 05:15:20 瀏覽:786
倉儲資源配置都需要開展哪些任務 發布:2025-02-08 05:13:51 瀏覽:676
探針資料庫 發布:2025-02-08 05:13:35 瀏覽:80