图片指定大小切割拼接
import os
from PIL import Image
'''
切割图片
'''
def breakup(src, rownum, colnum):
# xxx/xxx/ xxx.png
s = os.path.split(src)
# xxx.png
fn = os.path.splitext(s[1])
# xxx
basename = fn[0]
# .png
ext = fn[1]
num = 0
img = Image.open(src)
w, h = img.size
if rownum <= h and colnum <= w:
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(os.getcwd() +
"/image/breakup/", basename + '_' +
str(num) + ext), ext[1:])
num+=1
'''
合并图片
'''
def reorganize(dir,prefix,rownum, colnum,w,h):
ls = os.listdir(dir)
image = Image.new('RGB', (colnum*w, rownum*h))
x = 0
y = 0
for i in range(0, len(ls)):
try:
img = Image.open(dir+"/"+ prefix +"_"+ str(i) + ".png")
except IOError:
print("Error")
else:
img = img.resize((w, h), Image.ANTIALIAS)
image.paste(img, (x * w, y * h))
x += 1
if x == colnum:
x = 0
y += 1
image.save(os.getcwd() + "/image/to/all.jpg")
if __name__ == '__main__':
breakup(os.getcwd() + "/image/from/bbb.png",4,10)
reorganize(os.getcwd() + "/image/breakup","bbb",2,20,30,46)
```
import os
from PIL import Image
'''
切割图片
'''
def breakup(src, rownum, colnum):
# xxx/xxx/ xxx.png
s = os.path.split(src)
# xxx.png
fn = os.path.splitext(s[1])
# xxx
basename = fn[0]
# .png
ext = fn[1]
num = 0
img = Image.open(src)
w, h = img.size
if rownum <= h and colnum <= w:
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(os.getcwd() +
"/image/breakup/", basename + '_' +
str(num) + ext), ext[1:])
num+=1
'''
合并图片
'''
def reorganize(dir,prefix,rownum, colnum,w,h):
ls = os.listdir(dir)
image = Image.new('RGB', (colnum*w, rownum*h))
x = 0
y = 0
for i in range(0, len(ls)):
try:
img = Image.open(dir+"/"+ prefix +"_"+ str(i) + ".png")
except IOError:
print("Error")
else:
img = img.resize((w, h), Image.ANTIALIAS)
image.paste(img, (x * w, y * h))
x += 1
if x == colnum:
x = 0
y += 1
image.save(os.getcwd() + "/image/to/all.jpg")
if __name__ == '__main__':
breakup(os.getcwd() + "/image/from/bbb.png",4,10)
reorganize(os.getcwd() + "/image/breakup","bbb",2,20,30,46)
```