想做个照片切规则的正方形用来做九宫图,一般真实照片都是长方形那种,我见过别人把找照片填充成正方形,然后九宫格实在是太丑了,我喜欢整张图全是照片的。
不多赘述,上代码:
import os
from random import randint
import cv2def cut_resize_file(source_path, output_path, file_type, cut_size):"""先根据最短边进行裁剪,为正方形,在重设大小,默认256:param source_path::param output_path::param file_type::param cut_size::return:"""path_files = os.listdir(source_path)for item_name in path_files:if item_name.endswith(file_type): # 扩展名是图片# 调用cv2.imread读入图片,读入格式为IMREAD_COLORfull_name = source_path + "/" + item_nameprint('process +> ', full_name)img_mat = cv2.imread(full_name, cv2.COLOR_BGR2GRAY)size = img_mat.shapew = img_mat.shape[1]h = img_mat.shape[0]print('w',w)print('h',h)# 根据最短边进行图像裁剪sp = img_mat.shaperows = sp[0] # height(rows) of imagecols = sp[1] # width(colums) of imagenum=max(rows,cols)print(num)if rows >= cols:shorter = colselse:shorter = rowsprint(num-shorter)cropped = img_mat[num-shorter:num,0:shorter] # 裁剪坐标为[y0:y1, x0:x1]new_array = cv2.resize(cropped, cut_size)random_name = str(randint(0, 99999)) + '.jpg' # 随机生成一个数字作为名字cv2.imwrite(output_path + '/' + random_name, new_array)if __name__ == '__main__':# 本方法用于将原图依照最短边进行重设大小,并裁剪print('执行开始')source_path = './data' # 原图路径output_path = './output/' # 保存路径file_type = '.jpg' # 文件扩展名cut_size = (512, 512) # 裁剪大小cut_resize_file(source_path, output_path, file_type, cut_size)print('执行结束')
这个可以将照片切割成正方形。
人生没有奇迹,只有努力。——羽生结弦