python + opencv study -> class making, opencv and numpy simple usages,

I made simple image subtraction class by python + opencv.
More detail, the class evaluate whether two image is same or diffrent by 2 threshold.
first threshold is the britness different of pixel.
second threshold is percent of change. eg. count(changed pixel) / area(width*height)

This class can be applied detection of motion in continues image.

And you can study how to run opencv in the python.
I am also bigginer of python use.

I studied a part of relation numpy and opencv.

__author__ = 'mare'

import numpy as np
import cv2

class ImgSubtraction:
    #image load
    def __init__(self, r_img, th1, th2):
        self.RImg = r_img
        self.Th1, self.Th2 = th1, th2
        self.cols, self.rows = r_img.shape[:2]
        self.area = self.cols * self.rows

    #image subtraction
    def eval_subtraction(self, c_img):

        #return false if c_img size is different with RImg
        if self.RImg.shape[:2] != c_img.shape[:2]:
            return 0

        ic_img = c_img
        is_img = np.subtract(self.RImg, np.int_(ic_img))
        ia_img = np.abs(is_img)
        #count pixels difference over than th1
        dcount = np.sum(ia_img > self.Th1)
        #image change percent
        dpersent = (dcount/np.float32(self.area) ) * 100

        if dpersent >= self.Th2:
            return 1
            return 0


__author__ = 'mare'

import cv2
from class_ImgSubtraction import ImgSubtraction

RImg = cv2.imread('test.png', 0)
CImg = cv2.imread('test2.png', 0)

e1 = cv2.getTickCount()

cImgSub = ImgSubtraction(RImg, 10, 1)

if cImgSub.eval_subtraction(CImg):
    print ('image different')

e2 = cv2.getTickCount()
time = (e2 - e1)/cv2.getTickFrequency()
print(time, 1/time)



you can also download the source code on the github
-> https://gist.github.com/mare90/2ea9b9ca7c80c8c259e1

No comments:

Post a Comment