Generate coe file with 12 bits
Show older comments
I have a image on 24 bits and i want to have a coe file with 12 bits on a row.
This is the code:
clear all;
clc;
close all;
[filename, pathname] = uigetfile('Capture.PNG','Pick an M-file');
imagine = imread(filename);
[ncolumns,nrows,ncolors]=size(imagine);
im_12bit (:,:,1) = dec2bin ( round (imagine (:,:,1)/16),4);
im_12bit (:,:,2) = dec2bin ( round (imagine (:,:,2)/16),4);
im_12bit (:,:,3) = dec2bin ( round (imagine (:,:,3)/16),4);
fid = fopen('out3333.coe', 'w'); %Create COE file
fprintf(fid, 'memory_initialization_radix=2;\n');
fprintf(fid, 'memory_initialization_vector=\n');
m = size(imagine); % Get the image size, m(1) is high, m(2) is wide
for j =1 : m(1)
for i =1 : m(2)
% Write RGB data together
fprintf(fid, '%s%s%s,\n', im_12bit(j,i,1), im_12bit (j,i,2),im_12bit(j,i,3));
end
end
fseek(fid, -2, 1); % Overwrite the last comma with a semicolon
fprintf(fid, ';');
i have this error:
Index in position 2 exceeds array bounds (must not exceed 5).
Can you help me to solve this? It s another way to do it?
Thanks.
Answers (1)
Suppose you have an entry which is uint8(255) . Then
uint8(255)/16
Notice this is already rounded -- the integer data types are defined to operate like
A/B --> round(double(A)/double(B)) and then make it the integer data type
Now let's have a look:
dec2bin(round(uint8(255)/16), 4)
Notice you got out 5 bits even though you only expected 4. To get out 4, you need to floor() instead of round -- and that implies you have to convert the image to double yourself, so that the default behavior of round() does not interfere.
Now the next thing you need to look at is
dec2bin([1 2; 3 4; 5 6], 4)
You passed in a 3 x 2 array, but you got out a 6 x 4 array, where 4 is the number of bits per entry. When you use dec2bin() you do not get out string objects. The result of dec2bin() on that array is not going to be
["0001", "0010"; "0011", "0100"; "0101", "0110"]
so you are not going to be able to index the result of dec2bin() at a row and column number and expect the result to be the binary for the corresponding image row and column. You can arrange it to be that way though:
im = imresize(imread('flamingos.jpg'),[10 10]);
image(im)
bits = reshape(string(dec2bin( floor(double(im)/16), 4 )), size(im));
bits(1:2,1:2,:)
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!