#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
// Function to hide a message in an image
void encodeMessage(Mat& image, const string& message) {
// Ensure message fits in the image
int msgLength = message.size();
if (msgLength > image.rows * image.cols / 8) {
cerr << "Error: Message is too long to encode in the image!" << endl;
return;
}
// Convert message to binary
string binaryMessage;
for (char c : message) {
for (int i = 7; i >= 0; --i) {
binaryMessage += (c & (1 << i)) ? '1' : '0';
}
}
binaryMessage += '0'; // Add a terminator for the message
// Encode binary message into the image's LSB
int bitIndex = 0;
for (int y = 0; y < image.rows; ++y) {
for (int x = 0; x < image.cols; ++x) {
Vec3b& pixel = image.at<Vec3b>(y, x);
for (int c = 0; c < 3; ++c) {
if (bitIndex < binaryMessage.size()) {
pixel[c] = (pixel[c] & ~1) | (binaryMessage[bitIndex] - '0');
++bitIndex;
}
}
}
}
}
// Function to extract a message from an image
string decodeMessage(const Mat& image) {
string binaryMessage;
for (int y = 0; y < image.rows; ++y) {
for (int x = 0; x < image.cols; ++x) {
Vec3b pixel = image.at<Vec3b>(y, x);
for (int c = 0; c < 3; ++c) {
binaryMessage += (pixel[c] & 1) ? '1' : '0';
if (binaryMessage.size() >= 8 && binaryMessage.substr(binaryMessage.size() - 8) == "00000000") {
return binaryMessage.substr(0, binaryMessage.size() - 8);
}
}
}
}
return "";
}
int main() {
// Load an image from file
Mat image = imread("path/to/your/image.png");
if (image.empty()) {
cerr << "Error: Could not load image!" << endl;
return -1;
}
// Encode a message into the image
string message = "Hello, Steganography!";
encodeMessage(image, message);
// Save the modified image
imwrite("encoded_image.png", image);
// Load the modified image
Mat encodedImage = imread("encoded_image.png");
// Decode the message from the image
string decodedMessage = decodeMessage(encodedImage);
cout << "Decoded Message: " << decodedMessage << endl;
return 0;
}