功能说明
def image_combines(img_dir,fw=1,fh=1,cols=1,flag_sort=True,IMAGES_FORMAT = ['.jpg', '.JPG', 'PNG', '.png', '.jpeg']):
'''
img_dir 表示需要遍历文件夹
fw,fh 分别表示图像宽、高统一放缩的比例,1表示1倍
cols 表示拼接后的图片的每行多少张小图片(多少列),cols=0时,自动按照平方根拼接
flag_sort=True 路径按字符串顺序排列,防止每次图片位置不一样
'''
代码
def image_combines(img_dir,fw=1,fh=1,cols=0,flag_sort=True,IMAGES_FORMAT = ['.jpg', '.JPG', 'PNG', '.png', '.jpeg']):IMAGES_PATH=img_dirimg_paths=[]for cur_dir,folders,files in os.walk(IMAGES_PATH):for name in files:if name.endswith(tuple(IMAGES_FORMAT)):path=os.path.join(cur_dir,name)img_paths.append(path)# image_names = [name for name in (os.listdir(IMAGES_PATH)) for item in IMAGES_FORMAT if# os.path.splitext(name)[1] == item]if flag_sort:img_paths.sort()print('img_paths',img_paths)n_imgs=len(img_paths)# 向上取整 方图squrt=math.ceil(math.sqrt(n_imgs))print("n_imgs",n_imgs)print("squrt",squrt)# 如果不指定图片的列数,就需要if cols!=0:IMAGE_COLUMN=colselse:IMAGE_COLUMN =squrt # 图片间隔,也就是合并成一张图后,一共有几列IMAGE_ROW = n_imgs//IMAGE_COLUMN # 图片间隔,也就是合并成一张图后,一共有几行if n_imgs%IMAGE_COLUMN!=0:IMAGE_ROW+=1print("IMAGE_ROW,IMAGE_c",IMAGE_ROW,IMAGE_COLUMN)# https://blog.csdn.net/weixin_44548693/article/details/104125989src_w,src_h=Image.open(img_paths[0]).sizeIMAGE_X_SIZE=int(src_w*fw)IMAGE_Y_SIZE=int(src_h*fh)print("IMAGE_X_SIZE,IMAGE_c",IMAGE_X_SIZE,IMAGE_X_SIZE)to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_X_SIZE, IMAGE_ROW * IMAGE_Y_SIZE)) # 创建一个新图# 循环遍历,把每张图片按顺序粘贴到对应位置上i=0for y in range(1, IMAGE_ROW + 1):for x in range(1, IMAGE_COLUMN + 1):if i>=n_imgs:breakimg_path=img_paths[i]from_image = Image.open(img_path).resize((IMAGE_X_SIZE, IMAGE_Y_SIZE), Image.ANTIALIAS)# from_image = Image.open(os.path.join(IMAGES_PATH , image_names[IMAGE_COLUMN * (y - 1) + x - 1])).resize((IMAGE_X_SIZE, IMAGE_Y_SIZE), Image.ANTIALIAS)to_image.paste(from_image, ((x - 1) * IMAGE_X_SIZE, (y - 1) * IMAGE_Y_SIZE))i+=1return to_imageif __name__ == '__main__':test=r'your_imge_dir'to_image=image_combines(test,fw=0.5,fh=0.5,cols=5)to_image.save('./test.png')# 没有指定列cols,将自动计算列参数to_image=image_combines(test,fw=0.5,fh=0.5)to_image.save('./test_squra.png')
自动计算列宽拼接结果