Python-PIL-拼接圖片

最近學習了PIL,主要學習的是如何把當前目錄下的圖片拼接在一起,以下僅僅是拼接圖片的學習筆記:

一、學習的網(wǎng)址:
??PIL - 廖雪峰的官方網(wǎng)站
??圖像簡單處理(PIL or Pillow)
??Python拼接圖片
??PIL官方文檔:http://effbot.org/imagingbook/

二、下載:
??(1)windows不能通過pip直接安裝(我目前是還沒找到安裝的方法,如有人找到了請告知一下我,此處省略一萬個感謝)
??(2)根據(jù)需要自己去官網(wǎng)選擇適合自己電腦的安裝包,PIL官方網(wǎng)站:http://pythonware.com/products/pil/
安裝的需要了解更多詳情,看官方文檔 or 問度娘都是可以的 這里就不搬磚了

三、拼接圖片:
??(1)橫向拼接:

import os
from PIL import Image

UNIT_SIZE = 768#高
TARGET_WIDTH = 1184*6 # 拼接完后的橫向長度

path = "D:/imgs/"
images = [] # 先存儲所有的圖像的名稱
for root, dirs, files in os.walk(path):     
    for f in files :
        images.append(f)
for i in range(len(images)/6): # 6個圖像為一組
    imagefile = []
    j = 0
    for j in range(6):
        imagefile.append(Image.open(path+images[i*6+j])) 
    target = Image.new('RGB', (TARGET_WIDTH, UNIT_SIZE))    
    left = 0
    right = UNIT_SIZE
    for image in imagefile:     
        target.paste(image, (left, 0, right, UNIT_SIZE))# 將image復制到target的指定位置中
        left += UNIT_SIZE # left是左上角的橫坐標,依次遞增
        right += UNIT_SIZE # right是右下的橫坐標,依次遞增
        quality_value = 100 # quality來指定生成圖片的質(zhì)量,范圍是0~100
        target.save(path+'/result/'+os.path.splitext(images[i*6+j])[0]+'.jpg', quality = quality_value)
    imagefile = []

(2)縱向拼接:

import os
from PIL import Image

high_size = 768#高
width_size = 1184#寬

path = u'D:/imgs/'
imghigh = sum([len(x) for _, _, x in os.walk(os.path.dirname(path))])#獲取當前文件路徑下的文件個數(shù)
print imghigh
imagefile = []
for root,dirs,files in os.walk(path):
    for f in files:
        imagefile.append(Image.open(path+f))

target = Image.new('RGB',(width_size,high_size*imghigh))#最終拼接的圖像的大小
left = 0
right = high_size
for image in imagefile:
    target.paste(image,(0,left,width_size,right))
    left += high_size#從上往下拼接,左上角的縱坐標遞增
    right += high_size#左下角的縱坐標也遞增
    target.save(path+'result.jpg',quality=100)

*ValueError: images do not match表示圖片大小和box對應的寬度不一致,參考API說明:Pastes another image into this image. The box argument is either a 2-tuple giving the upper left corner, a 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.使用2緯的box避免上述問題

后續(xù)再更新...

操作圖像部分源碼:
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_resize.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_blur.py
https://github.com/michaelliao/learn-python3/blob/master/samples/packages/pil/use_pil_draw.py
侵刪

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容