Daily Creative Coding

元「30 min. Processing」。毎日、Creative Codingします。

カメラから取得した映像を二値化してから横線に変換する

f:id:aa_debdeb:20160928170405j:plain
/**
* camera of horizontal line
*
* @author aa_debdeb
* @date 2016/10/05
*/

import processing.video.*;

Capture camera;

void setup(){
  size(640, 480);
  camera = new Capture(this, 320, 240);
  camera.start();
}

void draw(){
  camera.loadPixels();
  noStroke();
  background(255);
  float[][] grey = new float[320][240];
  for(int x = 0; x < camera.width; x++){
    for(int y = 0; y < camera.height; y++){
      color c = getPixel(x, y);
      grey[x][y] = 0.30 * red(c) + 0.59 * green(c) + 0.11 * blue(c);
    }
  }
  
  background(0);
  float threshold = map(mouseX, 0, width, 0, 255);
  for(int y = 0; y < camera.height; y++){
    int state = 0;
    int startX = 0;
    int endX = 0;
    for(int x = 0; x < camera.width; x++){
      if(state == 0 && grey[x][y] >= threshold){
        startX = x;
        state = 1;
      } else if(state == 1 && (x == camera.width - 1 || grey[x][y] < threshold)){
        endX = x;
        PVector col = new PVector(0, 0, 0);
        for(int xx = startX; xx <= endX; xx++){
          color c = getPixel(xx, y);
          col.x += red(c);
          col.y += green(c);
          col.z += blue(c);
        }
        col.div(endX - startX + 1);
        stroke(col.x, col.y, col.z);
        line(startX * 2, y * 2, endX * 2, y * 2);
        state = 0;
      }

    }
  }
}

color getPixel(int x, int y){
  return camera.pixels[y * camera.width + x];
}

void captureEvent(Capture camera){
  camera.read();
}