【问题标题】:How to convert a matrix to an image in java [closed]如何在java中将矩阵转换为图像[关闭]
【发布时间】:2015-10-13 04:04:52
【问题描述】:

我有一个矩阵 a[512][512] 填充了 1 和 0,我怎样才能将此矩阵转换为图像(.png、.jpg 等)。

【问题讨论】:

  • 有趣的问题。到目前为止,您认为如何实际做到这一点?我的意思是 - 除了要求其他人做你的工作之外?
  • 没有足够的声誉来发表评论,但来自谷歌:stackoverflow.com/questions/20321606/…
  • openCV 我猜想为 java 设置一些努力,从来没有做过。

标签: java image matrix


【解决方案1】:

这将从您创建的矩阵创建灰度图像:

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

//Consider class and methods predefined. The following will be within a method

try {
    BufferedImage image;
    for(int i=0; i<yourmatrix.length; i++) {
        for(int j=0; j<yourmatrix[].length; j++) {
            int a = yourmatrix[i][j];
            Color newColor = new Color(a,a,a);
            image.setRGB(j,i,newColor.getRGB());
        }
    }
    File output = new File("GrayScale.jpg");
    ImageIO.write(image, "jpg", output);
}

catch(Exception e) {}

【讨论】:

    【解决方案2】:

    这是另一种方法,如果您从整个图像的一维大数组开始,您可以避免 for 循环。

    int width = 512;
    int height = 512;
    byte[][] a = new byte[width][height];
    
    byte raw[] = new byte[width * height];
    for (int i = 0; i < a.length; i++) {
        System.arraycopy(a[i], 0, raw, i*width, width);
    }
    //Arrays.fill(raw, width*height/2, width*height, (byte)1);
    byte levels[] = new byte[]{0, -1};
    BufferedImage image = new BufferedImage(width, height, 
            BufferedImage.TYPE_BYTE_INDEXED,
            new IndexColorModel(8, 2, levels, levels, levels));
    DataBuffer buffer = new DataBufferByte(raw, raw.length);
    SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width * 1, new int[]{0});
    Raster raster = Raster.createRaster(sampleModel, buffer, null);
    image.setData(raster);
    ImageIO.write(image, "png", new File("test.png"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多