1. 程式人生 > >python圖片處理(入門一)

python圖片處理(入門一)

先上一個程式碼例子

from PIL import Image
import os,sys

for infile in sys.argv[1:]:#
    print(infile)
    outfile=os.path.splitext(infile)[0]#os.path.splitext(text)是那infile字串裡面的按照名字和拓展名分開的方法
    print(outfile)#出現的outfile就是和拓展名分開的
    outfile+=".png"#把沒有拓展名的添上我們希望的拓展名,python會自動轉換格式
    print(outfile)
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)#使用Image先開啟這個圖片,然後用save方法儲存
        except IOError:
            print("Error")

這裡面我都主要的都註釋了,主要看看註釋

看看執行結果:

***MacBook-Pro:pyui zhangyongde$ python pic.py /Users/zhangyongde/Desktop/test.jpg
/Users/***/Desktop/test.jpg
/Users/***/Desktop/test
/Users/***/Desktop/test.png

但是如果來源不是標準的拓展的格式的時候,試試下面的方法:

import os, sys
  import Image
#create jpeg thumbnails
  for infile in sys.argv[1:]:
      outfile = os.path.splitext(infile)[0] + ".thumbnail"
      if infile != outfile:
          try:
              im = Image.open(infile)
              im.thumbnail((128, 128))
              im.save(outfile, "JPEG")#呼叫Save方法
          except IOError:
              print "cannot create thumbnail for", infile

但是這個庫不是負責解碼的。當你開啟一個圖片的時候,那麼這個時候就會讀取他的檔案頭並且從檔案頭來決定讀入的格式

看看下面這個介紹:

It is important to note is that the library doesn't decode or load the raster data unless itreally has to. When you open a file, the file header is read to determine the file formatand extract things like mode, size, and other properties required to decode the file, butthe rest of the file is not processed until later. 


使用crop方法可以擷取圖片的一部分出來:

for infile in sys.argv[1:]:
    try:
        im=Image.open(infile)
        print(infile,im.format,"%dx%d"%im.size,im.mode)
    except IOError:
        print("Error")

box=(100,100,400,400)
region=im.crop(box)
print(region)
region.show()

看看效果


這個是原圖

我們來看看執行後show的結果


這個就是給定一個元組,然後作為引數傳給crop方法來擷取元組內給定的部分,得到的圖是300X300的影象

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

這個就是把得到的結果反轉180度

同時把這個效果貼上到原影象上面去

得到下面這樣的結果: