# Opencv常用數據增強方法:平移+旋轉+縮放+模糊+光強+拉伸

``````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
# .MedianFilter(size=3)
# 隨機選取模糊參數
filter_ = random.choice(
[ImageFilter.SMOOTH,
ImageFilter.SMOOTH_MORE,
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_ｔｅｓｔ.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
``````

1. 在一般情況下， cv2.INTER_NEAREST速度最快，但質量不高。如果資源非常有限，可以考慮使用。否則不選這個，尤其在上採樣（增加）圖像的大小時。

2. 當增加（上採樣）圖像的大小時，可以考慮使用 cv2.INTER_LINEAR 和 cv2.INTER_CUBIC兩種插值方法。 cv2.INTER_LINEAR 方法比 cv2.INTER_CUBIC 方法稍快，兩個效果都不錯。

3. 當減小（下采樣）的圖像的大小，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)
``````