Choosing an image does not work the first time, works fine the second time and beyond

edited September 2017 in Questions about Code

hi I am trying to write a program to do the following.

a. display a set of images as thumbnails

b. choose an image

c. display the image and do further processing.

am using mousePressed() to determine which thumbnail is chosen. the program has a strange behaviour. first time a thumbnail is chosen the image is not displayed. second time onwards it works fine. unable to figure this one out. code is

            import java.util.Date;
            boolean DEBUG = true;
            color RED = color (255, 0, 0);
            color GREEN = color (0, 255, 0);
            color BG = color (0, 0, 0);
            color FG = color (255, 255, 255);
            float offset =10; // thumbnails will be drawn 20 pixels apart
            float thumbnailwidth =50;
            float thumbnailheight=50;
            PImage [] IMAGES;
            File [] fileobjects;
            File individualfile;
            boolean CHOOSINGFILE = true;
            int fileindexrow = 0;
            int fileindexcol = 0;
            int fileindex = 0;
            int currentpage =0;
            int maxrows = 0;
            int maxcols =0;
            int maxperpage =0;
            int pageno =1;
            int totalpages=1;
            String path = "F:/vsa/softwareforpc/processing/sourcecode/images";
            int currentchoicex =int (thumbnailwidth - offset);
            int currentchoicey =int (thumbnailheight - offset);
            int DISPLAYPAGECOUNT =0;

            Boolean BlackonWhite = false;
            PImage kolam, grey_kolam; // image type for input kolam variable and transformed kolam variable
            int FILEINDEX;
            File  inputfile ;
            String inputfilename = "";
            String outputfilename = "pixellist.txt";
            int screenwidth=1000; // this has to be the first variable of size fn. below
            int screenheight=1000; // this has to the second variable of size fn. below
            int[][] inputmatrix = {{0, 0}};//initialize 2D array with {0,0}
            PrintWriter output;
            Table pixeltable;
            int STATE;

            void setup() {
              size(1000, 1000);
              background (BG);
              frameRate(1);
              STATE = 0;
              FILEINDEX = 999;// initial value of the FILE INDEX is set to a non existent file index value
              output = createWriter(outputfilename); 
              pixeltable = new Table();
              pixeltable.addColumn("xcord");
              pixeltable.addColumn("ycord");
              maxrows = int(height/(thumbnailheight+offset));
              maxcols = int(width/(thumbnailwidth+offset));
              maxperpage = maxrows*maxcols;
              if (DEBUG) {
                println("max per page is ", maxperpage);
              }
              fileobjects=listFiles(path);
              if (fileobjects.length<=maxperpage) {
                maxperpage=fileobjects.length;
              } else {
                totalpages=int(fileobjects.length/maxperpage);
              }
              if (DEBUG) {
                println("print no of files =", fileobjects.length);
              }
              IMAGES = new PImage[fileobjects.length];
              // this for loop loads the images array with individual files
              for (int i=0; i<fileobjects.length; i++) {
                individualfile= fileobjects[i];
                //println ("counter i", i, "individual file  ", individualfile.getName());
                IMAGES[i]=loadImage(path+"/"+individualfile.getName());
              }
              displaypage(pageno, IMAGES); 

              noLoop();
            }

            //draw() doesn't loop because of the noLoop() in setup()
            void draw() {
            }
            void mousePressed() {

              choosefile();
              image (IMAGES[FILEINDEX], 500, 400, 400, 400);
              //redrawfile();
              //readpixelstoarray(screenwidth, screenheight);
              //writetocsv();
              //displaypage(pageno, IMAGES);
              loop();
            }

            void choosefile() {
              DISPLAYPAGECOUNT++;
              fileindexcol = int (mouseX/ (thumbnailwidth+offset))+1; // println (" file index col no is  = ", fileindexcol);
              fileindexrow = int (mouseY/ (thumbnailheight+offset))+1;//println (" file index row is  = ", fileindexrow);

              if (mouseX >= ((fileindexcol*thumbnailwidth+(fileindexcol-1)*offset)-10)&& mouseX<=(fileindexcol*thumbnailwidth+(fileindexcol-1)*offset))
              {
                if (mouseY >= ((fileindexrow*thumbnailheight+ (fileindexrow-1)*offset)-10)&& mouseY<= (fileindexrow*thumbnailheight+(fileindexrow-1)*offset))
                {
                  fill (RED);
                  rect (currentchoicex, currentchoicey, 10, 10);
                  fill (GREEN);
                  currentchoicex = int (fileindexcol*thumbnailwidth+(fileindexcol-1)*(offset)-10);
                  currentchoicey = int (fileindexrow*thumbnailheight+ (fileindexrow-1)*(offset)-10);
                  rect (currentchoicex, currentchoicey, 10, 10);
                }
              }

              println (" this is round no   ", DISPLAYPAGECOUNT, "   in choosefile");
              if ((fileindexrow-1)*maxcols+fileindexcol-1<=maxperpage) {
                FILEINDEX= (fileindexrow-1)*maxcols+fileindexcol-1;
                println (" the index for the file chosen is ", (fileindexrow-1)*maxcols+fileindexcol-1);
                image (IMAGES[FILEINDEX], 0, 400, 300, 300);
              } else {
                println(" Choose one of the files above");
              }
            }



            void redrawfile() {
              if (DEBUG) {
                println (" in redrawfile()the index for the file chosen is ", (fileindexrow-1)*maxcols+fileindexcol-1);
                println ("Path is ", path);
                println (" the fileindex in redraw is ", fileindex);
                println("before loading kolam image");
              }
              background (BG);
              //image (IMAGES[fileindex], 0, 400, 300, 300);
              if (DEBUG) {
                println(" at the end of redrawfile ");
              }
            }
            //function to convert all pixel data to array and to write to CSV file
            void readpixelstoarray(int xmax, int ymax) {
              // xmax is the horixontal width of the screen to be used
              // ymax is the vertical height of the screen to be used
              int pixel_xcord = 0;
              int pixel_ycord=0;
              if (DEBUG) {
                println(" Pixel coordinates  Redvalue   Blue Value   Green Value  ");// header line to display values of RBG
              }
              loadPixels();
              if (DEBUG) { 
                println("pixellength", pixels.length);
              }
              for (int i=0; i<pixels.length; i++) {
                float r= red(pixels[i]); // split the color c in to component values of RGB
                float g= green(pixels[i]);
                float b= blue(pixels[i]);
                // check if all 3 values are 0 to signify black, if black set the color to RED 
                if ((r<=10&& g<=10&&b<=10)) {
                  pixels[i]=RED;
                } else {
                  pixels[i]=GREEN;
                }
                pixel_ycord= i/xmax;
                pixel_xcord= i%xmax;
                /**    if (DEBUG) {
                 println("max pixels  ", pixels.length, "Index no. ", i, "X Cord  ", pixel_xcord, "Y Cord  ", pixel_ycord);
                 }*/
                inputmatrix = (int[][])append(inputmatrix, new int[]{pixel_xcord, pixel_ycord});
              }
              updatePixels();
              println ("at the end of updatePixels");
            }

            //function to redraw using 2 d array
            void writetocsv() {
              if (DEBUG) { 
                println (" In the writetocsv  function ");
              }
              color c= color(255, 255, 0);
              for (int i=0; i<inputmatrix.length; i++) {
                set (inputmatrix[i][0], inputmatrix[i][1], c);
                output.print(inputmatrix[i][0]);
                output.println (inputmatrix[i][1]);  // Write the coordinate to the file
                TableRow newRow = pixeltable.addRow();
                newRow.setInt("xcord", inputmatrix[i][0]);
                newRow.setInt("ycord", inputmatrix[i][1]);
              }
              saveTable(pixeltable, "pixellist.csv");
              STATE=0;
              //background (BG);
              if (DEBUG) { 
                println ("Reached the end of writingtocsv ");
              }
            }
            void displaypage(int pgno, PImage[] dispimage) {
              // calculate the index of image based on pageno
              int startingimageno =maxperpage*(pgno-1);
              int imagestoshow =0;
              int xoffset;
              int yoffset;
              STATE = 0;
              if ((fileobjects.length-startingimageno)>=maxperpage) {
                imagestoshow = maxperpage;
              } else {
                imagestoshow = fileobjects.length-startingimageno;
              }
              if (DEBUG) { 
                println("no of imgages to show ", imagestoshow, "starting from imageno  ", startingimageno);
              }
              for (int i=0; i<(imagestoshow); i++) {
                startingimageno = startingimageno+i;
                xoffset = int (int (i%maxcols)*(thumbnailwidth+offset));
                //println("xoffset computed as =", xoffset);
                yoffset = int (int(i/maxrows)*(thumbnailheight+offset));
                // println("yoffset computed as =", yoffset);
                //println("indext for image =", i);
                image(dispimage[i], xoffset, yoffset, thumbnailwidth, thumbnailheight);
                fill (RED);
                rect (xoffset+thumbnailwidth-10, yoffset+thumbnailheight-10, 10, 10);
              }
              /** if (DEBUG) { 
               println ("End of DIsplay PAge code");
               }*/
            }

            // This function returns all the files in a directory as an array of File objects
            // This is useful if you want more info about the file
            File[] listFiles(String dir) {
              File file = new File(dir);
              if (file.isDirectory()) {
                File[] files = file.listFiles();
                return files;
              } else {
                // If it's not a directory
                return null;
              }
            }


            void keypressed() {
              output.flush();  // Writes the remaining data to the file
              output.close();  // Finishes the file
              //exit(); //stop the program
            }

