import cv2
def resize_and_crop(image_path, new_size, crop_rect):
# Read the image
img = cv2.imread(image_path)
# Resize the image
resized_img = cv2.resize(img, new_size)
# Crop the resized image
x, y, w, h = crop_rect
cropped_img = resized_img[y:y+h, x:x+w]
# Display original, resized, and cropped images
cv2.imshow('Original', img)
cv2.imshow('Resized', resized_img)
cv2.imshow('Cropped', cropped_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
image_path = 'input_image.jpg'
new_size = (640, 480) # width, height
crop_rect = (100, 100, 300, 200) # x, y, w, h
resize_and_crop(image_path, new_size, crop_rect)
Explanation and Notes:
Histogram Equalization: The cv2.equalizeHist function applies histogram equalization to the input grayscale image, stretching the histogram to improve contrast.
Histogram Specification: This implementation follows the traditional approach:
Calculate histograms and normalize them.
Compute cumulative distribution functions (CDFs).
Create a lookup table (LUT) by finding the closest match between the input CDF and reference CDF.
Apply the LUT to the input image.
Resizing and Cropping:
cv2.resize resizes the image to the specified new_size.
Cropping uses NumPy array slicing to extract the desired region from the resized image.
Adjust new_size and crop_rect according to your specific requirements.
Tips and Variations:
For color images, convert to grayscale before applying histogram equalization or specification.
In histogram specification, you can use other distance metrics (e.g., KL-divergence) or optimization techniques (e.g., histogram matching) for better results.
For resizing, consider using cv2.INTER_AREA or cv2.INTER_LANCZOS4 interpolation for better quality.
Add error handling for invalid image paths, sizes, or crop rectangles.
Explore other OpenCV functions, such as cv2.createCLAHE for adaptive histogram equalization, or cv2.getOptimalNewCameraMatrix for more advanced image resizing.