Clear Filters
Clear Filters

I am getting wrong text file after extraction process.

1 view (last 30 days)
%embed.m
% Start the timer
tic;
% Read the text file
fileID = fopen('glioma.txt', 'r');
textData = fread(fileID, 'uint8');
fclose(fileID);
% Read the JPEG image
imageData = imread('glioma.jpg');
% Get the dimensions of the image
[rows, columns, ~] = size(imageData);
% Calculate the maximum number of bytes that can be embedded
maxBytes = floor(rows * columns / 8);
% Check if the text file size exceeds the maximum capacity
if numel(textData) > maxBytes
error('Text file size exceeds the capacity of the image.');
end
% Reshape the text data into a column vector
textData = textData(:);
% Convert the text data into binary format
binaryData = de2bi(textData, 8, 'left-msb');
% Embed the binary data into the image
embeddedImage = imageData;
% Flatten the image matrix
flattenedImage = reshape(embeddedImage, [], size(embeddedImage, 3));
% Calculate the number of bits to embed
numBits = size(binaryData, 1);
% Embed the binary data into the LSBs of the image
bitPlane = 1; % Select the least significant bit plane
% Embed the binary data into the bit planes
for i = 1:numBits
bitValue = binaryData(i); % Get the current bit value
% Check if the bit plane index exceeds the number of planes in the image
if bitPlane > size(flattenedImage, 2)
break;
end
flattenedImage(:, bitPlane) = floor(flattenedImage(:, bitPlane) / 2) * 2 + bitValue; % Embed the bit value into the bit plane
bitPlane = bitPlane + 1; % Move to the next bit plane
end
% Reshape the image matrix back to its original size
embeddedImage = reshape(flattenedImage, size(embeddedImage));
% Save the embedded image
imwrite(embeddedImage, 'embedded_image.jpg');
% Stop the timer and calculate the Time need to embed the text file
embeddedTime = toc;
% Display a message
% Display a message indicating successful embedding
fprintf('Text file embedded successfully and saved as embedded_image.jpg\n');
fprintf('Embedded Time: %.2f seconds\n', embeddedTime);
% Display the original image and the embedded image side by side
figure;
subplot(1, 2, 1);
imshow(imageData);
title('Original Image');
subplot(1, 2, 2);
imshow(embeddedImage);
title('Embedded Image');
% Adjust the figure size if needed
set(gcf, 'Position', get(0, 'Screensize'));
%extract.m
% Start the timer
tic;
% Read the embedded image
embeddedImage = imread('embedded_image.jpg');
% Get the dimensions of the image
[rows, columns, ~] = size(embeddedImage);
% Calculate the number of bytes to extract
numBytes = floor(rows * columns / 8);
% Initialize variables for extraction
extractedBytes = zeros(numBytes, 1);
byteIndex = 1;
bitIndex = 1;
% Extract the LSBs from the image pixels and convert them back to bytes
for i = 1:numel(embeddedImage)
pixel = embeddedImage(i);
bitValue = bitget(pixel, 1); % Extract the LSB (Least Significant Bit)
extractedBytes(byteIndex) = bitset(extractedBytes(byteIndex), bitIndex, bitValue);
bitIndex = bitIndex + 1;
if bitIndex > 8
bitIndex = 1;
byteIndex = byteIndex + 1;
end
if byteIndex > numBytes
break; % Stop extraction once all bytes have been retrieved
end
end
% Remove any trailing zeros from the extracted bytes
extractedBytes = extractedBytes(1:byteIndex-1);
% Convert the extracted bytes to a character array
extractedText = char(extractedBytes.');
% Save the extracted text to a file
fileID = fopen('extracted_text.txt', 'w');
fwrite(fileID, extractedText);
fclose(fileID);
% Stop the timer and calculate the extraction time
extractionTime = toc;
% Display a message indicating successful extraction
fprintf('Text file extracted successfully and saved as extracted_text.txt\n');
fprintf('Extraction Time: %.2f seconds\n', extractionTime);
  1 Comment
DGM
DGM on 28 Jun 2023
Edited: DGM on 28 Jun 2023
There are a number of things going wrong here, but it's not at all clear how you're actually trying to embed things.
You're interchangeably treating the variable bitPlane as the actual bit plane index (i.e. the LSB), and simultaneously treating it as a color channel index -- all while the comments say you're changing bit planes. Consequently, the embedding loop terminates immediately after indexing past the number of color channels in the image. None of this makes sense, and it's all at odds with the tests that are being performed beforehand.
Should embedded data be able to extend beyond the LSB in any element?
How should the data be placed? If you have six payload bits, should they go in:
pixel1(R), pixel1(G), pixel1(B), pixel2(R), pixel2(G), pixel2(B)
or
pixel1(R), pixel2(G), pixel3(B), pixel4(R), pixel5(G), pixel6(B)
... or should they fill up all R before continuing to G and then B?

Sign in to comment.

Accepted Answer

DGM
DGM on 28 Jun 2023
Edited: DGM on 28 Jun 2023
Here. This writes bits in a specified bit plane, across all three channels in the order [channels, rows, columns] (i.e. as per the first assumption in my comment).
% PARAMETERS
inimgfile = 'peppers.png';
outimgfile = 'embedded_image.png';
intextfile = 'glioma.txt';
outtextfile = 'recovered.txt';
bitsperchar = 8;
bitPlane = 1;
% Start the timer
tic;
% Read the text file
fileID = fopen(intextfile, 'r');
payloadtext = fread(fileID, 'uint8');
fclose(fileID);
% Read the JPEG image
cleanImage = imread(inimgfile);
% Get the dimensions of the image
[rows, columns, chans, ~] = size(cleanImage);
% Calculate the maximum number of chars that can be embedded
maxchars = floor(rows * columns * chans / bitsperchar);
% Check if the text file size exceeds the maximum capacity
numchars = numel(payloadtext);
if numchars > maxchars
error('Text file size exceeds the capacity of the image.');
end
% Reshape the text data into a column vector
payloadtext = payloadtext(:);
% Convert the text data into binary format
payloadbinary = de2bi(payloadtext, bitsperchar, 'left-msb');
payloadbinary = reshape(payloadbinary.',[],1); % vectorize
% Embed the binary data into the image
% bits are written in order of [channels, rows, columns]
% which is my best guess at intent
numbits = numchars*bitsperchar;
markedImage = permute(cleanImage,[3 1 2]); % reorient
affectedpixels = markedImage(1:numbits).'; % get relevant elements
affectedpixels = bitset(affectedpixels,bitPlane,payloadbinary); % set bits
markedImage(1:numbits) = affectedpixels; % insert back into image
markedImage = permute(markedImage,[2 3 1]); % reorient
% Save the embedded image
imwrite(markedImage, outimgfile);
% Stop the timer and calculate the Time need to embed the text file
embeddedTime = toc;
% Display a message
% Display a message indicating successful embedding
fprintf('Text file embedded successfully and saved\n');
fprintf('Embedded Time: %.2f seconds\n', embeddedTime);
% % Display the original image and the embedded image side by side
% %figure;
% subplot(1, 2, 1);
% imshow(imageData);
% title('Original Image');
%
% subplot(1, 2, 2);
% imshow(embeddedImage);
% title('Embedded Image');
%
% % Adjust the figure size if needed
% set(gcf, 'Position', get(0, 'Screensize'));
%%
%extract.m
% Start the timer
tic;
% Read the embedded image
markedImage = imread(outimgfile);
% Get the dimensions of the image
[rows, columns, chans, ~] = size(markedImage);
% Calculate the number of chars to extract
% this just blindly reads the entire image
% so there will almost always be trailing garbage
% writing that trailing garbage to a file may make the file unreadable
numchars = floor(rows * columns * chans / bitsperchar);
% extract the payload
numbits = numchars*bitsperchar;
markedImage = permute(markedImage,[3 1 2]); % reorient
affectedpixels = markedImage(1:numbits).'; % get only relevant elements
extractedbinary = bitget(affectedpixels,bitPlane); % extract bits
extractedbinary = reshape(extractedbinary,bitsperchar,[]).'; % devectorize
extractedText = char(bi2de(extractedbinary,'left-msb')).' % convert
% Save the extracted text to a file
fileID = fopen(outtextfile, 'w');
fwrite(fileID, extractedText);
fclose(fileID);
% Stop the timer and calculate the extraction time
extractionTime = toc;
% Display a message indicating successful extraction
fprintf('Text file extracted successfully and saved\n');
fprintf('Extraction Time: %.2f seconds\n', extractionTime);
  1 Comment
Ramya
Ramya on 29 Jun 2023
Edited: Ramya on 29 Jun 2023
Here if i embed the 100kb text file then i am getting Text file size exceeds the capacity of the image.I modified the payload text.Still its same.How to change if i want to embed 1mb text file?

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 28 Jun 2023
Unfortunately you forgot to attach glioma.txt and glioma.jpg. And of course you're saving images out as lossy JPG format, which is not recommended if you ever expect to get back the original image you saved. Unless you're specifically doing some research on image compression, never use JPG - use PNG format instead.
Looks like you're trying to do LSB watermarking. I'm attaching my demos that you can compare your code to. The one hiding the image in an image recovers the watermark perfectly at first and then adds noise to the image and recovers it again, and you can see the watermark is also a bit noisy.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:

Categories

Find more on Image Processing Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!