先导入图片。
import cv2
import numpy as np
from matplotlib import pyplot as plt
filename = '10.png'
## [Load an image from a file]
img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
print(img.shape)#查看图片大小
打印如下
1.图片缩放
用函数cv2.resize(img,size)就可以实现,img是输入的图片,size是缩放大小,如缩放为1000x1000就是(1000,1000)
class Resize:
def __init__(self, size):
self.size=size
def __call__(self, img):
img = cv2.resize(img,self.size)
return img
resize=Resize( (1000, 1000))
img2=resize(img)
plt.imshow(img2)
print(img2.shape)
打印如下
2.图片翻转
用函数cv2.flip(img,flag)可以实现。其中,参数flag = 0:垂直翻转(沿x轴),参数flag > 0: 水平翻转(沿y轴),参数flag < 0: 水平垂直翻转。
class Flip:
def __init__(self, mode):
self.mode=mode
def __call__(self, img):
img = cv2.flip(img,self.mode)
return img
flip=Flip(mode=0)
img2=flip(img)
plt.imshow(img2)
打印如下
3图片旋转
先看代码
class Rotate:
def __init__(self, degree,size):
self.degree=degree
self.size=size
def __call__(self, img):
rows, cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), self.degree, self.size)
img = cv2.warpAffine(img, M, (cols, rows))
return img
rotate=Rotate( 45, 0.7)
img2=rotate(img)
plt.imshow(img2)
打印如下
代码里要实现的是把图片旋转45度,缩放比例是0.5。
opencv里没有直接把图片旋转任意角度的函数,所以这里要用仿射变换实现。
opencv里用cv2.getRotationMatrix2D((x, y), degree, size)这个函数构造旋转矩阵,其中(x,y)是图像中心点的坐标,degree为旋转角度(正:逆时针,负:顺时针),size为缩放比例。构造出旋转矩阵M后,就可以进行仿射变换了,用函数cv2.warpAffine(img,M,(图片宽度,图片高度))。
4.图片亮度调节
class Brightness:
def __init__(self,brightness_factor):
self.brightness_factor=brightness_factor
def __call__(self, img):
img = np.uint8(np.clip((self.brightness_factor*img), 0, 255))
return img
brightness=Brightness(0.5)
img2=brightness(img)
plt.imshow(img2)
打印如下
代码实现借用了函数np.clip(a, a_min, a_max),a为一个数组,函数将将数组中的元素限制在a_min, a_max之间。
5.图片随机裁剪
import cv2
import numpy as np
from matplotlib import pyplot as plt
import random
import math
class RandomErasing(object):
def __init__(self, EPSILON=0.5, sl=0.02, sh=0.4, r1=0.3,
mean=[0., 0., 0.]):
self.EPSILON = EPSILON
self.mean = mean
self.sl = sl
self.sh = sh
self.r1 = r1
def __call__(self, img):
if random.uniform(0, 1) > self.EPSILON:
return img
#for attempt in range(100):
area = img.shape[0] * img.shape[1]
target_area = random.uniform(self.sl, self.sh) * area
aspect_ratio = random.uniform(self.r1, 1 / self.r1)
h = int(round(math.sqrt(target_area * aspect_ratio)))
w = int(round(math.sqrt(target_area / aspect_ratio)))
x = random.uniform(0,img.shape[1])
y = random.uniform(0,img.shape[0])
img = cv2.rectangle(img, (int(x),int(y)), (int(x)+int(w), int(y)+int(h)), (0, 0, 0),-1)
return img
erase = RandomErasing()
img2=erase(img)
plt.imshow(img2)
主要是用函数cv2.rectangle()这个函数,在原图上画一个黑色的长方形,就相当于擦除了原图像的一部分。
打印如下