python切割图片

python切割图片

用opencv处理一下
pillow也可以,但是试过有时候会把图片自动旋转180°,cv没有这个问题

import os
from cv2 import cv2


def split_image(src_path, rownum, colnum, file):
    img = cv2.imread(src_path)
    # cv2.imwrite(path, img)
    size = img.shape[0:2]
    w = size[1]
    h = size[0]
    # print(file, w, h)
    # 每行的高度和每列的宽度
    row_height = h // rownum
    col_width = w // rownum
    num = 0
    for i in range(rownum):
        for j in range(colnum):
        	# 保存切割好的图片的路径,记得要填上后缀,以及名字要处理一下,可以是
        	# src_path.split('.')[0] + '_' + str((i+1)*(j+1)) + '.jpg'
            save_path = ''
            row_start = j * col_width
            row_end = (j+1) * col_width
            col_start = i * row_height
            col_end = (i+1) * row_height
            # print(row_start, row_end, col_start, col_end)
            # cv2图片: [高, 宽]
            child_img = img[col_start:col_end, row_start:row_end]
            cv2.imwrite(save_path, child_img)


if __name__ == '__main__':
    # 可以遍历文件夹
    # file_path = r'我是路径(文件夹路径)'
    # for file in file_names:
    # src_path 具体图片路径,包含后缀
    src_path = ''
    row = 4
    col = 4
    split_image(src_path, row, col, file.split('.')[0])

原图:

在这里插入图片描述
切割后:
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜菜菜三菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值