OpenCV and Processing 18

In addition to the Hough circle detection, this example works on the Hough line segment detection. It inputs the live webcam image; converts it into greyscale; applies a medianBlur filter; processes the Canny edge detection. The Imgproc.HoughLinesP() function will finally single out the line segments into a Mat – lines in our example codes.


import processing.video.*;
 
import org.opencv.video.Video;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
 
Capture cap;
CVImage img;
 
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();
}
 
void draw() {
  img.copy(cap, 0, 0, cap.width, cap.height, 0, 0, img.width, img.height);
  img.toCV();
 
  Mat grey = img.getGrey();
  Mat dst = new Mat(grey.size(), grey.type());
  Imgproc.medianBlur(grey, dst, 3);
  Imgproc.Canny(dst, dst, 50, 200, 3, false);
  Mat lines = new Mat();
  Imgproc.HoughLinesP(dst, lines, 1, PI/180.0, 50, 10, 10);
  background(0);
  //  image(img, 0, 0);
 
  if (lines.cols()>0) {
    noFill();
    for (int i=0; i<lines.rows(); i++) {
      double [] v = lines.get(i, 0);
      float x1 = (float) v[0];
      float y1 = (float) v[1];
      float x2 = (float) v[2];
      float y2 = (float) v[3];
      int mx = constrain(round((x1 + x2)/2.0), 0, cap.width-1);
      int my = constrain(round((y1 + y2)/2.0), 0, cap.height-1);
      color col = cap.pixels[my*cap.width+mx];
      stroke(col);
      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();
  dst.release();
  lines.release();
}
 
void captureEvent(Capture _c) {
  _c.read();
}