Search code examples
imagematlabbinaryfilesbgrfile-import

How do I read a RAW RGB image in MATLAB?


I am trying to properly convert a RAW image so that I can view it in MATLAB. Image can be downloaded here. I am using the version of the code provided in How can I read in a RAW image in MATLAB? However, it is not working properly for me. Here is my slightly modified version below:

clear;
row=966;  col=1296;
fin=fopen('C:\Users\user\Desktop\test2.raw','r');
I=fread(fin, col*row*3,'uint8=>uint8'); %// Read in as a single byte stream
I = reshape(I, [col row 3]); %// Reshape so that it's a 3D matrix - Note that this is column major
Ifinal = flipdim(imrotate(I, -90),2); % // The clever transpose
imshow(Ifinal);
fclose(fin); %// Close the file

What I get: result

What I should get: correct

I'm not sure why it's not working for me but if I use an imaging program (ImageJ) I can correctly convert the RAW file if I select Image type as '24-bit BGR'. The pixel format of the image is 8 Bit BAYRG.


Solution

  • There you go:

    function q43127920
    row=966; col=1296;
    fin=fopen('test.raw','r');
    I = fread(fin, col*row*3,'ubit24=>uint32');
    I = reshape(I, col, row, []); 
    B = uint8(bitand(bitshift(I,-00),uint32(255)));
    G = uint8(bitand(bitshift(I,-08),uint32(255)));
    R = uint8(bitand(bitshift(I,-16),uint32(255)));
    I = cat(3,R,G,B);
    Ifinal = flip(imrotate(I, -90),2);
    imagesc(Ifinal);
    fclose(fin);
    

    Result:

    enter image description here