图像数据预处理
图像增强方法汇总
使用cv2
水平翻转
def horizon_flip(img):
#图像水平翻转
return cv2.flip(img, 1)
垂直翻转
def vertical_flip(img):
#图像垂直翻转
return cv2.flip(img, 0)
仿射(角度)变化
def rotate(img, limit_up=10, limit_down=-10):
#在一定角度范围内,图像随机旋转
rows, cols = img.shape[:2]
center_coordinate = (int(cols / 2), int(rows / 2))
angle = random.uniform(limit_down, limit_up)
M = cv2.getRotationMatrix2D(center_coordinate, angle, 1)
# 仿射变换
out_size = (cols, rows)
rotate_img = cv2.warpAffine(img, M, out_size, borderMode=cv2.BORDER_REPLICATE)
return rotate_img
仿射平移变化
def shift(img, distance_down, distance_up):
#利用仿射变换实现图像平移,平移距离∈[down, up]
rows, cols = img.shape[:2]
y_shift = random.uniform(distance_down, distance_up)
x_shift = random.uniform(distance_down, distance_up)
# 生成平移矩阵
M = np.float32([[1, 0, x_shift], [0, 1, y_shift]])
# 平移
img_shift = cv2.warpAffine(img, M, (cols, rows), borderMode=cv2.BORDER_REPLICATE)
return img_shift
亮度对比度调整
def lighting_adjust(img, k_down, k_up, b_down, b_up):
# 图像亮度、对比度调整
# :param img:
# :param k_down:对比度系数下限
# :param k_up:对比度系数上限
# :param b_down:亮度增值上限
# :param b_up:亮度增值下限
# :return:调整后的图像
#
# #对比度调整系数
slope = random.uniform(k_down, k_up)
# 亮度调整系数
bias = random.uniform(b_down, b_up)
# 图像亮度和对比度调整
img = img * slope + bias
# 灰度值截断,防止超出255
img = np.clip(img, 0, 255)
return cv2.cvtColor(img.astype(np.uint8),cv2.COLOR_BGR2RGB)
高斯噪声
def Gaussian_noise(img):
#
# 图像加高斯噪声
# :param img: 原图
# :param mean: 均值
# :param std: 标准差
# :return:
#
# # 高斯噪声图像
img = cv2.GaussianBlur(img, (5, 5), 1.1)
return img
椒盐噪声
def sp_noiseImg(img_file1,prob): #同时加杂乱(RGB单噪声)RGB图噪声 prob:噪声占比
image = np.array(img_file1,dtype=float)
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]
#prob = 0.05 #噪声占比 已经比较明显了 >0.1 严重影响画质
NoiseImg = image.copy()
NoiseNum = int(prob * image.shape[0] * image.shape[1])
for i in range(NoiseNum):
rows = np.random.randint(0, image.shape[0] - 1)
cols = np.random.randint(0, image.shape[1] - 1)
channel = np.random.randint(0, 3)
if np.random.randint(0, 2) == 0:#随机加盐或者加椒
NoiseImg[rows, cols, channel] = 0
else:
NoiseImg[rows, cols, channel] = 255
return NoiseImg
锐化处理
def burl(image):
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) # 锐化
dst = cv2.filter2D(image, -1, kernel=kernel)
return dst