image_moments.py 2.03 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
    Calculate raw, central and Hu's set of image moments.
    
    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

16
class RawCentralMoments(Extractor):
17 18

    
19 20
    def __init__(self):
        self._moments_order = [(0, 1), (1, 0), (1, 1), (0, 2), (2, 0)]        
21
        
22 23
    
    def run(self, image):
24
        
25
        image_binary = ImageUtils.image_binary(image, bgr = True)
26
        
27
        m = measure.moments(image_binary)
28 29 30
        
        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)]
31
        
32 33 34
        row = m[0, 1] / m[0, 0]
        col = m[1, 0] / m[0, 0]

35
        mu = measure.moments_central(image_binary, row, col)
36 37 38 39
        
        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)]
        
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        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):
        
56
        image_binary = ImageUtils.image_binary(image, bgr = True)
57
        
58
        m = measure.moments(image_binary)
59 60 61 62
        
        row = m[0, 1] / m[0, 0]
        col = m[1, 0] / m[0, 0]

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

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