Combine a (m x n x p) matrix (image) of 8 bit numbers to a (m x n) matrix of 24 bit numbers and vice versa

2 views (last 30 days)
Say there is a matrix of (m x n x p), esp. a color image with R G and B channel. Each channel information is 8-bit integer.
But, for an analysis, the three 8-bit values have to be combined to get a 24-bit value and the analysis is done on the (m x n) matrix of 24-bit values.
After the analysis, the matrix has to be decomposed back to three 8-bit channels for displaying the results.
What I am doing right now:
  • Iterating through all the values in the matrix
  • Convert each decimal value to binary (using `dec2bin`)
  • Combine the three binary values together to get a 24-bit number (using `strcat` and `bin2dec`)
Code:
for i=1:m
for j=1:n
new_img(i,j) = bin2dec(strcat(...
sprintf('%.8d',str2double(dec2bin(img(i,j,1)))), ...
sprintf('%.8d',str2double(dec2bin(img(i,j,2)))), ...
sprintf('%.8d',str2double(dec2bin(img(i,j,3))))));
end
end
For the decomposition back to three 8-bits after analysis, the exact reverse process is done, still iterating through (m x n) values.
The problem is huge computation time.
I know that this is the not the correct way of doing this. Is there any matrix operation that I can do to achieve this so that the computation is done quickly?

Answers (1)

Walter Roberson
Walter Roberson on 31 Aug 2015
img32 = uint32(img);
new_img = img32(:,:,1) * 2^16 + img32(:,:,2) * 2^8 + img32(:,:,3);
and now new_img is a uint32() image as appropriate.
  5 Comments
Walter Roberson
Walter Roberson on 30 Aug 2017
Suppose we were working in decimal and we were decomposing the number 738 . Then, r_img(:,:,3) = mod(738, 10) = 8. t = (738-8)/10 = 730/10 = 73. r_img(:,:,2) = mod(73,10) = 3. t = (t-rimg(:,:,2))/10 = (73-3)/10 = 7 . rimg(:,:,1) = 7
Each mod() extracts the last "digit" in the base we are working with. Subtracting that last digit from the original number is always going to give a number that is exactly divisible by the base we were working with, because 'mod' is defined as the remainder after division and when you subtract off the remainder you have to get something that divides evenly. You just repeat that process a couple of times.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!