Method: SPCore::Statistics.correlation
- Defined in:
- lib/spcore/analysis/statistics.rb
.correlation(image, feature, zero_padding = 0) ⇒ Object
Determines the normalized cross-correlation of a feature with an image.
Normalization is from -1 to 1, where 1 is high correlation, -1 is high correlation (of inverse), and 0 is no correlation.
For autocorrelation, just cross-correlate a signal with itself.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/spcore/analysis/statistics.rb', line 35 def self.correlation image, feature, zero_padding = 0 raise ArgumentError, "feature size is > image size" if feature.size > image.size unless zero_padding == 0 image = Array.new(zero_padding, 0) + image + Array.new(zero_padding, 0) end feature_mean = feature.inject(0){ |s, x| s + x } / feature.size.to_f feature_diff = feature.map {|x| x - feature_mean } sx = feature_diff.inject(0){ |s, x| s + x**2 } data = [] for i in 0...(1 + image.size - feature.size) region = image[i...(i + feature.size)] region_mean = region.inject(0){|s,x| s + x } / feature.size.to_f region_diff = region.map {|x| x - region_mean } sy = region_diff.inject(0){ |s, x| s + x**2 } if sx == 0 || sy == 0 if sx == 0 && sy == 0 data.push 1.0 else data.push 0.0 end next end denom = Math.sqrt(sx*sy) sum = 0 feature.size.times do |j| sum += (region_diff[j] * feature_diff[j]) end r = sum / denom data.push(r) end return data end |