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张
OpenCV+Python 批量处理图像之裁剪(crop)操作_第1张图片裁剪后图像768张,227
227
OpenCV+Python 批量处理图像之裁剪(crop)操作_第2张图片

你可能感兴趣的:(OpenCV)