How to get two dimensional pixel array from an image

Keyword: How to get two dimensional pixel array from an image


1. To get pixel value from image (gray-scale)
2. And then store the pixel value as two dimensional array


1. Load the image as buffered image (this image is gray-scale)
2. Pass the buffered image to method to get two dimensional array which is stored with pixel value
3. Display simple output result from array


To manipulate pixels directly and to apply various algorithm on pixels, getting right value of pixels and locations are important step. The location and pixel value can also be verified with Matlab. Take note that Matlab array start from [1][1] instead of [0][0];
Simple Matlab code:
h = imshow('boy.png');
hp = impixelinfo;

Input Source

Program Code

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import javax.imageio.ImageIO;

public class GetTwoDimensionalPixelArray {

       public static void main(String[] args) throws IOException { //required to throws exception for loading image

              BufferedImage inputImage = File("boy.png")); //load the image from this current folder
              int[][] result = convertToArrayLocation(inputImage); //pass buffered image to the method and get back the result
              System.out.println("The pixel value of location " + "[19][19] is " //print out the pixel value of array
                           + result[19][19]);

       } //!end of main!//
       //!start of method!//
       private static int[][] convertToArrayLocation(BufferedImage inputImage) {

              final byte[] pixels = ((DataBufferByte) inputImage.getRaster()
                           .getDataBuffer()).getData(); // get pixel value as single array from buffered Image
              final int width = inputImage.getWidth(); //get image width value
              final int height = inputImage.getHeight(); //get image height value
              int[][] result = new int[height][width]; //Initialize the array with height and width

              //this loop allocates pixels value to two dimensional array
              for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel++) {
                     int argb = 0;
                     argb = (int) pixels[pixel];

                     if (argb < 0) { //if pixel value is negative, change to positive //still weird to me
                           argb += 256;

                     result[row][col] = argb;
                     if (col == width) {
                           col = 0;
              return result; //return the result as two dimensional array
       } //!end of method!//
} //!end of class!//


The pixel value of location [19][19] is 121


1. <image is taken from this link>
2. <it is good to take a look at how to get RGB value also>

No comments:

Post a Comment