This project demonstrates a basic image compression technique using Principal Component Analysis (PCA) in Python. It reads an input image, applies PCA to reduce its dimensionality, and then visualizes the compressed image.
Make sure you have the following Python libraries installed:
numpy
matplotlib
opencv-python
scikit-learn
(for PCA)
You can install these libraries using pip
if you don't have them already:
pip install numpy matplotlib opencv-python scikit-learn
doraemon.jpg
: The input image you want to compress.cat.jpg
: An example of the compressed image (you can rename it to save the compressed result).Imagecompression.jpg
: An example of the compressed image generated by the script.
-
Place your desired input image (e.g.,
doraemon.jpg
) in the same directory as this script. -
Run the script. It will read the input image, apply PCA-based compression, and display the compressed image.
-
You can adjust the compression level by modifying the
compress
function argument. For example,compress(10)
will compress the image using only 10% of the principal components.
Here's an example of how to use the script:
# Import the necessary libraries
import numpy as np
from numpy.linalg import svd
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import cv2
# Define the show_image function
# Load the input image (e.g., 'doraemon.jpg') and convert it to RGB
orig = cv2.imread('doraemon.jpg')
rgb_image = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)
# Display the original image
show_image(rgb_image)
# Perform PCA-based compression
compress(10) # Adjust the compression percentage as needed
-
The script will display the original image and the compressed image using PCA. You can save the compressed image for further use by renaming it (e.g.,
cat.jpg
). -
Depending on the compression level, you may need to fine-tune the number of principal components used in the
compress
function to achieve the desired compression ratio. -
The script is provided as a basic example of PCA-based image compression and can be extended or modified for more advanced use cases.