本文實例為大家分享了python實現多張圖片拼接成大圖的具體代碼,供大家參考,具體內容如下
上次爬取了馬蜂窩的游記圖片,并解決了pil模塊的導入問題,現在直奔主題吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import pil.image as image import os images_path = 'd:\mafengwo\photo\五月坦桑的暖風,非洲原野的呼喚\\' # 圖片集地址 images_format = [ '.jpg' , '.jpg' ] # 圖片格式 image_size = 256 # 每張小圖片的大小 image_row = 5 # 圖片間隔,也就是合并成一張圖后,一共有幾行 image_column = 4 # 圖片間隔,也就是合并成一張圖后,一共有幾列 image_save_path = 'final.jpg' # 圖片轉換后的地址 # 獲取圖片集地址下的所有圖片名稱 image_names = [name for name in os.listdir(images_path) for item in images_format if os.path.splitext(name)[ 1 ] = = item] # 簡單的對于參數的設定和實際圖片集的大小進行數量判斷 if len (image_names) ! = image_row * image_column: raise valueerror( "合成圖片的參數和要求的數量不能匹配!" ) # 定義圖像拼接函數 def image_compose(): to_image = image.new( 'rgb' , (image_column * image_size, image_row * image_size)) #創建一個新圖 # 循環遍歷,把每張圖片按順序粘貼到對應位置上 for y in range ( 1 , image_row + 1 ): for x in range ( 1 , image_column + 1 ): from_image = image. open (images_path + image_names[image_column * (y - 1 ) + x - 1 ]).resize( (image_size, image_size),image.antialias) to_image.paste(from_image, ((x - 1 ) * image_size, (y - 1 ) * image_size)) return to_image.save(image_save_path) # 保存新圖 image_compose() #調用函數 |
前邊設置了很多變量,都很直觀,然后時獲取圖片的名稱以及對需要拼接圖片的數量進行檢查,比如你要拼接5*5的大圖,那就需要25張圖片,最后是我們的主函數,依次遍歷,主要還是利用了image模塊的強大功能,我們需要做的就是無縫對接。
效果如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/beyond9305/article/details/83413009