2017年1月18日 星期三

[Java] 將照片的像素資料儲存成csv檔

之前Show Me The Code的講者介紹 Machine Learning 的 Python版本,上星期找到如何用 R 做之後,就只差準備資料。

記得學Java時有處理過圖片的。以下就是要將 3 (MaxN) 張 32*32 (Heigth*Width) 的JPEG 相片,轉換成灰階資料,儲存成 3*1024 的CSV 檔案。

當中幾個 Functions 提供以下功能:
  1. 相片轉換成灰度,記錄到 2D Array:
    convertTo2DUsingGetRGB() 或 convertTo2DWithoutUsingGetRGB()
  2. 2D Array 轉換成 1D Array:
    two2oneD()
  3. 3. 2D Array 儲存成 Csv 檔:
    save2csv()


package JGT;

import java.io.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.imageio.ImageIO;

public class PicturesToCsv {

   public static void main(String[] args) throws IOException {
      System.out.println("ConvertTo2DWithoutUsingGetRGB:");
      final int MaxN = 3;
      final int Heigth = 32; final int Width = 32;  
      final int MaxSize = Heigth*Width; 
      int[][] resultAll = new int[MaxN][MaxSize];
      
      for (int i=0; i<MaxN; i++) {
       String sPath = "face_"+Integer.toString(i+1)+".png";
       BufferedImage hugeImage = ImageIO.read(PerformanceTest.class.getResource(sPath));
       int[][] result2D = convertTo2DWithoutUsingGetRGB(hugeImage);   
       int[] result1D = two2oneD(result2D);
          for (int j=0; j<MaxSize; j++){
           resultAll[i][j] = result1D[j];
          }
      }
      save2csv(resultAll, "resultAll.csv");
   }

   private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
      int width = image.getWidth();
      int height = image.getHeight();
      int[][] result = new int[height][width];
      for (int row = 0; row < height; row++) {
         for (int col = 0; col < width; col++) {
            result[row][col] = image.getRGB(col, row);
         }
      }
      return result;
   }

   private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
      final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
      final int width = image.getWidth();
      final int height = image.getHeight();
      final boolean hasAlphaChannel = image.getAlphaRaster() != null;
      
      int[][] result = new int[height][width];
      if (hasAlphaChannel) {
         final int pixelLength = 4;
         for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += ((int) pixels[pixel + 1] ); // blue
            argb += ((int) pixels[pixel + 2] ); // green
            argb += ((int) pixels[pixel + 3] ); // red
            argb /= 3;
            result[row][col] = argb;
            col++;
            if (col == width) {
               col = 0;
               row++;
            }
         }
      } else {
         final int pixelLength = 3;
         for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += ((int) pixels[pixel] ); // blue
            argb += ((int) pixels[pixel + 1] ); // green
            argb += ((int) pixels[pixel + 2] ); // red
            argb /= 3;
            result[row][col] = argb;
            System.out.println(Boolean.toString(hasAlphaChannel) + row + ", " + col + ", " + pixel);
            col++;
            if (col == width) {
               col = 0;
               row++;
            }
         }
      }
      return result;
   }
   
   private static int[] two2oneD(int[][] arr)
   {
     int[] oneDArray = new int[arr.length * arr[0].length];
     for(int i = 0; i < arr.length; i++)
     {
       for(int j = 0; j < arr[i].length; j++)
       {
         oneDArray[(i * arr[i].length) + j] = arr[i][j];
       }
     }
     return oneDArray;
   }
   
   private static void save2csv(int[][] arr, String fileName) throws IOException {
    StringBuilder builder = new StringBuilder();
       for(int i = 0; i < arr.length; i++)//for each row
       {
          for(int j = 0; j < arr[0].length; j++)//for each column
          {
             builder.append(arr[i][j]+"");//append to the output string
             if(j < arr[i].length - 1)//if this is not the last row element
                builder.append(",");//then add comma
          }
          builder.append("\n");//append new line at the end of the row
       }
       BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
       writer.write(builder.toString());//save the string representation of the board
       writer.close();
   }
}

沒有留言:

張貼留言