How to covert binary data to original data format?

4 次查看(过去 30 天)
I wrote a code that can convert an image or any data format to binary. Now I need to convert back the binary data to the picture or the corresponding format. Any one please help me with this.
clc;close all;clear all;
%Any file to binary
fid = fopen('file.pdf');
bits = fread(fid, inf, '*ubit1', 'b');
fclose(fid);

回答(1 个)

Walter Roberson
Walter Roberson 2025-1-21
You cannot generally convert the uint8 stream into an in memory version of the original object. For example if you have the uint8 stream that results from reading ubit1 from an image file, then you cannot generally convert the stream into the image (without a bunch of hard work.) Likewise you cannot convert the uint8 stream of a database file into a copy of the database (without a bunch of hard work.)
You can construct another file that contains the original content, by using fwrite() with 'ubit1' precision .
  3 个评论
Walter Roberson
Walter Roberson 2025-1-30
% Read the image
originalImage = imread('indiancorn.jpg'); % Replace 'your_image.jpg' with your image file
grayImage = rgb2gray(originalImage);
binaryImage = imbinarize(grayImage);
linearBinaryArray = binaryImage(:);
savedBinaryArray = linearBinaryArray;
reshapedBinaryImage = reshape(savedBinaryArray, size(binaryImage));
% Convert the binary image back to grayscale
reconstructedGrayImage = uint8(reshapedBinaryImage) * 255;
figure;
subplot(1, 2, 1);
imshow(grayImage);
title('Original Grayscale Image');
subplot(1, 2, 2);
imshow(reconstructedGrayImage);
title('Reconstructed Grayscale Image');
%imwrite(reconstructedGrayImage, 'reconstructed_gray_image.jpg');
This is what you should expect from binarizing an image.
Walter Roberson
Walter Roberson 2025-1-30
% Read the image
originalImage = imread('indiancorn.jpg'); % Replace 'your_image.jpg' with your image file
grayImage = rgb2gray(originalImage);
linearBinaryArray = dec2bin(grayImage(:),8) - '0';
savedBinaryArray = linearBinaryArray(:);
savedBinaryArray8 = char(reshape(savedBinaryArray,[],8) + '0');
reshapedBinaryImage = reshape(bin2dec(savedBinaryArray8), size(grayImage));
% Convert the binary image back to grayscale
reconstructedGrayImage = uint8(reshapedBinaryImage);
figure;
subplot(1, 2, 1);
imshow(grayImage);
title('Original Grayscale Image');
subplot(1, 2, 2);
imshow(reconstructedGrayImage);
title('Reconstructed Grayscale Image');
%imwrite(reconstructedGrayImage, 'reconstructed_gray_image.jpg');

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by