Created
June 3, 2018 10:20
-
-
Save chih-chun-chang/69ce48c5f2cd9fd3cfc470041596e04a to your computer and use it in GitHub Desktop.
PCA (Data Augmentation) with Scikit-Image
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
import numpy as np | |
from skimage import io, transform | |
# Using one image | |
image_filenames = 'image.jpg' | |
# Read the image | |
image = io.imread(images_filenames) | |
# Resize image (256 x 256 x 3) and turn the image matrix of m x n x 3 to lists of rgb | |
images_resized = transform.resize(image, (256, 256, 3)) | |
# Center the image data and then find the covariance | |
image_reshaped = images_resized.reshape(-1,3) # (256*256, 3) | |
image_centered = image_reshaped - image_reshaped.mean(axis=0) | |
# Find 3 x 3 covariance martix | |
image_cov = np.cov(image_centered, rowvar=False) | |
# Get eigen values and eigen vectors | |
eigen_vals, eigen_vecs = np.linalg.eigh(img_cov) | |
# Get principal components[p1, p2, p3] | |
sort = eigen_vals[::-1].argsort() | |
eigen_vals[::-1].sort() | |
eigem_vecs = eigen_vecs[:, sort] | |
pc = np.column_stack((eigen_vecs)) | |
# 3x1 matrix of eigen values multipled by a random variable drawn from Gaussian(0, 0.1) | |
m = np.zeros((3,1)) | |
for i in range(eigen_vals.shape[0]): | |
m[i][0] = np.random.normal(0, 0.1)*eigen_vals[i] | |
# Add value[p1, p2, p3][α1λ1, α2λ2, α3λ3]T | |
add_v = np.matrix(pc)*np.matrix(m) | |
# Scale the image | |
image_scaled = image/255.0 | |
# Adding the value to create a augmented image | |
for i in range(image_scaled.shape[0]): | |
for j in range(image_scaled.shape[1]): | |
for k in range(image_scaled.shape[2]): | |
image_scaled[i, j, k] = min(abs(float(image_scaled[i, j, k]) + float(add_v[k])), 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment