OpenCV+Python 批量处理图像之裁剪(crop)操作

到现在毕业设终于开始系统做实验写论文了,每解决一个小问题写一篇博客纪念一下:
毕业设计内容:卷积神经网络裂缝图像识别
本博客内容:图像预处理时,将高分辨率图像(10241024)标准化为小尺寸图像(227227)
直接上代码,有问题的请私信我或者评论区交流。

import cv2 as cv
import os


def crop_image(image_dir, output_path, size):   # image_dir 批量处理图像文件夹 size 裁剪后的尺寸
    # 获取图片路径列表
    file_path_list = []
    for filename in os.listdir(image_dir):
        file_path = os.path.join(image_dir, filename)
        file_path_list.append(file_path)

    # 逐张读取图片剪裁
    for counter, image_path in enumerate(file_path_list):
        image = cv.imread(image_path)
        h, w = image.shape[0:2]
        h_no = h // size
        w_no = w // size

        for row in range(0, h_no):
            for col in range(0, w_no):
                cropped_img = image[size*row : size*(row+1), size*col : size*(col+1), : ]
                cv.imwrite(output_path + "img_" + str(counter) + f"crop_{row}_{col}" + ".png",
                           cropped_img)


if __name__ == "__main__":
    image_dir = "D:\\Pycharm_MachineLearning\\cnn_experiment_tool\\crack\\"
    output_path = "D:\\Pycharm_MachineLearning\\cnn_experiment_tool\\resized_crack\\"
    size = 227
    crop_image(image_dir, output_path, size)

结果如下:
原图10241024,48张
在这里插入图片描述裁剪后图像768张,227
227
在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值