天天看點

對圖像進行随機翻轉和裁剪

opencv: cv2.flip 進行圖像翻轉,資料增強

cv2.flip(image, axis)

axis Anno
1 水準翻轉
垂直翻轉
-1 水準垂直翻轉
import numpy as np
import cv2

def horizontal_flip(image, axis):
    #axis 0 垂直翻轉,1水準翻轉 ,-1水準垂直翻轉,2不翻轉,各自以25%的可能性
    if axis != 2:
        image = cv2.flip(image, axis)
    return image
    
def random_flip(batch_data):
    #幫助随機翻轉一批圖像
    flip_batch = np.zeros(len(batch_data) * 224* 224 * 3).reshape(len(batch_data), 224, 224, 3)
    for i in range(len(batch_data)):
        axis1 = np.random.randint(low=-1, high=3)
        flip_batch[i, ...] = horizontal_flip(image=batch_data[i, ...], axis=axis1)
    return flip_batch
           

代碼中對一個batch中的圖檔進行一定機率的翻轉,25%不翻轉,25%垂直翻轉,25%水準翻轉,25%水準垂直翻轉。

進行圖像随機裁剪

import numpy as np
import cv2

def horizontal_flip(image, axis):
    #以50%的可能性翻轉圖檔,axis 0 垂直翻轉,1水準翻轉
    flip_prop = np.random.randint(low=0, high=2)
    if flip_prop ==0:
        image = cv2.flip(image, axis)
    
    return image
    
def random_crop_and_flip(batch_data, padding_size):
    #幫助随機裁剪和随機翻轉一批圖像
    cropped_batch = np.zeros(len(batch_data) * IMG_HEIGHT * IMG_WIDTH * IMG_DEPTH).reshape(
                 len(batch_data), IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH)
    
    for i in range(len(batch_data)):
        x_offset = np.random.randint(low=0, height=2*padding_size, size=1)[0]
        y_offset = np.random.randint(low=0, height=2 * padding_size, size=1)[0]
        cropped_batch[i, ...] = batch_data[i, ...][x_offset:x_offset+IMG_HEIGHT,
                        y_offset:y_offset+IMG_WIDTH, :]
        cropped_batch[i, ...] = horizontal_flip(image=cropped_batch[i, ...], axis=1)
        
    return cropped_batch
           

代碼中對一個batch中的圖檔進行随機裁剪以及一定機率的翻轉,50%不翻轉,50%進行垂直翻轉或者水準翻轉。