切图按图片的宽度和高度切成多行多列
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
import random,math
import os,time
def cutImage(imagePath,iamgeOutPath,w,h):
for file_name in os.listdir(imagePath):
s_t1 = time.time()
im = Image.open(imagePath+"/"+file_name) # 原始图片路
s_t11 = time.time()
file_name=os.path.splitext(file_name)[0]
img_size = im.size
m = img_size[0] #读取图片的宽度
n = img_size[1] #读取图片的高度
w_split_num_up=math.ceil(m/w)
h_split_num_up =math.ceil(n/h)
w_split_num_int=int(m/w)
h_split_num_int = int(n / h)
s_t2 = time.time()
for w_split_num_item in range(w_split_num_up):
for h_split_num_item in range(h_split_num_up):
if w_split_num_item==w_split_num_int:
x = m-w
else:
x = w_split_num_item * w
if h_split_num_item==h_split_num_int:
y = n-h
else:
y = h_split_num_item * h
region = im.crop((x, y, x + w, y + h))
region.save(iamgeOutPath+"/" + file_name +'_' +str(w_split_num_item)+'_'+ str(h_split_num_item) + ".jpg")
s_t22 = time.time()
print("----2、切图Tatal Cost Time:", s_t22 - s_t2)
print("----1、读图Tatal Cost Time:", s_t11- s_t1)
print("----3、生成图片的数量:", w_split_num_up*h_split_num_up)
#随机切图
# for i in range(1000): #裁剪为100张随机的小图
# # x = random.randint(0, m-w) #裁剪起点的x坐标范围
# # y = random.randint(0, n-h) #裁剪起点的y坐标范围
#
# x=i*1600
# y=i*1600
# region = im.crop((x, y, x+w, y+h)) #裁剪区域
if __name__=="__main__":
imagePath = "/data3/wxh/A_Yolov5s/data/images"
iamgeOutPath = "/data3/wxh/A_Yolov5s/data/images175"
w = 1600 # 设置你要裁剪的小图的宽度
h = 1600 # 设置你要裁剪的小图的高度
cutImage(imagePath, iamgeOutPath, w, h)