概述
不做过多解释,请自行理解 ,其中CheckPixel方法可以删掉,写这个方法的目的是为了排除透明的块,使得图片资源尽可量的小
# -*- coding: utf-8 -*-
from PIL import Image
import struct
import sys
import os
num = 0
def CheckPixel(region):
x, y = region.size
empty_box = Image.new('RGBA', (int(x + 1), int(y + 1)))
empty_box.paste(region,(0,0))
width, height = empty_box.size
pix_array = empty_box.load()
for i in range(width):
for j in range(height):
tuple = pix_array[i, j]
if len(tuple) == 4:
if tuple[3] != 0: # 非透明
return False
return True # 透明
def CutImg(imgPath, imgSaveDir, widthNum, heightNum, imgName):
global num
num +=1
img = Image.open(imgPath)
size = img.size
width = float(size[0]) / widthNum
height = float(size[1]) / heightNum
print(num, ' Image name: ', imgName, ' (宽,高):',size, ' 切割后 (宽,高): ',(width, height) , 'n')
for i in range(widthNum):
for j in range(heightNum):
box = (width * j, height * i, width * (j + 1), height * (i + 1))
region = img.crop(box)
if CheckPixel(region): # 检查是否透明,透明不存储
continue
new_i = i
new_j = j
if i < 10:
new_i = '0' + str(i)
if j < 10:
new_j = '0' + str(j)
region.save(imgSaveDir + '\' + imgName.split('.')[0] + '_{}{}.png'.format(new_i, new_j))
def TraverseDir(now_Dir, new_dir, widthNum, heightNum):
try:
if not os.path.exists(new_dir):
os.mkdir(new_dir)
for roots, dirs, files in os.walk(now_Dir):
# 操作根目录下的图片
for imgName in files:
if imgName.endswith('png') or imgName.endswith('jpg'):
# imgNum = imgName.split('.')[0]
imgSaveDir = new_dir # 仅仅为了展示字段的作用
if not os.path.exists(imgSaveDir):
os.mkdir(imgSaveDir)
imgPath = roots + '\' + imgName
CutImg(imgPath, imgSaveDir, widthNum, heightNum, imgName)
if len(dirs) != 0:
for dir in dirs:
new_nowDir = now_Dir + '\' + dir
new_newDir = new_dir + '\' + dir
TraverseDir(new_nowDir, new_newDir, widthNum, heightNum)
break
else:
break
except IOError:
print("执行出错,请退出重新尝试!!!")
if __name__ == '__main__':
print("start...")
print()
widthNum, heightNum = map(int, input('请输入要切割的比例,比如3*3,请输入3 3(中间以空格分开): nn').split(' '))
exedir_root = sys.argv[0][:-11]
basedir = sys.argv[1]
dirname = basedir.split('\')[-1]
new_dir = exedir_root + '\' + dirname + '_cut'
print('---------------------------------------------------------')
print('n原路径: ', basedir)
print('n保存路径: ', new_dir, 'n')
print('---------------------------------------------------------n')
TraverseDir(basedir, new_dir, widthNum, heightNum)
# TraverseDir('C:\UsersAdministratorDesktop新建文件夹\1', 'C:\UsersAdministratorDesktop新建文件夹\1_cut', 3,3)
print('n---------------------------------------------------------n')
print('切割的图片总数为:%d n' % num)
print('已完成!!!')
os.system("pause")
最后
以上就是落后大米为你收集整理的python PIL库对图片按比例进行分割的全部内容,希望文章能够帮你解决python PIL库对图片按比例进行分割所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复