How can I convert between RGB565 and RGB24 image formats in MATLAB?

自作多情 提交于 2019-12-09 17:00:45

问题


I am getting an RGB matrix from a microprocessor that outputs an image in RGB565 format. I want to read this into MATLAB, convert it to RGB24 format, and output the image. How do I do this?


回答1:


You first have to read your data from the text file into a matrix in MATLAB. Since I don't know what format your text file is in, I can only suggest that you will probably need to use the function fscanf to read in all of your values (probably of type uint16), then you will likely have to reshape the values into an N-by-M image matrix using the function reshape.

Let's assume you've done all that, and you now have an N-by-M matrix img of unsigned 16-bit integers. First, you can use the function bitand to extract the bits for the red, green, and blue components, whose positions in the 16-bit integer are illustrated here:

Next, you can use the function bitshift and multiplication by a scale factor to scale the red, green, and blue values to a range of 0 to 255, then convert them to an unsigned 8-bit integer using the function uint8. This will give you three color component matrices the same size as img:

imgR = uint8((255/31).*bitshift(bitand(img, 63488), -11));  % Red component
imgG = uint8((255/63).*bitshift(bitand(img, 2016), -5));    % Green component
imgB = uint8((255/31).*bitand(img, 31));                    % Blue component

Now you can use the function cat to put the three color components into an N-by-M-by-3 RGB image matrix, then save the image to an RGB24 bitmap file using the function imwrite:

imgRGB = cat(3, imgR, imgG, imgB);  % Concatenate along the third dimension
imwrite(imgRGB, 'myImage.bmp');     % Output the image to a file

EXAMPLE:

Using a randomly generated 100-by-100 matrix of uint16 values and applying the above conversions, here are the results:

img = randi([0 65535], 100, 100, 'uint16');
% Perform the above conversions to get imgRGB
subplot(1, 2, 1);
imshow(img);
title('Random uint16 image');
subplot(1, 2, 2);
imshow(imgRGB);
title('Corresponding RGB image');




回答2:


RGB565 means 5 bit red, 6 bit green and 5 bit blue. RGB24 is made of 8 bit red, 8 bit green and 8 bit blue.

Using bitget and bitset you may convert your data.

http://www.mathworks.de/access/helpdesk/help/techdoc/ref/bitget.html



来源:https://stackoverflow.com/questions/3578265/how-can-i-convert-between-rgb565-and-rgb24-image-formats-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!