Module: OpenCVColor

Includes:
OpenCV
Defined in:
lib/opencv-color.rb,
lib/opencv-color/version.rb

Defined Under Namespace

Classes: Cluster, Colors

Constant Summary collapse

VERSION =
"1.0.3"

Class Method Summary collapse

Class Method Details

.cluster_colors(colors, max_distance = 20) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/opencv-color.rb', line 82

def cluster_colors(colors, max_distance=20)
  clusters = []
  colors.each do |cs|
    cs.each do |color|
      cluster = clusters.find do |cluster|
        cluster.distance(color) < max_distance
      end

      if cluster
        cluster << color
      else
        clusters << Cluster.new(color)
      end
    end
  end
  clusters
end

.color_name(path, i) ⇒ Object



118
119
120
# File 'lib/opencv-color.rb', line 118

def color_name(path, i)
  "#{File.basename(path).downcase.gsub(/[^a-z_]/, '_')}_#{i}"
end

.colors(img) ⇒ Object



127
128
129
# File 'lib/opencv-color.rb', line 127

def colors(img)
  Colors.new(img)
end

.learn(dir) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
# File 'lib/opencv-color.rb', line 106

def learn(dir)
  ret = samples(dir).inject({}) do |memo, cd|
    color_dir, files = cd
    colors = files.map(&method(:load_image_colors))
    cluster_colors(normalize_colors(colors)).each_with_index do |cluster, i|
      memo[color_name(color_dir, i)] = cluster.color_range
    end
    memo
  end
  Hash[ret]
end

.load_image_colors(file) ⇒ Object



122
123
124
125
# File 'lib/opencv-color.rb', line 122

def load_image_colors(file)
  img = IplImage.load(file, OpenCV::CV_LOAD_IMAGE_ANYCOLOR | OpenCV::CV_LOAD_IMAGE_ANYDEPTH)
  colors(img.BGR2HSV)
end

.normalize_colors(colors) ⇒ Object



75
76
77
78
79
80
# File 'lib/opencv-color.rb', line 75

def normalize_colors(colors)
  size = colors.map(&:size).min
  colors.map do |cs|
    cs.to_a.shuffle.first(size)
  end
end

.samples(dir) ⇒ Object



100
101
102
103
104
# File 'lib/opencv-color.rb', line 100

def samples(dir)
  Dir["#{dir}/*"].map do |color|
    [color, Dir["#{color}/*"]]
  end
end