先上代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#coco
#将图片切分成多个图片
import os
from PIL import Image
# 切割图片
'''-----------------------------------------------图像分割-----------------------------------------------'''
def splitimage(src, rownum, colnum, dstpath):
img = Image.open(src)
w, h = img.size
print('w,h',w,h)
if rownum <= h and colnum <= w: #JPEG RGB
print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
print('图片切割')
#将文件和路径分割开
#s[0] s[1]
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))
num = num + 1
print('共生成 %s 张小图片。' % num)
return num
else:
print('error')
'''--------------------------------------------创建新文件夹--------------------------------------------------'''
# 创建文件夹
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 符号
#rstrip:用来去除结尾字符、空白符(包括n、r、t、' ',即:换行、回车、制表符、空格)
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 = 'E:/project/Template_detection/Image_preprocessing/data' # 存放图片的文件夹
path = os.listdir(folder)
print(path)
for each_bmp in path: # 批量操作
# os.path.splitext()分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作
first_name, second_name = os.path.splitext(each_bmp)
#print('first_name:',first_name)
#print('second_name:',second_name)
#整个图像文件目录
src=folder+'/'+each_bmp
#出现了'/'和''问题
#src = os.path.join(folder, each_bmp)
print(src)
print(first_name)
# 定义要创建的目录
mkpath = "E:/project/Template_detection/Image_preprocessing/data"+ first_name
# 调用函数
mkdir(mkpath)
#os.path.isfile():判断某一对象(需提供绝对路径)是否为文件
#os.path.isdir():判断某一对象(需提供绝对路径)是否为目录
if os.path.isfile(src):
dstpath = mkpath
#为什么等于空???
if (dstpath =='') or os.path.exists(dstpath):
row = int(2) # 切割行数
col = int(1) # 切割列数
if row > 0 and col > 0:
splitimage(src, row, col, dstpath)
以上就是图像的分割处理,对于我这个草书识别一点用没有,哎
搞了半天。。。
ps:周五了,追剧放松一下。



