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

數據增強中常用的方法有:鏡像(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

總結

  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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章