Skip to content

Instantly share code, notes, and snippets.

@InputBlackBoxOutput
Created August 6, 2021 04:23
Show Gist options
  • Save InputBlackBoxOutput/bf2bcca9f9a73ba59107d6fef8f74c47 to your computer and use it in GitHub Desktop.
Save InputBlackBoxOutput/bf2bcca9f9a73ba59107d6fef8f74c47 to your computer and use it in GitHub Desktop.
Image data augmentation using openCV
# Image Data augmentation
# Use this program to perform image data augmentation in case you do not want to use a generator for some reason
# Check out ImageDataGenerator if you are looking for a generator in TensorFlow: https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator
import cv2
import numpy as np
import glob
import hashlib
search_pattern = "images/*.jpg"
for each in glob.glob(search_pattern):
image = cv2.imread(each)
# --------------------------------------------------------------------------------
# Scaling using cubic interpolation
image = cv2.resize(image, None, fx=.75, fy=.75, interpolation = cv2.INTER_CUBIC)
# --------------------------------------------------------------------------------
# Flip
# Horizontal
image = cv2.flip(image, 1)
# Vertical
image = cv2.flip(image, 0)
# Both vertical and horizontal
image = cv2.flip(image, -1)
# --------------------------------------------------------------------------------
# Brightness
matrix = np.ones(image.shape, dtype = "uint8") * 120
# Increase
image = cv2.add(image, matrix)
# Decrease
image = cv2.subtract(image, matrix)
# --------------------------------------------------------------------------------
# Contrast
# Blurring
image = cv2.blur(image, (9,9))
# Sharpening
kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
image = cv2.filter2D(image, -1, kernel)
# --------------------------------------------------------------------------------
# Display the image and save the image in the same directory as this program
# cv2.imshow("Output", image)
# cv2.waitKey(0)
h = hashlib.sha1()
h.update(each.encode())
filename_hash = h.hexdigest()
cv2.imwrite(f"{filename_hash[:10]}.jpg", image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment