Less CPU intensive way to scan pixels

edited July 27 in Library Questions

Hi -

I am scanning an image line by line and outputting the greyscale of each pixel to Pure Data via OSC, all of it is working ok but it seems super intensive for the computer, the fans are on full speed and sometimes Processing crashes a few minutes in.

Is there anything I can do to make this code less intensive? Might be missing something obvious?

It could be because of the frameRate, and if so are there any suggestions of other ways of doing this? So that I can still run the scanning pretty fast

Thanks in advance for any help

import oscP5.*;
import netP5.*;

NetAddress remote;
OscP5 oscP5;
//int incomingOSCData;
// int sendTestData;
// String msgType;

PImage img;
int x, y, s, r;

void setup() {
  size(500, 500);
  oscP5 = new OscP5(this,12000);
  remote = new NetAddress("127.0.0.1",3000);
  s = 10;
  stroke(255);
  reset();
  frameRate(200);
  img = loadImage("10.jpg");
  background(0);
  img.loadPixels();
}

void reset(){
  background(0);
  x = 0;
  y = 0;
  OscMessage msg = new OscMessage("/sync");
  msg.add(1);
  oscP5.send(msg,remote);
}

void draw() {
  if(x>=width){ y+=s; x=0; }
  if(y>=height) reset();
  delay(100);
  int loc = x + y*img.width;
  noStroke();
  color c = img.pixels[loc];
  // int alpha = (c >> 24) & 0xFF;
  int red   = (c >> 16) & 0xFF;
  int green = (c >> 8)  & 0xFF;
  int blue  =  c        & 0xFF;
  int gray = ((red + green + blue) / 3);
  // println(alpha + " " + red + " " + green + " " + blue);
  fill(c);
  rect(x++,y,4,4);
  // println(gray);
  OscMessage msg = new OscMessage("/grayscale");
  msg.add(gray);
  oscP5.send(msg,remote);
}

Answers

  • Edit post, highlight code, press ctrl-o to format.

  • Frame rate 200 AND a delay?

    Make your mind up.

  • @koogs the delay is to give a little time when the reset function is called for stuff I have going on in Pure Data, its in the wrong place through so thanks for the heads up. any other suggestions?

  • thanks @gotoloop, I am aware of frame rate and doing tests it looks like my machine can run at around 5000 - but when I run the sketch above, my computer really struggles. I was wondering if there was something I was doing wrong or another way to achieve the results without pegging my CPU.

    Thanks

  • instantiating a new OscMessage every loop might not be the best idea. can you have one, instantiated outside the loop and modify that?

    the send() might be expensive also.

    try it without those bits, see how fast it is.

    there are java tools for this stuff, but even just printing the milliseconds might be enough to show the hotspots.

  • @koogs many thanks for the suggestion, even with those bit commented out my computer seems like its going to take off!!! Will keep experimenting.

Sign In or Register to comment.