MATLAB: JPG to 4-bit Color COE

.jpgconvertdigital image processingimage processingMATLABMATLAB and Simulink Student Suite

I have been using 39805-image-to-coe-converter to convert 256×256 pixel 24-bits total color jpg's (8 bits per color) to 8 bit (total) grayscale COE files. I'm flexible on the source images. I'm trying to take the color jpg's and turn them into 4-bit color (4-bit per color channel) COE files where each row is my 12 bit pixel color (RGB). Reason being these are creating block ram in an FPGA with a 12-bit total color pipe… 4 bits for Red, 4 for Blue, and 4 for Green (12 total).
So for example, the output file (COE is basically just a text file), a pure white field would output (in hexadecimal here):
000 (next line) 000 (next line) 000 (next line) 000 (next line) …
or
fff (next line) fff (next line) fff (next line) …
depending on inversion.
If there was a way to verify that the output COE is indeed the image that'd be rad too. I'm also assuming using img = img'; will be able to invert the colors if necessary.
% Image to text conversion
% Read the image from the file
[filename, pathname] = uigetfile('*.bmp;*.tif;*.jpg;*.pgm','Pick an M-file');
img = imread(filename);
img = imresize((img),[256 256]);
[ row col p ] =size(img);
% Next line for testing
%image(img);
% Turns 8 bit into 4 bit (collapses colors - no good)
%img = img ./ 16;
% Converts to 2 channel grascale
%if p == 3
% img = rgb2gray(img);
%end
% What does this do? Create a 65x65 array? Why?
rectImg = img(16:80,16:80);
% noise add. Why would he want to add noise?
%rectImg = imnoise(rectImg,'salt & pepper', 0.02);
img(16:80,16:80) = rectImg;
image(img);
% Image Transpose
%imgTrans = img';
% iD conversion
img1D = img(:);
% Decimal to Hex value conversion
imgHex = dec2hex(img1D);
% New txt file creation
fid = fopen([filename '.coe'], 'wt');
% Hex value write to the txt file
fprintf(fid,'memory_initialization_radix=16;\n');
fprintf(fid,'memory_initialization_vector=\n');
fprintf(fid, '%x\n', img1D);
% Close the txt file
fclose(fid);

Best Answer

Solved by by normalizing into 4 bits (0-15)
% normalize to 0..15 per channel
img_12 = uint8(double(img) / 255.0 * 15.0);