OpenCV and Processing 19

Similar to the last Hough Line detection, the following example illustrates the use of the new LineSegmentDetector class in the Imgproc module. Instead of using the new command, we have to use the Imgproc.createLineSegmentDetector() function to create a new instance of the class.
 



The detect() function will return an Mat that contains all information of the line segments. I use a MatOfFloat4 data structure to extract the details. Each part is essentially the 2 endpoints of the line segment.

Source codes of the example

import processing.video.*;
 
import org.opencv.video.Video;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat4;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgproc.LineSegmentDetector;
 
Capture cap;
CVImage img;
LineSegmentDetector line;
 
void setup() {
  size(640, 480, P3D);
  background(0);
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  cap = new Capture(this, width, height);
  cap.start();
  cap.read();
  img = new CVImage(width, height);
  smooth();
  line = Imgproc.createLineSegmentDetector();
}
 
void draw() {
  img.copy(cap, 0, 0, cap.width, cap.height, 0, 0, img.width, img.height);
  img.toCV();
  background(0);
  //  image(img, 0, 0);
  Mat grey = img.getGrey();
  MatOfFloat4 lines = new MatOfFloat4();
  line.detect(grey, lines);
 
  if (lines.rows()>0 && lines.cols()>0) {
    float [] f = lines.toArray();
    int cnt = f.length/4;
 
    for (int i=0; i<cnt; i++) {
      int x1 = round(f[i*4]);
      int y1 = round(f[i*4+1]);
      int x2 = round(f[i*4+2]);
      int y2 = round(f[i*4+3]);
      int mx = constrain((x1 + x2)/2, 0, img.width-1);
      int my = constrain((y1 + y2)/2, 0, img.height-1);
      color col = img.pixels[my*img.width+mx];
      stroke(col);
      strokeWeight(random(5));
      line(x1, y1, x2, y2);
    }
  }
 
  fill(0);
  noStroke();
  rect(0, 0, 110, 30);
  fill(255);
  text("Frame rate: " + nf(round(frameRate), 2), 10, 20, 0);
  grey.release();
  lines.release();
}
 
void captureEvent(Capture _c) {
  _c.read();
}