├── Assignments ├── Battleship Game │ ├── How To Send Answers.txt │ └── README.md └── Image Processing Basics │ ├── How To Send Answers.txt │ └── README.md ├── OpenCV Basics ├── basic_functions.py ├── bitwise.py ├── consts.py ├── draw.py ├── hidden_image.py ├── noise.py ├── read.py ├── requirements.txt └── transformation.py └── numpy_matplotlib_tutorial_complete.ipynb /Assignments/Battleship Game/How To Send Answers.txt: -------------------------------------------------------------------------------- 1 | # How to Submit Your Assignment 2 | 3 | Follow these steps to organize and submit your answer for the **Matrix-based Battleship Game** assignment. The submission process involves creating a folder with your name in the assignment repository and sending a **pull request** (PR) to the original repository. 4 | 5 | --- 6 | 7 | ### 1. Create a Folder with Your Name 8 | 9 | 1. Navigate to the assignment repository (the one you have been given access to). 10 | 2. Inside the repository, create a new folder. Name the folder using your **full name** (e.g., "John_Doe" or "Jane_Smith"). 11 | 3. This folder will contain all your work for the assignment. 12 | 13 | --- 14 | 15 | ### 2. Organize Your Files 16 | 17 | Inside your folder (e.g., `John_Doe/`), please add the following files: 18 | 19 | - **Python file**: Name your Python file `battleship.py`. This should contain the complete implementation of the game logic. 20 | - **README.md (optional)**: If you have any extra explanations, code walkthroughs, or details, include a `README.md` file. However, the main documentation (assignment details) is already in the original repository, so this is optional. 21 | - **How_to_run.txt (optional)**: If necessary, include a short file with instructions on how to run your Python code (if it requires any special setup, dependencies, or environments). 22 | 23 | The final structure of your folder should look like this: 24 | 25 | assignment-repository/ └── John_Doe/ ├── battleship.py ├── README.md (optional) └── How_to_run.txt (optional) 26 | 27 | 28 | 3. **Commit** your changes. 29 | 30 | --- 31 | 32 | ### 4. Push Your Changes to GitHub 33 | 34 | 1. **Push your branch** to your forked repository (or to the repository if you have direct write access). 35 | 2. Make sure the files are pushed to your folder in the main directory. 36 | 37 | --- 38 | 39 | ### 5. Create a Pull Request (PR) 40 | 41 | 1. Go to the **original repository** (the one you forked or were given access to). 42 | 2. Click on **Pull Requests** in the repository. 43 | 3. Create a **new pull request**. 44 | 4. Select your branch (the one where you pushed your folder) and compare it with the `main` branch (or `master` branch, depending on the project setup). 45 | 5. In the pull request description, add a brief message about the work you’ve done, like: 46 | 47 | This pull request contains my solution for the Matrix-based Battleship Game assignment. All files are organized inside my folder "John_Doe". 48 | 49 | 6. **Submit the pull request**. The project maintainer will review your work, and you will be notified once the PR is merged. 50 | 51 | --- 52 | 53 | ### 6. Wait for Feedback 54 | 55 | After submitting your pull request, the project maintainer will review your code. If there are any issues or improvements to make, they will leave feedback. Be ready to make changes and update your pull request if needed. 56 | 57 | --- 58 | 59 | ### 7. Make Sure You Follow the Naming and Folder Structure 60 | 61 | It is **very important** to follow the folder and file naming convention: 62 | - Folder name: **Your full name** (e.g., `John_Doe`) 63 | - Python file: `battleship.py` 64 | - Optional: `README.md` for explanations or extra features. 65 | 66 | This helps in keeping the repository organized and ensures that the project maintainer can easily identify your submission. 67 | 68 | --- 69 | 70 | ### Summary of Submission Process 71 | 72 | 1. Create a folder with **your name** (e.g., `John_Doe`). 73 | 2. Put all your assignment files (e.g., `battleship.py`) in your folder. 74 | 3. Commit and push your changes to your repository. 75 | 4. Create a pull request to the original repository. 76 | 5. Wait for feedback and make any necessary adjustments. 77 | 78 | --- 79 | 80 | Good luck with your assignment! If you have any questions, feel free to reach out. -------------------------------------------------------------------------------- /Assignments/Battleship Game/README.md: -------------------------------------------------------------------------------- 1 | # Matrix-based Battleship Game Assignment 2 | 3 | ## Overview 4 | 5 | In this assignment, you will implement a **text-based Battleship game** in Python, where players take turns to guess the location of their opponent’s ships on two 5x5 grids. The game will also allow players to place their own ships on their own board, adding a layer of strategy. 6 | 7 | You will implement two main modes of play: 8 | - **Single Player**: You will play against the computer. 9 | - **Multiplayer**: Two players can take turns playing against each other. 10 | 11 | The game will feature **turn-based gameplay**. If a player successfully hits a ship, they will get **another turn**. If they miss, the turn will switch to the opponent. 12 | 13 | --- 14 | 15 | ## Game Rules 16 | 17 | ### 1. Board Setup 18 | - The game board of each player is represented by a **5x5 matrix** (grid). 19 | - Initially, each position on the grid is filled with `0` (water), and ships will be placed on the board using `1` to indicate the ship's location. 20 | 21 | ### 2. Ships 22 | - Each player (either human or computer) has **three ships** to place: 23 | - A **large ship** of size **4**. 24 | - A **medium ship** of size **3**. 25 | - A **small ship** of size **2**. 26 | - Ships can be placed **horizontally** or **vertically** on the grid. 27 | 28 | ### 3. Gameplay 29 | - Players take turns to **guess** the opponent’s ship locations. 30 | - If a guess hits a ship, the player will get **another turn** to continue guessing. 31 | - If a guess is a miss, the turn changes to the opponent. 32 | 33 | ### 4. Ending the Game 34 | - The game ends when one player successfully sinks **all** of the opponent’s ships. 35 | - The winner is the player who sinks all of the opponent’s ships first. 36 | 37 | --- 38 | 39 | ## How to Play 40 | 41 | ### 1. Game Setup 42 | - At the beginning of the game, the player will choose between **Single Player** or **Multiplayer** mode: 43 | - **Single Player**: You will play against the computer. 44 | - **Multiplayer**: Two players will take turns guessing the opponent’s ship locations. 45 | 46 | ### 2. Ship Placement 47 | - Each player must place their ships on the grid. 48 | - The player will place ships of sizes **4**, **3**, and **2**. 49 | - For each ship, the player will provide: 50 | - The **starting row and column** for the ship. 51 | - The **direction** (either "horizontal" or "vertical") for placing the ship. 52 | - Ensure that ships do not **overlap** and stay within the **grid boundaries**. 53 | 54 | ### 3. Taking Turns 55 | - Players take turns guessing the coordinates of their opponent's ships. 56 | - For example, you would input a guess such as `(row: 3, column: 2)`. 57 | - If the guess is **correct (hit)**, the player gets **another turn**. 58 | - If the guess is **incorrect (miss)**, the turn switches to the opponent. 59 | 60 | ### 4. Winning the Game 61 | - The game continues until one player has successfully sunk all the opponent’s ships. 62 | - The player who sinks all the ships first is declared the **winner**. 63 | 64 | --- 65 | 66 | ## Steps to Implement the Game 67 | 68 | ### 1. Create the Game Board 69 | - The game board will be one **5x5 grid** (a 2D list in Python) for each player, initially filled with zeros (`0`). 70 | - The ships will be placed in this grid, and their locations will be marked with `1` when placed. 71 | 72 | ### 2. Ship Placement 73 | - The player will place each of their three ships (of sizes 4, 3, and 2) by specifying the starting position and direction. 74 | - **Horizontal** ships will occupy consecutive columns in the same row. 75 | - **Vertical** ships will occupy consecutive rows in the same column. 76 | - The player cannot place ships **outside the grid** or overlap existing ships. 77 | 78 | ### 3. Opponent Ship Placement (Single Player Mode) 79 | - In **Single Player** mode, the opponent's ships will be placed **randomly**. 80 | - The opponent's ships should not overlap or go out of bounds of the grid. 81 | 82 | ### 4. Player Input 83 | - Players will input their guesses in the form of **row** and **column** numbers (from 1 to 5). 84 | - The system will check whether the guessed location is a hit or a miss and return the appropriate response. 85 | 86 | ### 5. Game Loop 87 | - The game will alternate between the two players, allowing each player to guess the location of the opponent's ships. 88 | - If a ship is hit, the player will get an extra turn. 89 | - If a player misses, the turn will switch to the opponent. 90 | 91 | --- 92 | 93 | ## Example Game Flow 94 | 95 | ### 1. Game Start 96 | The game will first prompt the user to select between **Single Player** or **Multiplayer**. 97 | 98 | ``` 99 | Welcome to Battleship! 100 | 101 | Choose game mode: 102 | 103 | 1. singleplayer 104 | 2. multiplayer 105 | 106 | > 1 107 | ``` 108 | 109 | ### 2. Ship Placement 110 | After selecting the game mode, players will be prompted to place their ships one by one. For each ship, the player will need to provide: 111 | - The **starting row and column** for the ship. 112 | - The **direction** (horizontal or vertical). 113 | 114 | ``` 115 | Place your large ship (size 4) 116 | Enter the starting row and column: 117 | > 2 3 118 | Enter direction (horizontal/vertical): 119 | > horizontal 120 | ``` 121 | 122 | This process is repeated for the medium (size 3) and small (size 2) ships. 123 | 124 | ### 3. Taking Turns 125 | Once the ships are placed, players will take turns guessing coordinates. 126 | 127 | ``` 128 | Enter your guess (row 1-5, column 1-5): 129 | > 3 2 130 | Hit! (You hit an opponent's ship) 131 | ``` 132 | If a player hits a ship, they are allowed to take another guess. By each hit, that part of ship will be destroyed. 133 | 134 | ``` 135 | Enter your guess (row 1-5, column 1-5): 136 | > 4 4 137 | Miss! (No ship at this location) 138 | ``` 139 | 140 | The game continues, alternating turns until all ships of one player are sunk. 141 | 142 | ### 4. Game End 143 | The game ends when all of a player's ships have been sunk. The winner is the player who sinks all of their opponent's ships first. 144 | 145 | ``` 146 | Congratulations! You have sunk all the opponent’s ships! You win! 147 | ``` 148 | 149 | --- 150 | 151 | ## Challenge Extensions (Optional) 152 | 153 | After completing the basic game, you can add the following features to enhance the game: 154 | 155 | 1. **AI for Single Player**: 156 | - The computer’s moves can be made more strategic, targeting areas around previously hit ships. 157 | 158 | 2. **Multiple Grid Sizes**: 159 | - Allow the player to choose the size of the grid (e.g., 6x6, 10x10) and adjust the number of ships accordingly. 160 | 161 | 3. **Advanced Multiplayer**: 162 | - Create a server-client architecture to allow two players to play remotely over the internet. 163 | 164 | 4. **Ship Health**: 165 | - Instead of instantly removing a part of ship when it is hit, track the health of each ship and display the health of ship too. 166 | 167 | --- 168 | 169 | ## Submission Instructions 170 | 171 | 1. Implement the **Battleship game** as described in this README. 172 | 2. Submit your **Python file** (`battleship.py`) containing the completed game logic. 173 | 3. If you have added any extra features or enhancements, include those as well. 174 | 4. Ensure that your code is **well-commented**, clearly explaining your approach and logic. 175 | 176 | --- 177 | 178 | ## Grading Criteria 179 | 180 | Your assignment will be graded based on the following criteria: 181 | - Correct implementation of the **game rules** (ship placement, guessing, turn-based system, etc.). 182 | - User interaction: Clear and appropriate **input prompts** and responses (hits, misses). 183 | - Correct handling of **edge cases** (e.g., invalid input, ship overlap, grid boundaries). 184 | - **Code readability**: Well-commented code with appropriate variable names and structure. 185 | - Bonus points for adding **extra features** like AI, multiple grid sizes, or advanced multiplayer. 186 | 187 | --- 188 | 189 | ## Conclusion 190 | 191 | This assignment will help you develop a deeper understanding of **matrix manipulation** in Python, improve your ability to manage **game logic**, and enhance your skills with **conditional checks** and **loops**. It’s a fun way to learn programming while building a classic game like Battleship. 192 | 193 | Good luck, and enjoy coding! 194 | -------------------------------------------------------------------------------- /Assignments/Image Processing Basics/How To Send Answers.txt: -------------------------------------------------------------------------------- 1 | # How to Submit Your Assignment 2 | 3 | Follow these steps to organize and submit your answer for the **Matrix-based Battleship Game** assignment. The submission process involves creating a folder with your name in the assignment repository and sending a **pull request** (PR) to the original repository. 4 | 5 | --- 6 | 7 | ### 1. Create a Folder with Your Name 8 | 9 | 1. Navigate to the assignment repository (the one you have been given access to). 10 | 2. Inside the repository, create a new folder. Name the folder using your **full name** (e.g., "John_Doe" or "Jane_Smith"). 11 | 3. This folder will contain all your work for the assignment. 12 | 13 | --- 14 | 15 | ### 2. Organize Your Files 16 | 17 | Inside your folder (e.g., `John_Doe/`), please add the following files: 18 | 19 | - **Python file**: Name your Python file `battleship.py`. This should contain the complete implementation of the game logic. 20 | - **README.md (optional)**: If you have any extra explanations, code walkthroughs, or details, include a `README.md` file. However, the main documentation (assignment details) is already in the original repository, so this is optional. 21 | - **How_to_run.txt (optional)**: If necessary, include a short file with instructions on how to run your Python code (if it requires any special setup, dependencies, or environments). 22 | 23 | The final structure of your folder should look like this: 24 | 25 | assignment-repository/ └── John_Doe/ ├── battleship.py ├── README.md (optional) └── How_to_run.txt (optional) 26 | 27 | 28 | 3. **Commit** your changes. 29 | 30 | --- 31 | 32 | ### 4. Push Your Changes to GitHub 33 | 34 | 1. **Push your branch** to your forked repository (or to the repository if you have direct write access). 35 | 2. Make sure the files are pushed to your folder in the main directory. 36 | 37 | --- 38 | 39 | ### 5. Create a Pull Request (PR) 40 | 41 | 1. Go to the **original repository** (the one you forked or were given access to). 42 | 2. Click on **Pull Requests** in the repository. 43 | 3. Create a **new pull request**. 44 | 4. Select your branch (the one where you pushed your folder) and compare it with the `main` branch (or `master` branch, depending on the project setup). 45 | 5. In the pull request description, add a brief message about the work you’ve done, like: 46 | 47 | This pull request contains my solution for the Matrix-based Battleship Game assignment. All files are organized inside my folder "John_Doe". 48 | 49 | 6. **Submit the pull request**. The project maintainer will review your work, and you will be notified once the PR is merged. 50 | 51 | --- 52 | 53 | ### 6. Wait for Feedback 54 | 55 | After submitting your pull request, the project maintainer will review your code. If there are any issues or improvements to make, they will leave feedback. Be ready to make changes and update your pull request if needed. 56 | 57 | --- 58 | 59 | ### 7. Make Sure You Follow the Naming and Folder Structure 60 | 61 | It is **very important** to follow the folder and file naming convention: 62 | - Folder name: **Your full name** (e.g., `John_Doe`) 63 | - Python file: `battleship.py` 64 | - Optional: `README.md` for explanations or extra features. 65 | 66 | This helps in keeping the repository organized and ensures that the project maintainer can easily identify your submission. 67 | 68 | --- 69 | 70 | ### Summary of Submission Process 71 | 72 | 1. Create a folder with **your name** (e.g., `John_Doe`). 73 | 2. Put all your assignment files (e.g., `battleship.py`) in your folder. 74 | 3. Commit and push your changes to your repository. 75 | 4. Create a pull request to the original repository. 76 | 5. Wait for feedback and make any necessary adjustments. 77 | 78 | --- 79 | 80 | Good luck with your assignment! If you have any questions, feel free to reach out. -------------------------------------------------------------------------------- /Assignments/Image Processing Basics/README.md: -------------------------------------------------------------------------------- 1 | 2 | # Image Processing Assignment using OpenCV 3 | 4 | ## Objective 5 | The objective of this assignment is to introduce students to basic image processing techniques using **Python** and **OpenCV**. By completing the tasks, students will gain hands-on experience with image manipulation, enhancement, filtering, and transformation. 6 | 7 | --- 8 | 9 | ## Prerequisites 10 | - **Python** installed (>= 3.6) 11 | - **OpenCV** library (cv2) installed 12 | - Basic understanding of image processing concepts and Python programming. 13 | 14 | Install OpenCV using pip if not already installed: 15 | ```bash 16 | pip install opencv-python 17 | ``` 18 | 19 | --- 20 | 21 | ## Tasks 22 | Below are the tasks that need to be implemented as part of the assignment. Each task should use appropriate OpenCV functions and be well-documented with comments. 23 | 24 | ### 1. Adding Noise to an Image 25 | - Implement **Gaussian noise** or **Salt and Pepper noise** to an image. 26 | - Visualize the noisy image alongside the original image. 27 | 28 | ### 2. Edge Detection Using Sobel Operator 29 | - Perform **edge detection** using the Sobel operator. 30 | - Extract both horizontal and vertical edges. 31 | - Display the output images. 32 | 33 | ### 3. Histogram Equalization 34 | - Implement histogram equalization to improve the contrast of an image. 35 | - Compare the histogram before and after equalization. 36 | 37 | ### 4. Histogram Stretching 38 | - Apply histogram stretching to enhance the dynamic range of the image. 39 | - Display the transformed image and histogram. 40 | 41 | ### 5. Blurring Using Gaussian Filter 42 | - Apply a **Gaussian blur** to an image. 43 | - Experiment with different kernel sizes (e.g., 3x3, 5x5, 7x7). 44 | 45 | ### 6. Image Thresholding 46 | - Implement **binary thresholding** and **adaptive thresholding**. 47 | - Visualize the effects on grayscale images. 48 | 49 | ### 7. Image Smoothing 50 | - Apply image smoothing techniques such as **mean filtering**. 51 | - Compare the results with the original image. 52 | 53 | ### 8. Morphological Operations 54 | - Perform morphological operations such as: 55 | - **Erosion** 56 | - **Dilation** 57 | - **Opening** 58 | - **Closing** 59 | - Use a binary image for demonstration. 60 | 61 | ### 9. Contours and Object Detection 62 | - Detect **contours** in an image and draw them on the original image. 63 | - Count the number of detected objects (e.g., using thresholding). 64 | 65 | ### 10. Image Transformation: Rotation and Scaling 66 | - Implement image **rotation** and **scaling** using OpenCV functions. 67 | - Allow the user to specify the rotation angle and scaling factor. 68 | 69 | --- 70 | 71 | ## Instructions 72 | 1. **Input Image**: Use any grayscale or color image of your choice for each task. 73 | 2. **Code Organization**: Write the Python code for each task in a separate function. 74 | 3. **Visualization**: Display the input and output images using `cv2.imshow` or matplotlib. 75 | 4. **Documentation**: Add comments and explanations for each function. 76 | 5. **Submission**: 77 | - Submit your code in a single `.py` file. 78 | - Ensure that the file runs without errors. 79 | - Include a report (PDF or DOC) explaining each task with results (input/output images). 80 | 81 | --- 82 | 83 | ## Expected Output 84 | - For each task, the program should display: 85 | - Input image 86 | - Processed output image 87 | - Screenshots of all results must be included in the final report. 88 | 89 | --- 90 | 91 | ## Example Structure 92 | Below is an example of how the code structure can look: 93 | 94 | ```python 95 | import cv2 96 | import numpy as np 97 | 98 | def add_noise(image): 99 | # Function to add Gaussian noise 100 | pass 101 | 102 | def sobel_edge_detection(image): 103 | # Function to apply Sobel operator 104 | pass 105 | 106 | def histogram_equalization(image): 107 | # Function to perform histogram equalization 108 | pass 109 | 110 | def main(): 111 | image = cv2.imread('input.jpg', 0) # Read image in grayscale 112 | 113 | # Task 1: Adding Noise 114 | noisy_image = add_noise(image) 115 | cv2.imshow('Noisy Image', noisy_image) 116 | 117 | # Task 2: Sobel Edge Detection 118 | sobel_edges = sobel_edge_detection(image) 119 | cv2.imshow('Sobel Edges', sobel_edges) 120 | 121 | # Add other functions here... 122 | 123 | cv2.waitKey(0) 124 | cv2.destroyAllWindows() 125 | 126 | if __name__ == "__main__": 127 | main() 128 | ``` 129 | 130 | --- 131 | 132 | ## Evaluation Criteria 133 | 1. Correctness of code implementation for each task. 134 | 2. Proper organization and modularity of code. 135 | 3. Output image quality and visualization. 136 | 4. Report clarity and explanation. 137 | 138 | 139 | --- 140 | 141 | ## References 142 | - [OpenCV Documentation](https://docs.opencv.org/) 143 | - [Python Programming](https://www.python.org/) 144 | 145 | --- 146 | 147 | Good luck and happy coding! 148 | 149 | --- 150 | -------------------------------------------------------------------------------- /OpenCV Basics/basic_functions.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from consts import path # Import the path of the image to be loaded 4 | 5 | # Read the image from the specified path 6 | img = cv2.imread(path) 7 | 8 | # Split the image into Blue, Green, and Red channels 9 | B, G, R = cv2.split(img) 10 | print(B) # Print the Blue channel to the console 11 | 12 | # Modify Blue and Green channels 13 | B = np.zeros_like(B) # Set all pixels in Blue channel to 0 (black) 14 | G = 255 * np.ones_like(G) # Set all pixels in Green channel to 255 (green) 15 | 16 | # Display individual channels 17 | cv2.imshow("Blue Channel", B) 18 | cv2.imshow("Green Channel", G) 19 | cv2.imshow("Red Channel", R) 20 | 21 | # Merge the modified channels back into a single image 22 | merged_img = cv2.merge([B, G, R]) 23 | cv2.imshow("Merged", merged_img) 24 | 25 | # Convert the image to grayscale 26 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 27 | cv2.imshow('Gray', gray) 28 | 29 | # Apply Gaussian blur to the image 30 | blur = cv2.GaussianBlur(img, (5, 5), cv2.BORDER_DEFAULT) 31 | cv2.imshow('Blur', blur) 32 | 33 | # Apply Canny edge detection to the blurred image 34 | canny = cv2.Canny(blur, 130, 200) 35 | cv2.imshow('Canny Edges', canny) 36 | 37 | # Dilate the edges to make them thicker 38 | dilated = cv2.dilate(canny, kernel=(1, 1), iterations=3) 39 | cv2.imshow('Dilated', dilated) 40 | 41 | # Resize the image to 500x500 pixels using cubic interpolation 42 | resized = cv2.resize(dilated, (500, 500), interpolation=cv2.INTER_CUBIC) 43 | cv2.imshow('Resized', resized) 44 | 45 | # Crop a region of interest from the image 46 | cropped = img[154:602, 335:802] 47 | cv2.imshow('Cropped', cropped) 48 | 49 | # Apply blur, Canny edge detection, and dilation to the cropped image 50 | cropped_blur = cv2.GaussianBlur(cropped, (5, 5), cv2.BORDER_DEFAULT) 51 | canny = cv2.Canny(cropped_blur, 130, 200) 52 | dilated = cv2.dilate(canny, (3, 3), iterations=3) 53 | cv2.imshow('Dilated', dilated) 54 | 55 | # Wait until a key is pressed before closing all windows 56 | cv2.waitKey(0) 57 | -------------------------------------------------------------------------------- /OpenCV Basics/bitwise.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | # Create a blank black image of size 400x400 5 | blank = np.zeros((400, 400), dtype='uint8') 6 | 7 | # Draw a filled white rectangle on the blank image 8 | rectangle = cv2.rectangle(blank.copy(), (30, 30), (370, 370), 255, -1) 9 | 10 | # Draw a filled white circle on the blank image 11 | circle = cv2.circle(blank.copy(), (200, 200), 200, 255, -1) 12 | 13 | # Display the rectangle and circle 14 | cv2.imshow('Rectangle', rectangle) 15 | cv2.imshow('Circle', circle) 16 | 17 | # Perform bitwise AND operation: keeps only the intersecting regions of the rectangle and circle 18 | bitwise_and = cv2.bitwise_and(rectangle, circle) 19 | cv2.imshow('Bitwise AND', bitwise_and) 20 | 21 | # Perform bitwise OR operation: combines the non-intersecting and intersecting regions of the rectangle and circle 22 | bitwise_or = cv2.bitwise_or(rectangle, circle) 23 | cv2.imshow('Bitwise OR', bitwise_or) 24 | 25 | # Perform bitwise XOR operation: keeps only the non-intersecting regions of the rectangle and circle 26 | bitwise_xor = cv2.bitwise_xor(rectangle, circle) 27 | cv2.imshow('Bitwise XOR', bitwise_xor) 28 | 29 | # Perform bitwise NOT operation: inverts the bits of the circle 30 | bitwise_not = cv2.bitwise_not(circle) 31 | cv2.imshow('Circle NOT', bitwise_not) 32 | 33 | # Wait until a key is pressed before closing all windows 34 | cv2.waitKey(0) 35 | -------------------------------------------------------------------------------- /OpenCV Basics/consts.py: -------------------------------------------------------------------------------- 1 | path = 'PUT_THE_PATH_OF_THE_IMAGE_HERE' -------------------------------------------------------------------------------- /OpenCV Basics/draw.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | # Create a blank black image of size 500x500 5 | blank = np.zeros((500, 500, 3), dtype='uint8') 6 | cv2.imshow('Blank', blank) 7 | 8 | # 1. Paint a section of the image yellow (RGB: 0,255,255) 9 | blank[200:300, 300:400] = 0, 255, 255 10 | cv2.imshow('Yellow', blank) 11 | 12 | # 2. Draw a filled green rectangle (top-left: (0,0), bottom-right: half of the image size) 13 | cv2.rectangle(blank, (0, 0), (blank.shape[1]//2, blank.shape[0]//2), (0, 255, 0), thickness=-1) 14 | cv2.imshow('Rectangle', blank) 15 | 16 | # 3. Draw a filled red circle at the center of the image with a radius of 40 pixels 17 | cv2.circle(blank, (blank.shape[1]//2, blank.shape[0]//2), 40, (0, 0, 255), thickness=-1) 18 | cv2.imshow('Circle', blank) 19 | 20 | # 4. Draw a white line from point (100, 250) to (300, 400) 21 | cv2.line(blank, (100, 250), (300, 400), (255, 255, 255), thickness=3) 22 | cv2.imshow('Line', blank) 23 | 24 | # 5. Write text "Hello, my name is Aryan!!!" at the specified location with white color 25 | cv2.putText(blank, 'Hello, my name is Aryan!!!', (0, 100), cv2.FONT_HERSHEY_TRIPLEX, 1.0, (255, 255, 255), 2) 26 | cv2.imshow('Text', blank) 27 | 28 | # Wait until a key is pressed before closing all windows 29 | cv2.waitKey(0) 30 | -------------------------------------------------------------------------------- /OpenCV Basics/hidden_image.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | # Function to hide an image inside another image using LSB encoding 6 | def hide_image_inside_another_image(cover_image, hidden_image, wants_save_image=1): 7 | # Resize hidden image to match the cover image dimensions 8 | hidden_image = cv2.resize(hidden_image, cover_image.shape[::-1]) 9 | 10 | # Clear the least significant bit (LSB) of the cover image 11 | cover_image = cover_image & 0b11111110 12 | 13 | # Shift the hidden image to the LSB 14 | hidden_image = hidden_image >> 7 15 | 16 | # Combine both images using bitwise OR 17 | final_image = cover_image | hidden_image 18 | 19 | if wants_save_image: 20 | cv2.imwrite('final_image.png', final_image) # Save the stego image in a lossless format 21 | 22 | return final_image 23 | 24 | # Function to extract the hidden image from the stego image 25 | def extract_hidden_image(image, wants_save_image=1): 26 | # Extract the least significant bit from the image 27 | hidden_image = image & 0b00000001 28 | 29 | # Scale back to the 0-255 range for visualization 30 | hidden_image = hidden_image * 255 31 | 32 | if wants_save_image: 33 | cv2.imwrite('extracted_hidden_image.png', hidden_image) # Save the extracted hidden image 34 | 35 | return hidden_image 36 | 37 | # Paths to the cover and hidden images 38 | cover_image_path = 'img/Tehran.jpg' 39 | hidden_image_path = 'img/WW0.jpg' 40 | 41 | # Load the images (grayscale) 42 | cover_image = cv2.imread(cover_image_path, cv2.IMREAD_GRAYSCALE) 43 | hidden_image = cv2.imread(hidden_image_path, cv2.IMREAD_GRAYSCALE) 44 | 45 | # Step 1: Embed the hidden image into the cover image 46 | stego_image = hide_image_inside_another_image(cover_image, hidden_image, wants_save_image=1) 47 | 48 | # Step 2: Extract the hidden image from the stego image 49 | extracted_image = extract_hidden_image(stego_image) 50 | 51 | # Step 3: Display the images using Matplotlib 52 | fig, axes = plt.subplots(1, 3, figsize=(15, 5)) 53 | axes[0].imshow(cover_image, cmap='gray') 54 | axes[0].set_title("Cover Image") 55 | axes[1].imshow(stego_image, cmap='gray') 56 | axes[1].set_title("Stego Image (With Hidden Image)") 57 | axes[2].imshow(extracted_image, cmap='gray') 58 | axes[2].set_title("Extracted Hidden Image") 59 | 60 | plt.show() 61 | -------------------------------------------------------------------------------- /OpenCV Basics/noise.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from consts import path # Import image path 5 | 6 | # Function to add Gaussian noise to an image 7 | def add_gaussian_noise(image, mean=0, std=25): 8 | noise = np.random.normal(mean, std, image.shape).astype(np.uint8) 9 | noisy_image = cv2.add(image, noise) # Add noise to the original image 10 | return noisy_image 11 | 12 | # Function to add salt-and-pepper noise to an image 13 | def add_salt_and_pepper_noise(image, noise_ratio=0.1): 14 | noisy_image = image.copy() 15 | h, w, c = noisy_image.shape 16 | noisy_pixels = int(h * w * noise_ratio) 17 | 18 | for _ in range(noisy_pixels): 19 | row, col = np.random.randint(0, h), np.random.randint(0, w) 20 | if np.random.rand() < 0.5: 21 | noisy_image[row, col] = [0, 0, 0] # Black pixel (salt) 22 | else: 23 | noisy_image[row, col] = [255, 255, 255] # White pixel (pepper) 24 | 25 | return noisy_image 26 | 27 | # Load the original image 28 | original_image = cv2.imread(path) 29 | 30 | # Add Gaussian and salt-and-pepper noise to the image 31 | noisy_image_gauss = add_gaussian_noise(original_image, mean=0, std=25) 32 | noisy_image_salt = add_salt_and_pepper_noise(original_image) 33 | 34 | # Display the original image and the noisy images 35 | fig, axes = plt.subplots(1, 3, figsize=(10, 20)) 36 | fig.suptitle('Image Processing Results') 37 | axes[0].imshow(original_image) 38 | axes[0].set_title("Original Image") 39 | axes[0].axis('off') 40 | axes[1].imshow(noisy_image_gauss) 41 | axes[1].set_title("Gaussian Noise") 42 | axes[1].axis('off') 43 | axes[2].imshow(noisy_image_salt) 44 | axes[2].set_title("Salt & Pepper Noise") 45 | axes[2].axis('off') 46 | 47 | plt.show() 48 | -------------------------------------------------------------------------------- /OpenCV Basics/read.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | from consts import path 3 | 4 | # Read the image from the specified path 5 | my_img = cv2.imread(path) 6 | 7 | # Display the image in a window named 'Frame Name' 8 | cv2.imshow("Frame Name", my_img) 9 | 10 | # Open the default camera (index 0) 11 | cap = cv2.VideoCapture(0) 12 | 13 | RUN = True # Flag to control the while loop 14 | 15 | while RUN: 16 | # Capture a frame from the video stream 17 | is_true, frame = cap.read() 18 | 19 | if is_true: # If the frame was successfully captured 20 | # Show the captured video frame in a window named 'Video' 21 | cv2.imshow('Video', frame) 22 | 23 | # If the 'q' key is pressed, exit the loop 24 | if cv2.waitKey(20) & 0xFF == ord('q'): 25 | break 26 | else: 27 | break # If frame capture fails, break the loop 28 | 29 | # Release the video capture object and close all OpenCV windows 30 | cap.release() 31 | cv2.destroyAllWindows() 32 | -------------------------------------------------------------------------------- /OpenCV Basics/requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python==4.10.0.84 2 | numpy==1.26.4 3 | matplotlib==3.8.4 4 | -------------------------------------------------------------------------------- /OpenCV Basics/transformation.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from consts import path # Import image path 4 | 5 | # Load the image to be transformed 6 | img = cv2.imread(path) 7 | cv2.imshow('Original', img) 8 | 9 | # Function to rotate an image by a specified angle 10 | def rotate(img, angle, rotPoint=None): 11 | (height, width) = img.shape[:2] # Get the image dimensions 12 | 13 | # If no rotation point is specified, use the center of the image 14 | if rotPoint is None: 15 | rotPoint = (width // 2, height // 2) 16 | 17 | # Get the rotation matrix 18 | rotMat = cv2.getRotationMatrix2D(rotPoint, angle, 1.0) 19 | 20 | # Apply the rotation transformation 21 | return cv2.warpAffine(img, rotMat, (width, height)) 22 | 23 | # Rotate the image by -45 degrees and display the result 24 | rotated = rotate(img, -45) 25 | cv2.imshow('Rotated', rotated) 26 | 27 | # Rotate the image by -90 degrees and display the result 28 | rotated_rotated = rotate(img, -90) 29 | cv2.imshow('Rotated Rotated', rotated_rotated) 30 | 31 | # Flip the image both horizontally and vertically 32 | flip = cv2.flip(img, -1) 33 | cv2.imshow('Flip', flip) 34 | 35 | # Wait until a key is pressed before closing all windows 36 | cv2.waitKey(0) 37 | --------------------------------------------------------------------------------