image_moments.py 2.15 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
    Calculate raw, central and Hu's set of image moments.
    
7 8
    M. K. Hu, “Visual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962
    
9 10 11 12 13 14 15 16 17
    Name: image_moments.py
    Author: Alessandro dos Santos Ferreira ( santosferreira.alessandro@gmail.com )
"""
from skimage import measure

from util.utils import ImageUtils

from extractor import Extractor

18
class RawCentralMoments(Extractor):
19 20

    
21 22
    def __init__(self):
        self._moments_order = [(0, 1), (1, 0), (1, 1), (0, 2), (2, 0)]        
23
        
24 25
    
    def run(self, image):
26
        
27
        image_binary = ImageUtils.image_binary(image, bgr = True)
28
        
29
        m = measure.moments(image_binary)
30 31 32
        
        values_m = [m[p, q] for (p, q) in self._moments_order]
        labels_m = [M+str(p)+str(q) for M,(p,q) in zip(['M_'] * len(self._moments_order), self._moments_order)]
33
        
34 35 36
        row = m[0, 1] / m[0, 0]
        col = m[1, 0] / m[0, 0]

37
        mu = measure.moments_central(image_binary, row, col)
38 39 40 41
        
        values_mu = [mu[p, q] for (p, q) in self._moments_order]
        labels_mu = [M+str(p)+str(q) for M,(p,q) in zip(['Mu_'] * len(self._moments_order), self._moments_order)]
        
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
        labels = labels_m + labels_mu
        types = [Extractor.NUMERIC] * len(labels)
        values = values_m + values_mu
        
        return labels, types, values


class HuMoments(Extractor):

    
    def __init__(self):
        pass
        
    
    def run(self, image):
        
58
        image_binary = ImageUtils.image_binary(image, bgr = True)
59
        
60
        m = measure.moments(image_binary)
61 62 63 64
        
        row = m[0, 1] / m[0, 0]
        col = m[1, 0] / m[0, 0]

65
        mu = measure.moments_central(image_binary, row, col)
66
        
67 68 69 70
        nu = measure.moments_normalized(mu)
        hu = measure.moments_hu(nu)

        values_hu = list(hu)
71
        labels_hu = [m+n for m,n in zip(['Hu_'] * len(values_hu),map(str,range(0,len(values_hu))))]
72
        
73
        labels = labels_hu
74
        types = [Extractor.NUMERIC] * len(labels)
75
        values = values_hu
76
        
77 78
        return labels, types, values