cutmix

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
import random
import numpy as np
import cv2
import os
import math
import torch
from torch import nn

图像灰度延展、直方图均衡化

file_root = r'E:\wd_0.01_deal\wd_train_0.01\wd_train_0.01_4_2parts\real/'  # 当前文件夹下的所有图片
file_list = os.listdir(file_root)
save_out = r"E:\wd_0.01_deal\wd_train_0.01\4_cutmix\real/"  # 保存图片的文件夹名称


def rand_bbox(size, lam):
W = size[2]
H = size[3]
cut_rat = np.sqrt(1. - lam)
cut_w = np.int(W * cut_rat)
cut_h = np.int(H * cut_rat)

 #       uniform
cx = np.random.randint(W)
cy = np.random.randint(H)

bbx1 = np.clip(cx - cut_w // 2, 0, W)
bby1 = np.clip(cy - cut_h // 2, 0, H)
bbx2 = np.clip(cx + cut_w // 2, 0, W)
bby2 = np.clip(cy + cut_h // 2, 0, H)
return bbx1, bby1, bbx2, bby2
def cutmix(data, alpha):
indices = nn.randperm(data.size(0))
shuffled_data = data[indices]
# shuffled_target = target[indices]

lam = np.clip(np.random.beta(alpha, alpha), 0.3, 0.4)
bbx1, bby1, bbx2, bby2 = rand_bbox(data.size(), lam)
new_data = data.clone()
new_data[:, :, bby1:bby2, bbx1:bbx2] = data[indices, :, bby1:bby2, bbx1:bbx2]
    # adjust lambda to exactly match pixel ratio
lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (data.size()[-1] * data.size()[-2]))
# targets = (target, shuffled_target, lam)

return new_data
for img_name in file_list:
img_path = file_root + img_name

img = cv.imread(img_path, -1)
# out_min = 0
# out_max = 255
#
# in_min = np.min(img)
# in_max = np.max(img)
#
# a = float(out_max - out_min) / (in_max - in_min)
# b = out_min - a * in_min
# img_norm = img * a + b
# img_norm = img_norm.astype(np.uint8)
#尺寸变小
# h, w, _ = img.shape
# s_h = h // 2
# s_w = w // 2
# img = cv2.resize(img, (s_w, s_h))
# 高斯模糊
# img = cv2.GaussianBlur(img, (5, 5), 5)
#随机翻转
# if random.randint(0, 1):
#
#    axis = random.randint(0, 2)
#
#    img = np.flip(img, axis=axis)
#cutmix
# """train.py 279-295行"""
# """输入为:样本的size和生成的随机lamda值"""
img = cutmix(img, 1)
# img = cv2.resize(img, (w, h))
img_norm = img.astype(np.uint8)
# out_name = img_name.split('.')[0]
out_name = img_name
save_path = save_out + 'cutmix_' + out_name + '.png'
cv2.imwrite(save_path, img_norm)#

你可能感兴趣的:(机器学习常用代码总结,python,计算机视觉,深度学习)