Saturday, 19 May 2012

Legolab, code, Image to Array

import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageToArray {

    private int imageHeight = 0;
   
    public int getHeight() {
        return imageHeight;
    }
   
   public int[] getArray(String fileLocation) throws FileNotFoundException, IOException {
      
      File file = new File(fileLocation);
      BufferedImage image = ImageIO.read(file);
      imageHeight = image.getHeight();
      int[] rgbarr = image.getRGB(0, 0, image.getHeight(), image.getHeight(), null, 0, image.getHeight());// image is 13*15
      
      int[] output = new int[rgbarr.length];
      for ( int i=0; i<rgbarr.length; ++i ) {
        
        int r = (rgbarr[i] >> 16 ) & 0x0FF;
        int g = (rgbarr[i] >> 8  ) & 0x0FF;
        int b = (rgbarr[i]       ) & 0x0FF;
        
        if((0.30*r + 0.59*g + 0.11*b) > 127){
            output[i] = 0;
        } else {
            output[i] = 1;
        }
      }
      
      String toPrint = "";
      for(int j=1; j<=output.length;j++){
          
          toPrint += output[j-1];
          if(j%100 == 0) {
              toPrint += "\n";
          }
      }
      return output;
   }
}

No comments:

Post a Comment