javabufferedimagekinect-v2

Grayscale image not saving using BufferedImage.TYPE_USHORT_GRAY


I am trying to save a depth map from Kinect v2 which should come out as grayscale but every time that I try to save it as JPG file using the type BufferedImage.TYPE_USHORT_GRAY literally nothing happens (No warning on screen or in the console).

I manage to save it if I use types BufferedImage.TYPE_USHORT_555_RGB or BufferedImage.TYPE_USHORT_565_RGB but instead of being grayscale it come as out blueish or greenish depth maps.

Find below the code sample:

short[] depth = myKinect.getDepthFrame();
int DHeight=424;
int DWidth = 512;
int dx=0;
int dy = 21;

BufferedImage bufferDepth = new BufferedImage(DWidth,  DHeight, BufferedImage.TYPE_USHORT_GRAY);

try {
    ImageIO.write(bufferDepth, "jpg", outputFileD);
} catch (IOException e) {
    e.printStackTrace();
}

Is there anything I am doing wrong to save it in grayscale? Thanks in advance


Solution

  • You have to assign your data (depth) to the BufferedImage (bufferDepth) first.

    A simple way to do this is:

    short[] depth = myKinect.getDepthFrame();
    int DHeight = 424;
    int DWidth = 512;
    int dx = 0;
    int dy = 21;
    
    BufferedImage bufferDepth = new BufferedImage(DWidth, DHeight, BufferedImage.TYPE_USHORT_GRAY);
    
    for (int j = 0; j < DHeight; j++) {
        for (int i = 0; i < DWidth; i++) {
            int index = i + j * DWidth;
            short value = depth[index];
            Color color = new Color(value, value, value);
            bufferDepth.setRGB(i, j, color.getRGB());
        }
    }
    
    try {
        ImageIO.write(bufferDepth, "jpg", outputFileD);
    } catch (IOException e) {
        e.printStackTrace();
    }