Opening bitmap images in C/C++ as matrices


I am working on an image processing project in MATLAB, but I need to
work in C/C++ in parallel and so, I need to implement the operations
in MATLAB provided as commands in the Image Processing Library in

One of the primary goals to to implement imread which basically takes
a RGB/grayscale image and deposits the intensity values of each pixel
of the image into a matrix having an order equal to the resolution of
the image.

for instance,

A = imread('test.bmp');

in MATLAB generates a matrix A, which is the intensity matrix of
test.bmp. This is important since it allows image processing
operations to be performed on the matrix.

Can anyone suggest a source where I can find some algorithm or
program to achieve this?


  • SephirothSephiroth Fayetteville, NC, USA
    Simple as heck!
    void MyFunc(char *FileName)
    FILE *ImageFile;
    unsigned char *Array;

    if((ImageFile = fopen(FileName, "rb")) == NULL)
    MessageBox(NULL, "Could not open file for reading.", "Error", MB_OK);

    fread(&bmfh, sizeof(BITMAPFILEHEADER), 1, ImageFile);
    fread(&bmih, sizeof(BITMAPINFOHEADER), 1, ImageFile);

    if((Array = (unsigned char*)calloc(((bmih.bmHeight * bmih.bmWidth) * 3), sizeof(unsigned char))) == NULL)
    MessageBox(NULL, "Could not allocate any memory for the image array.", "Error", MB_OK);

    for(int Loop = 0; Loop < ((bmih.bmHeight * bmih.bmWidth) * 3); Loop += 3)
    fread(Array[Loop], sizeof(unsigned char[3]), 1, ImageFile);

    //Now do whatever you want with the array!
    Basically, that allocates an array of "unsigned chars", also referred to as "bytes" that is big enough for a red, green, and blue pixel for each pixel in the bitmap. Let's pretend the image you are trying to load into this array is 256x256 in size. This makes our "Array" pointer 256x256x3. You want to multiply the height and width first to get the number of pixels in the image. After you get the result, you want to multiply that by three so each pixel can have a red, green, and blue value. the pixel at 0, 0 on the image would be accessed in the array by "Array[0]", "Array[1]", and "Array[2]". If you need more help let me know.


  • Hi

    I am new to C++.Thanks a lot for the code. The concept is very useful. However, when I compile the code it gives the following error

    'fread' : cannot convert parameter 1 from 'void' to 'void *'
    1> Expressions of type void cannot be converted to other types"

    This is because the "Array" parameter is of unsigned char type and not array type and the fread syntax is to store it in void * pointer type. Kindly tell how to rectify this problem.

    thanks a lot in advance
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!