Skip to content

Commit

Permalink
Merge pull request #4 from aditya9211/blur_clear_v2
Browse files Browse the repository at this point in the history
Blur clear v2
  • Loading branch information
aditya9211 authored Apr 8, 2018
2 parents 042b2b0 + 71631bf commit 4da6154
Show file tree
Hide file tree
Showing 6 changed files with 1,012 additions and 296 deletions.
89 changes: 73 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,89 @@
# Blur-and-Clear Images Classification
## Classifying the Blur and Clear Images

### Program to Classifying the Blur and the Clear Images by Using Supervised Learning by Neural Networks Model
### Program to Classifying the Blur and Clear Images Using Supervised Learning by Neural Networks Model

In day to day Life we encounter the poor images clicked from our Camera due to poor focus, motion of objects in frame
or handshaking motion while capturing the Images.

As a CS Student we wants to filter out the Clear and Blurred Images to delete the uneccessary Images.

`Blur is typically the thing which suppress the high frequency of our Images, therefore can be detected by using various low-pass filter
eg. Laplacaian Filter. `
eg. Laplacaian Filter.`

As a smart person(myself a CS guy) we doesn't want to manually filter out the Clear and Blurred Images,
so we need some smart way to delete the uneccessary Images.

I also applied the Laplacian of gausssian filter to detect the blur images, but it was difficult to find
exact value of threshold needed to seggregate; despite results were also not fascinating.

**Used variance LoG filter mentioned in https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/**

Some of its discussions

https://stackoverflow.com/questions/7765810/is-there-a-way-to-detect-if-an-image-is-blurry

https://stackoverflow.com/questions/5180327/detection-of-blur-in-images-video-sequences

LoG Ref:

http://academic.mu.edu/phys/matthysd/web226/Lab02.htm

http://aishack.in/tutorials/sift-scale-invariant-feature-transform-log-approximation/

Repo which implemented LoG filter in Python:
https://github.com/WillBrennan/BlurDetection2


As the Now the era of Deep Conv Nets has supressed the Standard Computer Vision Techniques,
Thus we are focussing on the root of it which is Neural Nets.
`
Neural Nets learn very Quickly the complex features , therefore can be used much easily then std. CV technique.
Tuning ANN efficiently can provide us the results much better than CV TEchnique.`
Thus I focussed on the root of it which is Neural Nets.

`Neural Nets learn very Quickly the complex features, therefore can be used much easily then std. CV technique.
Tuning ANN efficiently can provide me the results much better than CV TEchnique.`


## Here the Dependencies Required for Running the Code:
1. Python 2.7xx
2. Numpy, scipy, sklearn, matplotlib Library Installed
1. Python 2.7xx or 3.5xx
2. use `pip install -r requirements.txt'` to fulfill the dependencies


Code are segmented as follows:

1. Training Part :
   **train.py**

__train.py__

`which train the neural network with given images
and stores the trained parameters and splitted train, test set to disk `

2. Testing Part :
   __test.py__

`Our Model has 3 Layers`
__test.py__

`test the neural network with test data
stored by train.py `

3. Predict Part :

__predict.py__

`predict the label of images(Good/Bad)
provided by argument while calling`

4. Config File :

__config.py__

`contains list of constanst used by files
or hyper-parameters which can be changed
by editing this file`

5. Utiltities Part :

__utils.py__

`helper functions or common function among used in train, test and predict`


`Model has 3 Layers`
`Containing`
```
1 Input Layer -> 100*100 U
Expand All @@ -40,7 +93,7 @@ Code are segmented as follows:
1 Output Layer -> 2 U
```

**We have used the Backprop Algorithm for Training using the SGD Optimizer with Momentum .
**I have used the Backprop Algorithm for Training ANN using the SGD Optimizer with Momentum.
Rescaled the Images to 100 x 100 Pixels in Grayscale Coding and done median filtering to filter out the noise from Images.**

