opencv利用opencv对数据图像实现数据增强
# -*- coding: utf-8 -*-
"""
# 数据增强实现
"""
import cv2
import numpy as np
# 图像平移
def img_translation(image):
# 图像平移 下、上、右、左平移
M = np.float32([[1, 0, 0], [0, 1, 100]])
img_down = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, 0], [0, 1, -100]])
img_up = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, 100], [0, 1, 0]])
img_right = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, -100], [0, 1, 0]])
img_left = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
# 显示图形
cv2.imshow("down", img_down)
cv2.imshow("up", img_up)
cv2.imshow("right", img_right)
cv2.imshow("left", img_left)
# 图像缩放
def img_scale(image):
result = cv2.resize(image, (200, 100))
cv2.imshow("scale", result)
# 图像翻转
def img_flip(image):
# 0以X轴为对称轴翻转,>0以Y轴为对称轴翻转, <0X轴Y轴翻转
horizontally = cv2.flip(image, 0) # 水平镜像
vertically = cv2.flip(image, 1) # 垂直镜像
hv = cv2.flip(image, -1) # 水平垂直镜像
# 显示图形
cv2.imshow("Horizontally", horizontally)
cv2.imshow("Vertically", vertically)
cv2.imshow("Horizontally & Vertically", hv)
# 图像旋转
def img_rotation(image):
# 原图的高、宽 以及通道数
rows, cols, channel = image.shape
# 绕图像的中心旋转
# 参数:旋转中心 旋转度数 scale
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 1)
# 参数:原始图像 旋转参数 元素图像宽高
rotated = cv2.warpAffine(image, M, (cols, rows))
# 显示图像
cv2.imshow("rotated", rotated)
# 图像加噪
def img_noise(image, mean=0, var=0.001):
'''
添加高斯噪声
mean : 均值
var : 方差
'''
image = np.array(image / 255, dtype=float)
noise = np.random.normal(mean, var ** 0.5, image.shape)
out = image + noise
if out.min() < 0:
low_clip = -1.
else:
low_clip = 0.
out = np.clip(out, low_clip, 1.0)
out = np.uint8(out * 255)
cv2.imshow("noise", out)
# 图像亮度调节
def img_brightness(image):
contrast = 1 # 对比度
brightness = 100 # 亮度
pic_turn = cv2.addWeighted(image, contrast, image, 0, brightness)
# cv2.addWeighted(对象,对比度,对象,对比度)
'''cv2.addWeighted()实现的是图像透明度的改变与图像的叠加'''
cv2.imshow('bright', pic_turn) # 显示图片
if __name__ == '__main__':
# src = cv2.imread('./images/jie1.jpg')
src = cv2.imread('./images/luowen.jpg')
src = cv2.imread('./green_dog.jpg')
img_translation(src)
img_scale(src)
img_flip(src)
img_rotation(src)
img_noise(src)
img_brightness(src)
cv2.waitKey(0)
cv2.destroyAllWindows()
显示效果如下所示:
|