栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python实现图片切正方形

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python实现图片切正方形

        想做个照片切规则的正方形用来做九宫图,一般真实照片都是长方形那种,我见过别人把找照片填充成正方形,然后九宫格实在是太丑了,我喜欢整张图全是照片的。

不多赘述,上代码:

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('执行结束')

这个可以将照片切割成正方形。

人生没有奇迹,只有努力。——羽生结弦

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/994919.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号