Get 5 colors from random webcam pixels?

edited April 2014 in How To...

Hi, what I am trying to do is:

Get 5 colours, each one from a random pixel in webcam video. The problem is I don't want the webcam video to be visible in the sketch window. So essentially the very first thing the sketch will do when run is (but without showing cam.read):

      color a = get((int)random(width),(int)random(height));
      color b = get((int)random(width),(int)random(height));
      color c = get((int)random(width),(int)random(height));
      color d = get((int)random(width),(int)random(height));
      color e = get((int)random(width),(int)random(height));

So that I can then use the colours as the colour scheme of a sketch.

Thanks!

Tagged:

Answers

  • cam.read() doesn't write anything to screen — you have to use image(cam, x, y) to actually draw the output. However, it doesn't look like the camera is available to read during setup(), so you have to do it during the first frame. You can use a boolean to ensure it only happens once.

    import processing.video.*; 
    Capture cam; 
    color[] colors;
    boolean hasReadColors = false;
    
    void setup() { 
      size(200, 200); 
      cam = new Capture(this);
      cam.start(); 
      colors = new color[5];
    } 
    
    void draw() { 
    
      if (cam.available() && hasReadColors == false) { 
        cam.read(); 
        for (int i = 0; i< colors.length; i++) {
          colors[i] = cam.get((int)random(width), (int)random(height));
        }
        hasReadColors = true;
      } 
    
      float step = width/colors.length;
      for (int i = 0; i < colors.length; i ++) {
        fill(colors[i]);
        rect(step*i, 0, step, height);
      }
    } 
    
Sign In or Register to comment.