数据增强中常用的方法有:镜像(flip)、旋转(rotation)、缩放(scale)、裁剪(crop)、平移(translation)、高斯噪声(gaussion noise)、图像亮度、饱和度和对比度变化
旋转
def rotate_func(image):
cols,rows,_,=image.shape
M=cv2.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),angle,1)
#cv2.getRotationMarix2D(point2f center,double angle,double scale)
#参数分别为:旋转中心,旋转角度,图像缩放因子
dst=cv2.warpAffine(img,M,(cols,rows))
#仿射变换其三个参数分别为:输入图像,变换矩阵,输出图像大小
#保存图像
return dst
def randomRotation(image, mode=Image.BICUBIC):
"""
对图像进行随机任意角度(0~360度)旋转
:param mode 邻近插值,双线性插值,双三次B样条插值(default)
:param image PIL的图像image
:return: 旋转转之后的图像
"""
random_angle = np.random.randint(1, 360)
return image.rotate(random_angle, mode)
翻转
#coding=utf-8
from PIL import Image
import os
import os.path
#图片的水平翻转
#创建文件夹
#os.mkdir(r'./38f')
#删除文件
#os.remove('./38/rotation.py')
#os.remove('./38/rotation.py~')
rootdir = r'/home/qxq/Desktop/eyedata/train/label/21/' # 指明被遍历的文件夹
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
print('parent is :' + parent)
print('filename is :' + filename)
currentPath = os.path.join(parent, filename)
print('the fulll name of the file is :' + currentPath)
im = Image.open(currentPath)
out = im.transpose(Image.FLIP_LEFT_RIGHT)
newname1 = r"/home/qxq/Desktop/eyedata/train/label/21f/" + 'L_' + filename
out.save(newname1)
out1 = im.transpose(Image.FLIP_TOP_BOTTOM)
newname2 = r"/home/qxq/Desktop/eyedata/train/label/21f/" + 't_' + filename
out1.save(newname2)
平移
def randomShift(image):
#def randomShift(image, xoffset, yoffset=None):
"""
对图像进行平移操作
:param image: PIL的图像image
:param xoffset: x方向向右平移
:param yoffset: y方向向下平移
:return: 翻转之后的图像
"""
random_xoffset = np.random.randint(0, math.ceil(image.size[0]*0.2))
random_yoffset = np.random.randint(0, math.ceil(image.size[1]*0.2))
#return image.offset(xoffset = random_xoffset, yoffset = random_yoffset)
return image.offset(random_xoffset)
模糊
def darken_func(image):
# .SMOOTH
# .SMOOTH_MORE
# .GaussianBlur(radius=2 or 1)
# .MedianFilter(size=3)
# 随机选取模糊参数
filter_ = random.choice(
[ImageFilter.SMOOTH,
ImageFilter.SMOOTH_MORE,
ImageFilter.GaussianBlur(radius=1.10)])
image = image.filter(filter_)
# image = img.resize((290,32))
return image
光强
#coding=utf-8
from PIL import Image
from PIL import ImageEnhance
#读取图像
image= Image.open('test.gif')
image.show()
#增强亮度
enh_bri = ImageEnhance.Brightness(image)
brightness = 1.5
image_brightened = enh_bri.enhance(brightness)
image_brightened.show()
image.save("Bri_test.gif") #保存
# 色度增强
enh_col = ImageEnhance.Color(image)
color = 1.5
image_colored = enh_col.enhance(color)
image_colored.show()
image.save("color_test.gif")
# 对比度增强
enh_con = ImageEnhance.Contrast(image)
contrast = 1.5
image_contrasted = enh_con.enhance(contrast)
image_contrasted.show()
image.save("contrast_test.gif")
# 锐度增强
enh_sha = ImageEnhance.Sharpness(image)
sharpness = 3.0
image_sharped = enh_sha.enhance(sharpness)
image_sharped.show()
image.save("sharpness_test.gif")
缩放
# 定义缩放resize函数
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# 初始化缩放比例,并获取图像尺寸
dim = None
(h, w) = image.shape[:2]
# 如果宽度和高度均为0,则返回原图
if width is None and height is None:
return image
# 宽度是0
if width is None:
# 则根据高度计算缩放比例
r = height / float(h)
dim = (int(w * r), height)
# 如果高度为0
else:
# 根据宽度计算缩放比例
r = width / float(w)
dim = (width, int(h * r))
# 缩放图像
resized = cv2.resize(image, dim, interpolation=inter)
# 返回缩放后的图像
return resized
总结
-
在一般情况下, cv2.INTER_NEAREST速度最快,但质量不高。如果资源非常有限,可以考虑使用。否则不选这个,尤其在上采样(增加)图像的大小时。
-
当增加(上采样)图像的大小时,可以考虑使用 cv2.INTER_LINEAR 和 cv2.INTER_CUBIC两种插值方法。 cv2.INTER_LINEAR 方法比 cv2.INTER_CUBIC 方法稍快,两个效果都不错。
-
当减小(下采样)的图像的大小,OpenCV的文档建议使用 cv2.INTER_AREA。PS.我感觉其实下采样各种方法都差不多,取速度最快的(cv2.INTER_NEAREST)就好。
拉伸
# 字体拉伸函数
def stretching_func():
pass
噪声
# 噪声函数
def random_noise_func():
pass
补边操作
img_patch = cv2.copyMakeBorder(img_standard, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=(255, 0, 0))#top bottom left right
opencv读取图片
opencv读取图片的格式为BGR,根据需要转化为RGB
img = cv2.imread(path)--->BGR
img = cv2.cvtColor(img,cv2.COLOR_BGR2RBG)#cv2.COLOR_RBG2BGR
灰度图
img = cv2.imread(path,0)
img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
锐化
def custom_blur_demo(image):
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) #锐化
dst = cv.filter2D(image, -1, kernel=kernel)
cv.imshow("custom_blur_demo", dst)