Frido
Frido

Reputation: 52

how to find the pca of an image using python and opencv?

I am developing an image classifier using svm.In the feature extraction phase can i use pca as feature.How to find the pca of an image using python and opencv.what my plan is

  1. Find pca of each image in training set and store it in a array.It may be list of lists
  2. Store class labels in another list
  3. pass this as argument to svm

Am i going in right Direction.Please help me

Upvotes: 1

Views: 2231

Answers (1)

triiiiista
triiiiista

Reputation: 378

Yes you can do PCA+SVM, some might argue that PCA is not the best feature to use or SVM is not the best classification algorithm. But hey, have a good start is better than sitting around.

To do PCA with OpenCV, try something like (I haven't verified the codes, just to get you an idea):

import os
import cv2 
import numpy as np

# Construct the input matrix
in_matrix = None 
for f in os.listdir('dirpath'):
    # Read the image in as a gray level image. Some modifications 
    # of the codes are needed if you want to read it in as a color 
    # image. For simplicity, let's use gray level images for now.
    im = cv2.imread(os.path.join('dirpath', f), cv2.IMREAD_GRAYSCALE)

    # Assume your images are all the same size, width w, and height h. 
    # If not, let's resize them to w * h first with cv2.resize(..)
    vec = im.reshape(w * h)

    # stack them up to form the matrix
    try:
        in_matrix = np.vstack((in_matrix, vec))
    except:
        in_matrix = vec

# PCA 
if in_matrix is not None:
    mean, eigenvectors = cv2.PCACompute(in_matrix, np.mean(in_matrix, axis=0).reshape(1,-1))       

Upvotes: 2

Related Questions