image和陣列轉換
阿新 • • 發佈:2020-09-08
public static int[][] convertImageToArray(BufferedImage bf) { // 獲取圖片寬度和高度 int width = bf.getWidth(); int height = bf.getHeight(); // 將圖片sRGB資料寫入一維陣列 int[] data = new int[width*height]; bf.getRGB(0, 0, width, height, data, 0, width); // 將一維陣列轉換為為二維陣列int[][] rgbArray = new int[height][width]; for(int i = 0; i < height; i++) for(int j = 0; j < width; j++) rgbArray[i][j] = data[i*width + j]; return rgbArray; } public static void writeImageFromArray(String imageFile, String type, int[][] rgbArray){ // 獲取陣列寬度和高度 int width = rgbArray[0].length; int height = rgbArray.length; // 將二維陣列轉換為一維陣列 int[] data = new int[width*height]; for(int i = 0; i < height; i++) for(int j = 0; j < width; j++) data[i*width + j] = rgbArray[i][j];// 將資料寫入BufferedImage BufferedImage bf = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); bf.setRGB(0, 0, width, height, data, 0, width); // 輸出圖片 try { File file= new File(imageFile); ImageIO.write((RenderedImage)bf, type, file); } catch (IOException e) { e.printStackTrace(); } }
import java.awt.image.BufferedImage import org.apache.spark.ml.linalg.{Vector => MLVector, Vectors => MLVectors} def imgToArray(inputImg: BufferedImage): Array[MLVector] ={ //獲取圖片寬度和高度 val wResize = inputImg.getWidth val hResize = inputImg.getHeight val pixelList = new Array[MLVector](wResize) for (x <- 0 until wResize){ //將圖片sRGB資料寫入一維陣列中 val lineList = new Array[Double](hResize) for (y <- 0 until hResize){ lineList(y) = inputImg.getRGB(x, y) } val lineVector: MLVector = MLVectors.dense(lineList) pixelList(x) = lineVector } pixelList }