読者です 読者をやめる 読者になる 読者になる

Daily Creative Coding

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

カメラから所得した映像をグリッチする

f:id:aa_debdeb:20160928171153j:plain
/**
* glitch camera
*
* @author aa_debdeb
* @date 2016/10/06
*/

import processing.video.*;

Capture camera;
int[][][] references;

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

void mousePressed(){
  makeReferences();
}

void makeReferences(){
  references = new int[width][height][2];
  for(int w = 0; w < camera.width; w++){
    for(int h = 0; h < camera.height; h++){
      references[w][h][0] = w;
      references[w][h][1] = h;
    }
  }
  int count = 0;
  int maxCount = int(random(10, 100));
  while(count < maxCount){
    int x1 = int(random(camera.width));
    int y1 = int(random(camera.height));
    int x2 = int(random(camera.width));
    int y2 = int(random(camera.height));
    int wSize = int(random(1, 100));
    int hSize = int(random(1, 100));
    if(random(1) < 0.5){
      x1 -= wSize;
      x2 -= wSize;
    }
    if(random(1) < 0.5){
      y1 -= hSize;
      y2 -= hSize;
    }
    if(!(isInCamera(x1, y1) && isInCamera(x2, y2))){
      continue;
    }
    for(int w = 0; w <= wSize; w++){
      for(int h = 0; h <= hSize; h++){
        int tempX = references[x1 + w][y1 + h][0];
        int tempY = references[x1 + w][y1 + h][1];
        references[x1 + w][y1 + h][0] = references[x2 + w][y2 + h][0];
        references[x1 + w][y1 + h][1] = references[x2 + w][y2 + h][1];
        references[x2 + w][y2 + h][0] = tempX;
        references[x2 + w][y2 + h][1] = tempY;   
      }
    }
    count++;
  }
}

boolean isInCamera(int x, int y){
  return 0 <= x && x < width && 0 <= y && y < height;
}

void draw(){
  camera.loadPixels();
  noStroke();
  background(255);
  for(int w = 0; w < camera.width; w++){
    for(int h = 0; h < camera.height; h++){
      color c = getPixel(references[w][h][0], references[w][h][1]);
      fill(c);
      rect(w * 2, h * 2, 2, 2);
    }
  }
}

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

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