Answers

  • Did you try to get rid of noLoop() ?

  • Thanks Chrisir, after that I made multiple changes. will work some more and update you later.

  • hi Chrisir I apologize for the long silence. finally decided to check this by building a smaller piece of code. this code is to test keyboard handling as the application goes thru different states.(finally will add mousehandler as well). this code also does not behave consistently. the first time I run the code (well at least most of the times), the code does not respond to the key board inputs. I wonder why. can you please throw some light on what is happening.

    int STATE =0; // temporary variable to track the state
    int MAIN_MENU = 0;
    int CALIBRATE =1;
    int CHOOSE_KOLAM = 2;
    int DRAW_KOLAM = 3;
    color RED = color (255, 0, 0); 
    color GREEN = color (0, 255, 0); 
    color BLUE = color (0, 0, 255); 
    color BROWN = color (122, 122, 122); // define colors
    color WHITE = color (255, 255, 255); 
    color BLACK = color (0, 0, 0);
    
    
    
    void setup() {
      size (600, 600);
      background(0);
      main_menu_screen();
    }
    void draw() {
      switch (STATE) {
      case 0:
        println (" in the MAIN MENU ");
        background(RED);
        main_menu();
        break;
      case 1:
        background(BLUE);
        println(" in the CALIBRATE MENU ");
        calibrate();
        break;
      case 2:
        background(GREEN);
        println(" in the CHOOSE KOLAM  MENU ");
        choose_kolam();
        break;
      case 3:
        background(255);
        println(" in the DRAW KOLAM MENU ");
        draw_kolam();
        break;
      default:
        println (" In unknown state ");
        break;
      }
    }
    
    void main_menu() {
      //fill (BLACK);
      text (" in main menu ", 10, 10);
    }
    void calibrate() {
    
      text (" in calibrate menu ", 10, 10);
    
      for (int j =0; j<40; j=j+20) {
        for (int i =0; i< height; i=i+20){
       fill (RED);      
        rect(j, i, 10, 10);}
        }
    
      //fill (BLACK);
    }
    void choose_kolam() {
      fill(BLACK);
      text (" in choose kolam menu ", 10, 10);
    }
    void draw_kolam() {
      fill(BLACK);
      text (" in draw kolam menu ", 10, 10);
    }
    void keyPressed() {
      println (" value of Key presssed is ", key);
      println (" int value of Key is ", int (key));
    
      if (int (key)>=48&&int(key)<=51) {
        STATE = int( key)-48;
      } else {
        println ( " Please enter a value between 0 to 3 ");
      }
    }
    
    void main_menu_screen() {
      text(" In the main menu ", 10, 10);
    }
    
Sign In or Register to comment.