memory problem

edited July 2017 in Questions about Code

Hello!

I'm trying to make a slide show-type program that loads images into an array and displays them randomly. I've worked that out on a smaller scale but with the full array (1714 images) it runs out of memory. Any ideas on how to optimize this? Is there a way to randomly load a smaller number of images into the array as I go along, like randomized buffering?

PImage [] images = new PImage [1714];


void setup() {
  fullScreen;
  noCursor();
  for (int i = 0; i < images.length; i++) {
    images[i] = loadImage(i+".jpg");
  }
}

void draw() {
  image(images[int(random(1714))], 0, 0, width, height);
  frameRate(24);
}

Thank you!!

Answers

  • Answer ✓

    Create an int array with a capacity of 1714. Load the series of numbers from 0 to 1713 in random order. Then create a PImage array of size, say, 10. Load 10 images based on the first 10 entries of your index array. Display them. When you reach the end of the image array, load the next 10 images from your index array that you created initially. You do this until you run out of indices. Then you generate your index array again in another random order.

    Kf

  • Thanks. I'm just starting off and, though I think I understand the spirit of what you mean, I'm having trouble executing it. Can you point me towards an example?

  • Answer ✓

    This is a sample code... you need to load the PImages. Notice it is untested. This is only to show the concept.

    Kf

    final int N=1714;
    final int IMG2LOAD=10;
    
    
    PImage[] imgs=new PImage[IMG2LOAD];
    
    IntList indices = new IntList()
    int masterIdx=0; //Index in indices
    
    int current=0;  //Keeps track of current index in PImage[]
    
    
    void setup(){
      fillNow();
      loadBatch(0);
    }
    
    void draw(){
    
      image(imgs[current++],0,0,width,height);
    
      if(masterIdx>=N){ 
         masterIdx=0;
         current=0;
         fillNow();
         loadBatch(0);
      }
    
      if(current==IMG2LOAD){
         current=0;
         loadBatch(masterIdx);
      }
    
    }
    
    void fillNow(){
    
      indices.clear();  //Empty list
    
      for(int i=0;i<N;i++){
         int val =(int)random(N); 
    
         //Ensure index added is unique
         while(indices.hasValue(val)==true){
              val =(int)random(N); 
         }
          indices.append(val);  //If error... then use add()
      }
    }
    
    void loadBatch( int strIdx){
    
      //Load IMG2LOAD images here starting from strIdx
    
      ...TO be implemented
    
       masterIdx=strIdx+IMG2LOAD;
    }
    
  • (isn't there a long-standing bug where images don't clear all the memory they use when they are re-used? won't this just mean it runs out of memory later rather than sooner? maybe that's enough)

    i've seen people using jcache for things like long slideshows.

Sign In or Register to comment.