opencv之图象裁剪

在深度学习的模型训练中,经常需要将模型裁剪成模型要求的输入尺寸。本文介绍了如何将一个矩形的图像裁剪成指定尺寸的正方形图像。

import cv2
import os


def cut_images(origin_image, image_size):
    """
    图像裁剪:将图像裁剪成固定尺寸的大小作为模型的输入。
    (1)先将图象resize成短边和image_size一致,然后再从中间截取图像。
    (2)此处只考虑了长宽相等的情况,因此image_size只是一个数值。
    :return 裁剪后的image数组。
    """
    # origin_image = cv2.imread(origin_image_path)
    height, width = origin_image.shape[0], origin_image.shape[1]
    if height <= width:
        new_height = image_size
        new_width = int(width/height * image_size)
        # 注意:imread()返回的是(height,width), resize的参数是(width,height)
        origin_image = cv2.resize(origin_image, (new_width, new_height))
        # 从图像中间截取
        cut_width = int((new_width-new_height)/2)
        return_image = origin_image[:, cut_width:cut_width+image_size, :]
        print(new_height, new_width, origin_image.shape, cut_width, return_image.shape)
    else:
        new_width = image_size
        new_height = int(height/width * image_size)
        origin_image = cv2.resize(origin_image, (new_width, new_height))
        # 从图像中间截取
        cut_height = int((new_height-new_width)/2)
        return_image = origin_image[cut_height:cut_height+image_size, :, :]
        print(new_height, new_width, origin_image.shape, cut_height, return_image.shape)

    return return_image


def cut_images_file(origin_image_path, target_image_path, image_size):
    """
    将图像或者目录中的图像剪裁成某个尺寸。
    :return:
    """
    if os.path.isfile(origin_image_path) and not os.path.isdir(target_image_path):
        origin_image = cv2.imread(origin_image_path)
        return_images = cut_images(origin_image, image_size)
        cv2.imwrite(target_image_path, return_images)
    elif os.path.isdir(origin_image_path) and os.path.isdir(target_image_path):
        images = os.listdir(origin_image_path)
        for origin_image_name in images:
            origin_image = cv2.imread(os.path.join(origin_image_path, origin_image_name))
            print(origin_image_name, origin_image.shape)
            return_images = cut_images(origin_image, image_size)
            cv2.imwrite(os.path.join(target_image_path,origin_image_name), return_images)
    else:
        return 1


def cut_images_demo():
    origin_image_dir = '/Users/lujinhong/Downloads/image_cut/origin'
    target_image_dir = '/Users/lujinhong/Downloads/image_cut/cut'
    cut_images_file(origin_image_dir, target_image_dir, 224)

    origin_image_file = '/Users/lujinhong/Downloads/image_cut/1.jpeg'
    target_image_file = '/Users/lujinhong/Downloads/image_cut/1_cut.jpeg'
    cut_images_file(origin_image_file, target_image_file, 224)


if __name__ == '__main__':
    cut_images_demo()

你可能感兴趣的:(9.图象_NLP,opencv,pytorch,深度学习)