Segment Robots - MarvinJ

by Gabriel Ambrósio Archanjo

HTML

by <a href="https://www.marvinj.org">www.marvinj.org</a></br>
<script src="https://www.marvinj.org/releases/marvinj-0.9.js"></script>
<canvas id="canvas" width="600" height="440"></canvas>

CSS

body{font-size:12px;}

JavaScript

var canvas = document.getElementById("canvas");
image = new MarvinImage();
image.load("https://i.imgur.com/soi3nmT.jpg", imageLoaded);


function imageLoaded() {

  var width = image.getWidth();
  var factor = width / 80;

  var original = image.clone();
  Marvin.scale(image.clone(), image, 80);

  // 2. Change green pixels to white
  filterGreen(image);

  // 3. Use threshold to separate foreground and background.
  var bin = MarvinColorModelConverter.rgbToBinary(image, 145);

  // 4. Morphological closing to group separated parts of the same object
  Marvin.morphologicalClosing(bin.clone(), bin, MarvinMath.getTrueMatrix(6, 6));

  // 5. Use Floodfill segmention to get image segments
  image = MarvinColorModelConverter.binaryToRgb(bin);
  var segments = Marvin.floodfillSegmentation(image);

  // 6. Show the segments in the original image
  for (var i = 1; i < segments.length; i++) {
    var seg = segments[i];
    
   original.drawRect(Math.floor(seg.x1 * factor), Math.floor(seg.y1 * factor), Math.floor(seg.width * factor), Math.floor(seg.height * factor), 0xFFFFFF00);
    original.drawRect(Math.floor(seg.x1 * factor) + 1, Math.floor(seg.y1 * factor) + 1, Math.floor(seg.width * factor) - 2, Math.floor(seg.height * factor) - 2, 0xFFFFFF00);
  }

  original.draw(canvas);
}

function filterGreen(image) {
  var r, g, b;
  for (var y = 0; y < image.getHeight(); y++) {
    for (var x = 0; x < image.getWidth(); x++) {
      r = image.getIntComponent0(x, y);
      g = image.getIntComponent1(x, y);
      b = image.getIntComponent2(x, y);
      if (g > r * 1.5 && g > b * 1.5) {
        image.setIntColor(x, y, 255, 255, 255);
      }
    }
  }
}