想做个照片切规则的正方形用来做九宫图,一般真实照片都是长方形那种,我见过别人把找照片填充成正方形,然后九宫格实在是太丑了,我喜欢整张图全是照片的。
不多赘述,上代码:
import os
from random import randint
import cv2
def 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_COLOR
full_name = source_path + "/" + item_name
print('process +> ', full_name)
img_mat = cv2.imread(full_name, cv2.COLOR_BGR2GRAY)
size = img_mat.shape
w = img_mat.shape[1]
h = img_mat.shape[0]
print('w',w)
print('h',h)
# 根据最短边进行图像裁剪
sp = img_mat.shape
rows = sp[0] # height(rows) of image
cols = sp[1] # width(colums) of image
num=max(rows,cols)
print(num)
if rows >= cols:
shorter = cols
else:
shorter = rows
print(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('执行结束')
这个可以将照片切割成正方形。
人生没有奇迹,只有努力。——羽生结弦