lundi 13 avril 2015

Reading uint16 to image java

I have a .bin file that has been created in a matlab code as uint16 and i need to read it in java. With the code I'm using now I get a blurry image with a very bad grayscale. Any ideas on how I can make this work?


This is the class I use to read the .bin file:



import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BinaryFile2 {

public BinaryFile2() {
}

InputStream is;
DataInputStream dis;

public int[][] read(String filename, int x, int y) throws IOException {

try {

is = new FileInputStream(filename);
dis = new DataInputStream(is);
int length = dis.available();

int[] buf = new int[length];
int[][] real = new int[x][y];

int i = 0;
System.out.print(dis.available());
while (dis.available() > 0) {
buf[i] = dis.readShort();
;
i++;
}
int counter = 0;
for (int j = 0; j < x; j++) {
for (int k = 0; k < y; k++) {
real[j][k] = buf[counter];
counter++;
}
}
return real;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null)
is.close();
if (dis != null)
dis.close();
}
return null;

}
}


And this is the main class:



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

public class main {

public static void main(String[] args) {

BinaryFile2 binary = new BinaryFile2();

try {
int[][] image = binary.read("data001.bin", 1024, 2048);
BufferedImage theImage = new BufferedImage(1024, 2048,
BufferedImage.TYPE_BYTE_GRAY);
for (int y = 0; y < 2048; y++) {
for (int x = 0; x < 1024; x++) {
int value = image[x][y];
theImage.setRGB(x, y, value);
System.out.println(value);
}
}

File outputfile = new File("saved.png");
ImageIO.write(theImage, "png", outputfile);

System.out.println("done");
} catch (IOException e) {
e.printStackTrace();
}

}
}

Aucun commentaire:

Enregistrer un commentaire