OpenCV图像数据增强代码解析与实战【飞桨】【图像分类】【PaddlePaddle】
欢迎报名:
飞桨领航团图像分类零基础训练营
常用图像增广方法主要有:左右翻转(上下翻转对于许多目标并不常用),随机裁剪,变换颜色(亮度,对比度,饱和度和色调)等等,我们拟用opencv-python实现部分数据增强方法。
结构如下:
class FunctionClass:
def __init__(self, parameter):
self.parameter=parameter
def __call__(self, img):
import cv2
import numpy as np
import random
from matplotlib import pyplot as plt
%matplotlib inline
filename = 'lena.jpg'
## [Load an image from a file]
img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
<matplotlib.image.AxesImage at 0x7fc780124ed0>
print(img.shape)
(350, 350, 3)
1.图片缩放
interpolation 选项 | 所用的插值方法 |
---|---|
INTER_NEAREST | 最近邻插值 |
INTER_LINEAR | 双线性插值(默认设置) |
INTER_AREA | 使用像素区域关系进行重采样。 它可能是图像抽取的首选方法,因为它会产生无云纹理的结果。 但是当图像缩放时,它类似于INTER_NEAREST方法。 |
INTER_CUBIC | 4x4像素邻域的双三次插值 |
INTER_LANCZOS4 | 8x8像素邻域的Lanczos插值 |
class Resize:
def __init__(self, size):
if size is not None:
self.w = size if type(size) is int else size[0]
self.h = size if type(size) is int else size[1]
else:
raise OperatorParamError("invalid params for ReisizeImage for 'size' is None")
def __call__(self, img):
# TODO
return cv2.resize(img, (self.w, self.h), interpolation=cv2.INTER_LINEAR)
resize1 = Resize(600)
img2 = resize1(img)
plt.imshow(img2)
print(img2.shape)
(600, 600, 3)
resize2 = Resize((600, 700))
img3 = resize2(img)
plt.imshow(img3)
print(img3.shape)
(700, 600, 3)
2.图片翻转
class Flip:
"""
random flip image 随机翻转图片
mode:
1: Flipped Horizontally 水平翻转
0: Flipped Vertically 上下翻转
-1: Flipped Horizontally & Vertically 水平、上下翻转
"""
def __init__(self, mode=1):
# 设置一个翻转参数,1、0或-1
assert mode in <