Gamma correction is a crucial concept in digital image processing that addresses the differences between how a camera captures images and how a device displays those images to viewers. It involves adjusting the brightness and contrast of an image to ensure that it appears as intended to the human eye.
Observe how gamma correction enhances the color harmony and detail visibility of the image above, improving the overall image quality with minimal adjustments. Not correctly updating the monitor’s gamma value can result in inaccurate lighting representation, making it hard to achieve realistic and appealing results.
The primary issue addressed by gamma correction is that display devices, including computer monitors, do not respond linearly to different levels of pixel intensities in the input signal. This non-linearity can cause images to appear too dark or washed out on the screen, which is not consistent with how our eyes perceive brightness and contrast.
In order to correct this non-linearity, a logarithmic transformation is applied to the input signal before it is displayed on the monitor. This is implemented using the power-law equation
Gamma (
Gamma correction is achieved by mapping the input values through a correction function tailored to the characteristics of the display device before sending them to the display device. This transformation compresses the higher intensity levels, making them appear less bright, and stretches the lower intensity levels, making them appear brighter.
The choice of gamma value is device-dependent, with various imaging devices like cameras, displays, scanners, and printers having unique gamma characteristics. As a result, each device may necessitate specific gamma correction to ensure the visual accuracy and consistency of the images they produce or display.
Gamma correction is crucial for several reasons:
Human vision is not linear; our eyes perceive changes in brightness and contrast nonlinearly. Gamma correction helps ensure that images appear perceptually uniform to viewers.
It helps maintain consistency in image rendering across various devices, preventing images from appearing too dark or washed out.
Gamma correction is closely related to color accuracy and affects how colors are displayed. Proper gamma correction can help preserve an image’s color fidelity.
Let’s look at the code for implementing gamma correction in Python using OpenCV.
import numpy as npimport cv2import matplotlib.pyplot as plt# Step 1: Generate a Synthetic Imagedef generate_image(size=(256, 256)):"""Generate a colorful radial gradient image."""rows, cols = sizecenter_x, center_y = cols / 2, rows / 2max_radius = np.sqrt(center_x**2 + center_y**2)# Create an empty image with 3 color channelsimage = np.zeros((rows, cols, 3), dtype=np.uint8)for y in range(rows):for x in range(cols):dx = x - center_xdy = y - center_ydistance = np.sqrt(dx**2 + dy**2)normalized_distance = distance / max_radius# Assign colors based on distanceimage[y, x] = [int(normalized_distance * 255), int((1 - normalized_distance) * 255), int(np.sin(normalized_distance * np.pi) * 255)]return image# Step 2: Apply Gamma Correctiondef gamma_correction(image, gamma):inv_gamma = 1.0 / gammatable = np.array([(i / 255.0) ** inv_gamma * 255 for i in np.arange(0, 256)]).astype("uint8")return cv2.LUT(image, table)# Step 3: Compute Correlationdef compute_correlation(image1, image2):# Flatten the images to 1D arraysflat_image1 = image1.flatten()flat_image2 = image2.flatten()# Compute correlation coefficientcorrelation_matrix = np.corrcoef(flat_image1, flat_image2)correlation = correlation_matrix[0, 1]return correlation# Main executionif __name__ == "__main__":# Generate imageoriginal_image = generate_image()# Apply gamma correctiongamma_value = 2.2corrected_image = gamma_correction(original_image, gamma_value)# Compute correlationcorrelation = compute_correlation(original_image, corrected_image)# Plot the imagesplt.figure(figsize=(12, 6))plt.subplot(1, 2, 1)plt.title("Original Image")plt.imshow(original_image, cmap='gray')plt.axis('off')plt.subplot(1, 2, 2)plt.title(f"Gamma Corrected Image (Gamma={gamma_value})")plt.imshow(corrected_image, cmap='gray')plt.axis('off')plt.suptitle(f"Correlation between Original and Gamma Corrected Image: {correlation:.4f}")plt.show()# Save the plot as imageplt.savefig('output/line_plot.png')
Import libraries: The script imports essential libraries for numerical operations (numpy
), image processing (cv2
), and plotting (matplotlib.pyplot
).
Generate a synthetic image:
The generate_image
function creates a radial gradient image. The gradient’s intensity varies with the distance from the image’s center, producing a colorful pattern.
An empty image with three color channels (RGB) is initialized. Each pixel’s color is determined based on its distance from the center, creating the gradient effect.
Apply gamma correction:
The gamma_correction
function adjusts the image’s brightness. Gamma correction is applied to make the image appear lighter or darker based on the gamma value provided.
A lookup table (LUT) is created to map the original pixel values to the gamma-corrected values, and this LUT is applied to the image using OpenCV’s cv2.LUT
function.
Compute correlation:
The compute_correlation
function calculates the correlation between the original and gamma-corrected images to quantify how similar they are.
Both images are flattened into 1D arrays, and the correlation coefficient is computed using NumPy’s np.corrcoef
function.
Visualize and save results:
The script uses Matplotlib to plot the original and gamma-corrected images side by side. It also displays the correlation coefficient in the plot’s title.
Finally, the plot is saved as an image file for future reference.
Free Resources