1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; // XOR encryption/decryption function void xorCipher(Mat& frame, char key) { frame.forEach<uchar>([&key](uchar& pixel, const int* position) { pixel ^= key; // XOR pixel value with key }); } int main() { // Open video file VideoCapture cap("path/to/your/video.mp4"); if (!cap.isOpened()) { cerr << "Error: Could not open video file!" << endl; return -1; } // Create windows for displaying the original and processed video namedWindow("Original Video", WINDOW_AUTOSIZE); namedWindow("Encrypted Video", WINDOW_AUTOSIZE); char key = 'K'; // Encryption/Decryption key while (true) { Mat frame; cap >> frame; // Capture a new frame from the video if (frame.empty()) { break; // Exit loop if there are no more frames } Mat encryptedFrame = frame.clone(); // Clone the frame for encryption xorCipher(encryptedFrame, key); // Encrypt the frame imshow("Original Video", frame); // Display the original frame imshow("Encrypted Video", encryptedFrame); // Display the encrypted frame int keyPressed = waitKey(30); // Wait for 30 ms for a key press if (keyPressed == 'q') { break; // Exit if 'q' is pressed } } cap.release(); // Release video file destroyAllWindows(); // Close all OpenCV windows return 0; } |
Explanation
- Include Libraries:
#include <opencv2/opencv.hpp>
: Includes OpenCV for video processing.#include <iostream>
: Used for input and output operations.
- XOR Cipher Function (
xorCipher
):void xorCipher(Mat& frame, char key)
: Function that applies XOR encryption/decryption to the video frame.frame.forEach<uchar>([&key](uchar& pixel, const int* position)
: Iterates through each pixel in the frame and XORs it with the given key.
- Open Video File:
VideoCapture cap("path/to/your/video.mp4");
: Opens the video file for reading.- Checks if the file was opened successfully. If not, prints an error message and exits.
- Create Windows:
namedWindow("Original Video", WINDOW_AUTOSIZE);
: Creates a window to display the original video.namedWindow("Encrypted Video", WINDOW_AUTOSIZE);
: Creates a window to display the encrypted video.
- Processing Loop:
- Captures frames from the video and encrypts each frame using the XOR cipher.
- Displays both the original and encrypted frames.
waitKey(30);
waits for 30 milliseconds for a key press. If ‘q’ is pressed, the loop exits.
- Cleanup:
cap.release();
: Releases the video file resource.destroyAllWindows();
: Closes all OpenCV windows.