python + opencv 图像4等份切割

本文介绍了一个使用Python实现的图像处理程序,该程序能够将指定文件夹内的所有图片进行四等分切割,并将切割后的子图像保存到新的文件夹中。通过简单的脚本实现了图像的批量处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用python对图像进行4等分切割,这里是使用目录,对目录中的所有图像进行切割后保存到新的目录中

mport cv2
import os
import pathlib
source_path = "D:/up_cam124_90"
target_path = "D:/up_cam124_90_split"

def mkdir(path):
    path = path.strip()
    path = path.rstrip("\\")
 
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        print(path + ' 目录已存在')
        return False


def split_img(img_file):
    img = cv2.imread(img_file)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    img_h = img.shape[0]  # 高度
    img_w = img.shape[1]  # 宽度
    # h1_half = int(img_h / 2)
    # w1_half = int(img_w / 2)

    h1_half = img_h // 2
    w1_half = img_w // 2

    img_name = os.path.basename(img_file)
    for i in range(4):
        img1 = img[int(i / 2) * h1_half: h1_half * (int(i / 2) + 1), int(i % 2) * w1_half: (int(i % 2) + 1) * w1_half]

        img1_path = os.path.join(target_path, f"{img_name[:-4]}_{i}.jpg")
        print("spilt img:", img1_path)
        cv2.imwrite(img1_path, img1)


if __name__ == '__main__':
    mkdir(target_path)
    for file in pathlib.Path(source_path).glob('**/*'):

        split_img(os.path.join(source_path, file))

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值