What is gamma correction?

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.

Implementation of gamma correction
Implementation of gamma correction

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.

How it works

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 s=crγs=c*r^\gamma, where the brightness of each pixel cc is raised to γ\gamma to generate the value of the transformed pixel ss.

Gamma (γ\gamma) is a key parameter that determines how the image will be adjusted. Different gamma values can result in various degrees of correction, affecting the image’s contrast and overall appearance.

Process of gamma correction
Process of gamma correction

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.

Benefits

Gamma correction is crucial for several reasons:

  1. 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.

  2. It helps maintain consistency in image rendering across various devices, preventing images from appearing too dark or washed out.

  3. 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.

Implementation

Let’s look at the code for implementing gamma correction in Python using OpenCV.

import numpy as np
import cv2
import matplotlib.pyplot as plt
# Step 1: Generate a Synthetic Image
def generate_image(size=(256, 256)):
"""Generate a colorful radial gradient image."""
rows, cols = size
center_x, center_y = cols / 2, rows / 2
max_radius = np.sqrt(center_x**2 + center_y**2)
# Create an empty image with 3 color channels
image = np.zeros((rows, cols, 3), dtype=np.uint8)
for y in range(rows):
for x in range(cols):
dx = x - center_x
dy = y - center_y
distance = np.sqrt(dx**2 + dy**2)
normalized_distance = distance / max_radius
# Assign colors based on distance
image[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 Correction
def gamma_correction(image, gamma):
inv_gamma = 1.0 / gamma
table = 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 Correlation
def compute_correlation(image1, image2):
# Flatten the images to 1D arrays
flat_image1 = image1.flatten()
flat_image2 = image2.flatten()
# Compute correlation coefficient
correlation_matrix = np.corrcoef(flat_image1, flat_image2)
correlation = correlation_matrix[0, 1]
return correlation
# Main execution
if __name__ == "__main__":
# Generate image
original_image = generate_image()
# Apply gamma correction
gamma_value = 2.2
corrected_image = gamma_correction(original_image, gamma_value)
# Compute correlation
correlation = compute_correlation(original_image, corrected_image)
# Plot the images
plt.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 image
plt.savefig('output/line_plot.png')

Code explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved