一、說在前面
? ? ? ?需求:有一張長為960,寬為96的圖片,需要將其分割成10張96*96的圖片并存放在另外一個文件夾下,通過手工分割耗時且不規范,選擇python寫一個簡單的程序完成。
二、源碼
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 18:19:09 2018
@author: Administrator
"""
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('error')
# 創建文件夾
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符號
path = path.rstrip("\\")
# 判斷路徑是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判斷結果
if not isExists:
os.makedirs(path)
print (path+' 創建成功')
return True
else:
print (path + ' 目錄已存在')
return False
folder = r'C:/Users/Administrator/Desktop/testresults' # 存放圖片的文件夾
path = os.listdir(folder)
# print(path)
for each_bmp in path: # 批量操作
first_name, second_name = os.path.splitext(each_bmp)
each_bmp = os.path.join(folder, each_bmp)
src = each_bmp
print(src)
print(first_name)
# 定義要創建的目錄
mkpath = "C:/Users/Administrator/Desktop/results/"+ first_name
# 調用函數
mkdir(mkpath)
if os.path.isfile(src):
dstpath = mkpath
if (dstpath == '') or os.path.exists(dstpath):
row = int(1) # 切割行數
col = int(10) # 切割列數
if row > 0 and col > 0:
splitimage(src, row, col, dstpath)
else:
print('無效的')
else:
print('圖片保存目錄 %s 不存在!' % dstpath)
else:
print('圖片文件 %s 不存在!' % src)
三、寫在后面
這里定義了切割行數和列數:
如果需要將圖片更改尺寸,可以簡單的使用PIL庫中的resize()函數,代碼如下:
from PIL import Image
for i in range(1,100):
img = Image.open("C:/Users/Administrator/Desktop/test_results/"+str(i)+".png")
img = img.convert("L")
img = img.resize((960,96))
img.save("C:/Users/Administrator/Desktop/test_results/"+str(i)+".png", "PNG")
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

