【CV】制作数据集(裁剪图片)

记录制作数据集裁剪图片的代码


import numpy as np
from PIL import Image
import sys
import os

def SampleCount(length, sample_step=128):
    ## 这个函数的实现的功能就是判断当前维度可以分成多少个sample_step,应该就是划分成多少个patch

    count = length * 1.0 / sample_step
    count = int(count)
    return count

def cut_image(image):
    width, height = image.size
    n = SampleCount(width)
    m = SampleCount(height)
    item_width = 128  # 修改这里的参数
    item_height = 128  # 修改这里的参数
    box_list = []
    count = 0
    for j in range(0, m):  # 修改这里的参数
        for i in range(0, n):  # 修改这里的参数
            count += 1
            box = (54+i * item_width, 38+j * item_height, 54+(i + 1) * item_width, 38+(j + 1) * item_height)
            box_list.append(box)
    print(count)
    image_list = [image.crop(box) for box in box_list]
    return image_list

wx = -1
def save_images(image_list,image_name,save_path,image_mean):
    index = 1
    j = 0
    global wx
    for image in image_list:
        image.save(os.path.join(save_path, image_name.split(".")[0].rstrip('0') + str(index) + "_" + str(image_mean[wx][j]) + ".png"))
        j = j + 1
        index += 1
    wx = wx + 1

def search_mean(image_list1):
    image_mean = []
    for image in image_list1:
        imgArr = np.array(image)
        img = imgArr/255
        image_means = np.mean(img)
        image_mean.append(image_means)
    return image_mean

if __name__ == '__main__':
    file_path = r"D:\data_lab\photo\test"
    file_path1 = r"D:\data_lab\photo\test_trans"
    save_path = r"D:\data_lab\photo\t"
    # 打开图像
    image_mean = []
    for image_name1 in os.listdir(file_path1):
        print(image_name1)
        image1 = Image.open(os.path.join(file_path1,image_name1))
        image_list1 = cut_image(image1)
        image_mean.append(search_mean(image_list1))

    for image_name in os.listdir(file_path):
        print(image_name)
        image = Image.open(os.path.join(file_path,image_name))
        image_list = cut_image(image)
        save_images(image_list,image_name,save_path,image_mean)


越努力,越幸运

end~

你可能感兴趣的:(【CV】制作数据集(裁剪图片))