1 Star 0 Fork 0

kongfu/py3Utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
split_image.py 2.75 KB
一键复制 编辑 原始数据 按行查看 历史
kongfu 提交于 2018-02-26 17:38 . 添加python切割地图的例子
import os,math
import time
from PIL import Image
# http://www.cnblogs.com/ecofast/p/5487926.html
# https://python-pillow.org
def splitimage(src, dstpath):
img = Image.open(src)
w, h = img.size
smallSize = 256
rownum = math.ceil(h/smallSize)
colnum = math.ceil(w/smallSize)
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), 'jpeg')
num = num + 1
print('图片切割完毕,共生成 %s 张小图片。' % num)
else:
print('不合法的行列切割参数!')
def get_dir_imgs(dirUrl):
files = os.listdir(dirUrl)
result = [ os.path.join(dirUrl,f) for f in files if os.path.isfile(os.path.join(dirUrl,f))]
return result
def split_img(src,saveUrl):
img = Image.open(src)
w, h = img.size
smallSize = 256
rownum = math.ceil(h/smallSize)
colnum = math.ceil(w/smallSize)
for col in range(0,colnum):
for row in range(0,rownum):
left = col*smallSize
uper = row*smallSize
box = (left,uper,left+smallSize,uper+smallSize) #左上右下
a = ""
b = ""
c = ""
tarUrl = os.path.join(saveUrl,str(col)+"_"+str(row)+".jpg")
img.crop(box).save(tarUrl)
print("saveUrl:",tarUrl)
src = "D:/srcimg/big.jpg"
#src = "D:/srcimg/scene.jpg"
saveUrl = "D:\imgsave"
'''
imgs = "D:/srcimg"
fs = get_dir_imgs(imgs)
src = fs[0]
print(fs)
'''
#splitimage(src, '')
st = time.time()
split_img(src,saveUrl)
et = time.time()
print('cost time :',et-st)
'''
src = input('请输入图片文件路径:')
if os.path.isfile(src):
dstpath = input('请输入图片输出目录(不输入路径则表示使用源图片所在目录):')
if (dstpath == '') or os.path.exists(dstpath):
row = int(input('请输入切割行数:'))
col = int(input('请输入切割列数:'))
if row > 0 and col > 0:
splitimage(src, row, col, dstpath)
else:
print('无效的行列切割参数!')
else:
print('图片输出目录 %s 不存在!' % dstpath)
else:
print('图片文件 %s 不存在!' % src)
'''
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/kongfu/py3Utils.git
[email protected]:kongfu/py3Utils.git
kongfu
py3Utils
py3Utils
master

搜索帮助