`Need the Images that are clear in separate folder and one with blurred in other folder.
Expand All @@ -53,9 +106,13 @@ Rescaled the Images to 100 x 100 Pixels in Grayscale Coding and done median filt

`python train.py --good_path '/home/......' --bad_path '/home/.......'`

`and result get stored default in 'tmp/blur_clear/' Folder.`
`and result get stored default in 'MODEL_PATH' configures in config.py file.`


`python test.py`

`to test the results.`
`to test the results and gives the accuracy score`

`python predict.py --img '/home/...../..jpg'`

`to predict the labels of given images`
59 changes: 59 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
This file contains constants required in the training
and testing stage of data processing also for training
Neural Networks Model
"""
# -*- coding: utf-8 -*-
import os

# Stores current exceuting path
HOME_FOLDER_PATH = os.getcwd()

# if not passes default model path
MODEL_PATH = HOME_FOLDER_PATH + '/model/result.pkl'
DATA_PATH = HOME_FOLDER_PATH + '/data'

# Path where splitted data get stored
TRAIN_DATA_PATH = DATA_PATH + '/train_images.npy'
TRAIN_LABEL_PATH = DATA_PATH + '/train_labels.npy'
TEST_DATA_PATH = DATA_PATH + '/test_images.npy'
TEST_LABEL_PATH = DATA_PATH + '/test_labels.npy'

# Path for saving plot of cost vs iterations
PLOT_PATH = DATA_PATH + '/loss_decay.png'


# Median Filter size
RADIUS = 3

# width and height of resized image
WIDTH = 100
HEIGHT = 100

# Splitting ratio for training & testing
SPLIT_RATIO = 0.2

# Seed to get same results on re-run
SEED = 10

# Size of data to be fed at each epochs
BATCH_SIZE = 10

# Hidden Layer neurons size
NEURONS_SIZE = 300

# Iteration in NN Model
MAX_ITER = 50

# Logging steps to show summary
LOGGING_STEPS = min(1, MAX_ITER)

# Learning rate in NN Model
ALPHA = 0.001

# Regularization Term used in cost
LAMBDA = 0.0007

# Default Activation Function
ACT = 'sig'
91 changes: 91 additions & 0 deletions predict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
"""
Script for predicting label as
good or bad given the image
It preprocess the image same as it
was pre-processed in training
"""
import argparse
from sklearn.externals import joblib
import numpy as np
import scipy.misc as ms
import scipy.ndimage as nd
from utils import (resize, validate, path_validation)
from config import (MODEL_PATH, WIDTH, HEIGHT,
RADIUS)

def predict_preprocess(IMAGE_PATH):
"""
Preprocess the image given path of the image/images
to apply median filter and resizing the image
same as done in training the network
@ Parameters:
-------------
IMAGE_PATH: str
Path of the images
@ Returns:
----------
img: np.array
filtered and pre-processed combined
images arrays
"""
# Reading images in grayscale mode
img = ms.imread(IMAGE_PATH, mode='L')
# APllying median filter to remove noise
img = nd.median_filter(img, RADIUS)
# To make it 2D
img = img[np.newaxis, :]
# Resizing the images to that of train
img = resize(img, width=WIDTH, height=HEIGHT)
# Addition of bias term
img = np.insert(img, 0, 1, axis=1)

return img


def main():
"""
Parse the argument and check validaton
of passed image and trained model path
Predict the label of images passed after
pre-process the images same as done in
training part
"""
# Construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-img", "--image_path", required=True,
help="path to image")
args = vars(ap.parse_args())

IMAGE_PATH = args["image_path"]

# Path Validation of image and Model
if not path_validation(IMAGE_PATH, read_access=True):
exit(0)
if not path_validation(MODEL_PATH, read_access=True):
exit(0)

# Preprocessed the images
img = predict_preprocess(IMAGE_PATH)

# Load the trained NN model
params = joblib.load(MODEL_PATH)

# Find the label predicted by the model
predicted_label = validate(params, img)

for label in predicted_label:
if label:
print("Good Image\n")
else:
print("Bad Image\n")


if __name__ == "__main__":
main()


Loading

0 comments on commit 4da6154

Please sign in to comment.