MATLAB: How do you convert a 4D logical matrix to a 3D uint8 matrix

4d logicalimage

Hi, so I have a 4D logical matrix in form of x,y,3,8 representing an image, where the 3rd dimension is each layer and the 4 dimension is the 8 bits representing the colour channel value. I need to convert this into a 3D unit8 matrix, similar to what is produced when an image is imported.

Best Answer

With a Matlab version >= R2016b:
x = 100;
y = 200;
Img4D = (randi([0,1], x,y,3,8) == 1);
Img3D = uint8(sum(Img4D .* reshape(2.^(0:7), 1, 1, 1, 8), 4));
Multiplying the logical values with the powers of 2 and summing it up converts the bits to an uint8 value. Example:
sum([1, 0, 1, 0, 1, 1, 1, 0] .* [1, 2, 4, 8, 16, 32, 64, 128])
>> 117