python切割圖片的示例
更新時間:2020年11月12日 16:37:22 作者:jujua
這篇文章主要介紹了利用python切割圖片的示例,幫助大家更好的利用python處理圖片,感興趣的朋友可以了解下
這個小程序可以自己設定行數(shù)和列數(shù)進行圖片切割
import os from PIL import Image def splitimage(src, rownum, colnum, dstpath): img = Image.open(src) w, h = img.size if rownum <= h and colnum <= w: print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode)) print('開始處理圖片切割, 請稍候...') s = os.path.split(src) if dstpath == '': dstpath = s[0] fn = s[1].split('.') basename = fn[0] ext = fn[-1] num = 0 rowheight = h // rownum colwidth = w // colnum for r in range(rownum): for c in range(colnum): box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight) img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext) num = num + 1 print('圖片切割完畢,共生成 %s 張小圖片。' % num) else: print('不合法的行列切割參數(shù)!') src = input('請輸入圖片文件路徑:') if os.path.isfile(src): dstpath = input('請輸入圖片輸出目錄(不輸入路徑則表示使用源圖片所在目錄):') if (dstpath == '') or os.path.exists(dstpath): row = int(input('請輸入切割行數(shù):')) col = int(input('請輸入切割列數(shù):')) if row > 0 and col > 0: splitimage(src, row, col, dstpath) else: print('無效的行列切割參數(shù)!') else: print('圖片輸出目錄 %s 不存在!' % dstpath) else: print('圖片文件 %s 不存在!' % src)
運行效果
以上就是利用python切割圖片的示例的詳細內(nèi)容,更多關(guān)于python 切割圖片的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python中使用Queue和Condition進行線程同步的方法
這篇文章主要介紹了Python中使用Queue模塊和Condition對象進行線程同步的方法,配合threading模塊下的線程編程進行操作的實例,需要的朋友可以參考下2016-01-01Pycharm使用時會出現(xiàn)的問題之cv2無法安裝解決
這篇文章主要介紹了Pycharm使用時會出現(xiàn)的問題之cv2無法安裝解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05對python中字典keys,values,items的使用詳解
今天小編就為大家分享一篇對python中字典keys,values,items的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02