Let's break down how to achieve these image processing tasks using OpenCV.
Important Note: OpenCV is a powerful library, but it's best to understand the concepts before diving into code.
1. Histogram Equalization
python Copy code
import cv2
import numpy as np
# Load the image
image = cv2.imread('input_image.jpg')
# Convert to grayscale (if needed)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Calculate the histogram
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
# Normalize the histogram
hist = hist / hist.sum()
# Apply histogram equalization
equalized = cv2.equalizeHist(gray)
# Display the results
cv2.imshow('Original Image', image)
cv2.imshow('Equalized Image', equalized)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation:
cv2.imread(): Loads the image.
cv2.cvtColor(): Converts the image to grayscale if needed.
cv2.calcHist(): Calculates the histogram of the image.
cv2.equalizeHist(): Performs histogram equalization.
cv2.imshow(): Displays the images.
cv2.waitKey(0): Waits for a key press.
cv2.destroyAllWindows(): Closes the display windows.
2. Histogram Specification
python Copy code
import cv2
import numpy as np
# Load the images
input_image = cv2.imread('input_image.jpg')
reference_image = cv2.imread('reference_image.jpg')
# Convert to grayscale
input_gray = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
reference_gray = cv2.cvtColor(reference_image, cv2.COLOR_BGR2GRAY)
# Calculate histograms
input_hist = cv2.calcHist([input_gray], [0], None, [256], [0, 256])
reference_hist = cv2.calcHist([reference_gray], [0], None, [256], [0, 256])
# Display histograms
cv2.imshow('Input Histogram', input_hist)
cv2.imshow('Reference Histogram', reference_hist)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation:
cv2.calcHist(): Calculates the histogram of the image.
cv2.imshow(): Displays the histograms.
3. Resizing and Cropping
python Copy code
import cv2
# Load the image
image = cv2.imread('input_image.jpg')
# Resize the image
resized = cv2.resize(image, (500, 300))
# Crop the image
cropped = image[100:200, 50:250]
# Display the results
cv2.imshow('Original Image', image)
cv2.imshow('Resized Image', resized)
cv2.imshow('Cropped Image', cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
Explanation:
cv2.resize(): Resizes the image.
cv2.imread(): Loads the image.
cv2.cvtColor(): Converts the image to grayscale if needed.
cv2.imshow(): Displays the images.
cv2.waitKey(0): Waits for a key press.
cv2.destroyAllWindows(): Closes the display windows.
Key Points:
OpenCV Documentation: https://docs.opencv.org/
Image Formats: OpenCV supports many image formats (JPEG, PNG, TIFF, etc.).
Image Processing: OpenCV provides a wide range of image processing functions.
Experimentation: Try different parameters and techniques to achieve the desired results.
Let me know if you'd like to explore any of these concepts in more detail!