Matlab: Spatial domain pixel value binary conversion

Matlab: Spatial domain pixel value binary conversion

In digital image processing, it is often necessary to convert the decimal value of a pixel into a binary representation. Matlab provides a quick and easy way to implement this conversion process.

The following is a simple Matlab program that converts the decimal values ​​of all pixels in a grayscale image to binary format and displays them:

% 读取灰度图像
img = imread('lena_gray.jpg');

% 将图像转换为二进制格式
binaryImg = dec2bin(img);

% 显示二进制图像
imshow(binaryImg);

The program first imreadreads a grayscale image using the function and stores it in imga variable named . Then, use dec2bina function imgto convert the decimal values ​​of all pixels in to binary format and store the result in a binaryImgvariable named . Finally, use imshowa function to display the image in binary format.

It should be noted that imshowthe function can only display grayscale or RGB images, so before converting the image to binary format, you must ensure that it is a grayscale image.

If you want to save the converted binary format as a file, you can use the following code:

% 将二进制图像写入文件
fid = fopen('binaryImg.txt', 'wt');
for i = 1:size(binaryImg, 1)
    fprintf(fid, '%s\n', binaryImg(i, :));
end
fclose(fid);

The code writes the converted binary format binaryImg.txtto a text file named . It uses fopena function to create a file pointer, then uses a loop to iterate through binaryImgeach line in the file, and uses fprintfthe function to write it to the file. Finally, use fclosethe function to close the file pointer.

The above is the method and code for converting the airspace pixel value from decimal to binary in Matlab, I hope it will be helpful to you!

Guess you like

Origin blog.csdn.net/CodeWG/article/details/132033439