image和数组转换

    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
    }

 

posted @ 2020-09-08 16:01  等木鱼的猫  阅读(516)  评论(0编辑  收藏  举报