如有错误,恳请指出。
下面简单记录测试了部分数据增强案例,具体原理可以见参考资料,这里不作介绍。
import cv2
import numpy as np
import math
def Img_Show(img):
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
1. 旋转、平移、缩放
img = cv2.imread("./photo/cow.jpg")
h, w = img.shape[0], img.shape[1]
r_img = cv2.warpAffine(src = img,
M = cv2.getRotationMatrix2D(center=(w // 2, h // 2), angle=-30, scale=0.5),
dsize = (w, h),
borderValue = (0, 0, 0))
Img_Show(r_img)
旋转、平移、缩放后图像:
2. 错切
img = cv2.imread("./photo/cow.jpg")
h, w = img.shape[0], img.shape[1]
angle = 30
mh = np.eye(3)
mh[0, 1] = np.tan(np.radians(angle))
hh, wh = h, w+h*mh[0, 1]
imgh = cv2.warpAffine(src = img,
M = mh[:2],
dsize = (int(wh), int(hh)),
borderValue = (0, 0, 0))
Img_Show(imgh)
mv = np.eye(3)
mv[1, 0] = np.tan(np.radians(angle))
hv, wv = h+w*mv[1, 0], w
imgv = cv2.warpAffine(src = img,
M = mv[:2],
dsize = (int(wv), int(hv)),
borderValue = (0, 0, 0))
Img_Show(imgv)
mb = np.eye(3)
mb[0, 1] = np.tan(np.radians(angle))
mb[1, 0] = np.tan(np.radians(angle))
hb, wb = h+w*mv[1, 0], w+h*mh[0, 1]
imgb = cv2.warpAffine(src = img,
M = mb[:2],
dsize = (int(wb), int(hb)),
borderValue = (0, 0, 0))
Img_Show(imgb)
水平错切30°图像: 竖直错切30°图像: 两个方向同时错切30°图像:
3. 随机增强图像HSV
def augment_hsv(img, h_gain=0.5, s_gain=0.5, v_gain=0.5):
r = np.random.uniform(-1, 1, 3) * [h_gain, s_gain, v_gain] + 1
hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
dtype = img.dtype
x = np.arange(0, 256, dtype=np.int16)
lut_hue = ((x * r[0]) % 180).astype(dtype)
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
aug_img = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR)
return aug_img
img = cv2.imread("./photo/cow.jpg")
img_hsv = augment_hsv(img)
Img_Show(img)
Img_Show(img_hsv)
原始图像: 数据增强后图像:
参考资料:
- 数据增广:旋转,缩放,平移以及错切
- HSV模型简介以及利用HSV模型随机增强图像
|