Created
June 4, 2020 16:25
-
-
Save alik604/473c1207954051f97dc332c9a065ce94 to your computer and use it in GitHub Desktop.
Image augmentation by mirroring, random rotation, shifts, shear and flips, etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @credit - kaggle.com/hanzh0420/image-augmentation-with-opencv | |
import os | |
print(os.listdir("../input")) | |
# Input data files are available in the "../input/" directory. | |
# Any results you write to the current directory are saved as output. | |
import numpy as np | |
#import pandas as pd # pd.read_csv | |
import cv2 | |
import random | |
class Data_augmentation: | |
def __init__(self, path, image_name): | |
''' | |
Import image | |
:param path: Path to the image | |
:param image_name: image name | |
''' | |
self.path = path | |
self.name = image_name | |
print(path+image_name) | |
self.image = cv2.imread(path+image_name) | |
def rotate(self, image, angle=90, scale=1.0): | |
''' | |
Rotate the image | |
:param image: image to be processed | |
:param angle: Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner). | |
:param scale: Isotropic scale factor. | |
''' | |
w = image.shape[1] | |
h = image.shape[0] | |
#rotate matrix | |
M = cv2.getRotationMatrix2D((w/2,h/2), angle, scale) | |
#rotate | |
image = cv2.warpAffine(image,M,(w,h)) | |
return image | |
def flip(self, image, vflip=False, hflip=False): | |
''' | |
Flip the image | |
:param image: image to be processed | |
:param vflip: whether to flip the image vertically | |
:param hflip: whether to flip the image horizontally | |
''' | |
if hflip or vflip: | |
if hflip and vflip: | |
c = -1 | |
else: | |
c = 0 if vflip else 1 | |
image = cv2.flip(image, flipCode=c) | |
return image | |
def image_augment(self, save_path): | |
''' | |
Create the new image with imge augmentation | |
:param path: the path to store the new image | |
''' | |
img = self.image.copy() | |
img_flip = self.flip(img, vflip=True, hflip=False) | |
img_rot = self.rotate(img) | |
img_gaussian = self.add_GaussianNoise(img) | |
name_int = self.name[:len(self.name)-4] | |
cv2.imwrite(save_path+'%s' %str(name_int)+'_vflip.jpg', img_flip) | |
cv2.imwrite(save_path+'%s' %str(name_int)+'_rot.jpg', img_rot) | |
cv2.imwrite(save_path+'%s' %str(name_int)+'_GaussianNoise.jpg', img_gaussian) | |
def main(file_dir,output_path): | |
for root, _, files in os.walk(file_dir): | |
print(root) | |
for file in files: | |
raw_image = Data_augmentation(root,file) | |
raw_image.image_augment(output_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment