SoFunction
Updated on 2025-04-15

Common ways to improve picture clarity using python

In Python, improving image clarity can be achieved through a variety of methods, some of which include using image processing libraries such as OpenCV and Pillow, and deep learning libraries such as TensorFlow or PyTorch for more advanced image enhancement. Here are some common methods:

Method 1: Use the Pillow library

Pillow is a very popular Python image processing library that can be used to adjust the contrast, sharpening, etc. of pictures, thereby improving the clarity of pictures to a certain extent.

from PIL import Image, ImageEnhance, ImageFilter
 
# Open the pictureimage = ("path_to_your_image.jpg")
 
# Increase contrastenhancer = (image)
image_enhanced = (2)  #2 is the contrast factor, which can be adjusted 
# Sharpen picturesimage_sharp = image_enhanced.filter()
 
# Save the processed pictureimage_sharp.save("path_to_save_enhanced_image.jpg")

Method 2: Use OpenCV library

OpenCV is an open source computer vision and machine learning software library that also provides operations such as image sharpening.

import cv2
import numpy as np
 
# Read picturesimage = ("path_to_your_image.jpg")
 
# Convert to grayscale (optional, sharpening is usually operated on grayscale)gray = (image, cv2.COLOR_BGR2GRAY)
 
# Use sharpening cores for sharpening processingkernel_sharpening = ([[-1,-1,-1], 
                             [-1, 9,-1],
                             [-1,-1,-1]])
sharpened = cv2.filter2D(gray, -1, kernel_sharpening)
 
# Convert grayscale back to color image (if needed)sharpened_color = (sharpened, cv2.COLOR_GRAY2BGR)
 
# Save the processed picture("path_to_save_enhanced_image.jpg", sharpened_color)

Method 3: Use deep learning methods (e.g. using TensorFlow or PyTorch)

For more advanced image enhancement, deep learning models can be used, such as style transfer or Super-Resolution using pre-trained models. This usually requires more computing resources and data.

Image super-resolution using TensorFlow's Keras:

import tensorflow as tf
from .vgg16 import VGG16, preprocess_input
from  import Model
from  import Input, Conv2D, UpSampling2D, concatenate
import numpy as np
import cv2
 
# Load the pre-trained VGG16 model (for feature extraction)base_model = VGG16(weights='imagenet', include_top=False, input_shape=(None, None, 3))
base_output = base_model.output
base_model.trainable = False  # Freeze VGG16 layer to save memory and speed up processing 
# Define super-resolution model structure (This is an example only, the actual model may require more complex structures)input_img = Input(shape=(None, None, 3))
x = Conv2D(64, (3, 3), activation='relu', padding='same')(input_img)
x = UpSampling2D()(x)  # Upsampling to increase image size, usually multiple upsampling and convolutional layers are combined for better results.x = Conv2D(64, (3, 3), activation='relu', padding='same')(x)
x = UpSampling2D()(x)  # Upsample again to further increase image size and sharpness.output_img = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)  # Output layer, pay attention to the activation function selection according to the requirements.model = Model(input_img, output_img)  # Create a model instance.(optimizer='adam', loss='mse')  # Compile the model and select the appropriate loss function. 
# Load and preprocess the image (for example only, it needs to be adjusted according to the dataset when actually using it)image = ("path_to_your_image.jpg")
image = (image, (256, 256))

Knowledge extension

Method 1: Use interpolation methods (such as bilinear interpolation, bicubital interpolation)

Interpolation is a simple method of image amplification, suitable for quick implementation, but may lose some details.

from PIL import Image

# Open the imageimage = ("input_image.jpg")

# Set the target resolution (width, height)target_size = (1920, 1080)  # For example, zoom in to 1920x1080
# Use bicubital interpolation to enlarge the imageresized_image = (target_size, )

# Save the resultsresized_image.save("output_image_high_res.jpg")

Interpolation method description:

  • : Nearest neighbor interpolation (fastest speed and lowest quality).
  • : Bilinear interpolation (medium quality).
  • : Binary interpolation (higher quality, recommended).
  • : Lanczos interpolation (highest quality, but slower calculation).

Method 2: Use deep learning models (such as ESRGAN, SRCNN)

Deep learning models can generate higher quality images, suitable for scenes that require high fidelity.

Use OpenCV and TensorFlow to achieve super resolution:

Installation dependencies:

pip install opencv-python tensorflow

Using pre-trained deep learning models:

import cv2
import tensorflow as tf
import numpy as np

# Load pretrained super-resolution modelmodel = .load_model("pretrained_esrgan_model.h5")  # Replace with your model path
# Read the imageimage = ("input_image.jpg")
image = (image, cv2.COLOR_BGR2RGB)  # Convert to RGB formatimage = image / 255.0  # Normalization
# Resize the image to the model input sizeinput_image = np.expand_dims(image, axis=0)  # Add batch dimensions
# Predict high-resolution images using modelshigh_res_image = (input_image)

# Post-processinghigh_res_image = (high_res_image, axis=0)  # Remove batch dimensionshigh_res_image = (high_res_image * 255).astype(np.uint8)  # Reverse Normalization
# Save the results("output_image_high_res.jpg", (high_res_image, cv2.COLOR_RGB2BGR))

Model description:

  • ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks, generate high-quality super-resolution images.
  • SRCNN: Super-Resolution Convolutional Neural Network, a classic super-resolution model.
  • You can download pretrained models from open source communities such as TensorFlow Hub or GitHub.

Method 3: Use the ready-made super-resolution toolkit

Some ready-made toolkits (such as OpenCV's dnn_superres module) can easily achieve super resolution.

Installation dependencies:

pip install opencv-python opencv-contrib-python

Using dnn_superres:

import cv2

# Create a super-resolution objectsr = cv2.dnn_superres.DnnSuperResImpl_create()

# Load the pretrained modelmodel_path = "EDSR_x4.pb"  # Replace with your model path(model_path)
("edsr", 4)  # Set model type and magnification
# Read the imageimage = ("input_image.jpg")

# Perform super resolutionhigh_res_image = (image)

# Save the results("output_image_high_res.jpg", high_res_image)

Model description:

Pre-trained models (such as EDSR, ESPCN, FSRCNN, etc.) can be downloaded from OpenCV official resources.

Summarize

Interpolation method: simple and fast, suitable for general needs, but the details may be insufficient.

Deep Learning Model: Generate high-quality images that are suitable for high-fidelity needs, but require more computing resources.

Ready-to-shelf toolkit: such as OpenCV's dnn_superres, which is easy to use and suitable for quick implementation.

Choose the right method according to your needs! If high-quality results are required, deep learning models are recommended.

If you want to directly modify the resolution of the image (i.e. adjust the width and height of the image), you can use OpenCV's resize function. This approach enlarges or reduces the image by interpolation, but does not increase the detail of the image (i.e. does not really improve the quality of the image). Here is a code example:

Code: Use OpenCV to modify image resolution

import cv2

# Read the imageimage = ("input_image.jpg")

# Set the target resolution (width, height)target_width = 1920  # Target Widthtarget_height = 1080  # Target heighttarget_size = (target_width, target_height)

# Use OpenCV's resize function to adjust resolutionresized_image = (image, target_size, interpolation=cv2.INTER_CUBIC)

# Save the results("output_image_resized.jpg", resized_image)

# Show results (optional)("Resized Image", resized_image)
(0)
()

Parameter description

1.target_size:

  • Target resolution, format (width, height).
  • For example (1920, 1080) means adjusting the image to a resolution of 1920x1080.

Interpolation method, used to determine how to calculate the value of a new pixel. Commonly used interpolation methods include:

  • cv2.INTER_NEAREST: Nearest neighbor interpolation (fastest, lowest quality).
  • cv2.INTER_LINEAR: Bilinear interpolation (default, faster speed, better quality).
  • cv2.INTER_CUBIC: Binary interpolation (slower speed, higher quality).
  • cv2.INTER_LANCZOS4: Lanczos interpolation (slowest speed, best quality).

Things to note

Zoom in the image:

  • If the target resolution is larger than the original image, OpenCV fills the new pixels with interpolation, but does not add details to the image.
  • The enlarged image may appear blurry.

Reduce the image:

If the target resolution is smaller than the original image, OpenCV discards some pixels and the image becomes smaller, but some details may be lost.

Maintain aspect ratio:

If you want to maintain the aspect ratio of the image while adjusting the resolution, you can calculate the scaling ratio first and then adjust the resolution. For example:

original_height, original_width = [:2]
scale_percent = 50  # Shrink to 50%target_width = int(original_width * scale_percent / 100)
target_height = int(original_height * scale_percent / 100)
target_size = (target_width, target_height)

Summarize

Use the image resolution can be directly modified, but the image details are not added.

If high-quality super-resolution effects are required, deep learning models (such as ESRGAN, SRCNN, etc.) are recommended.

This is the article about common methods to improve picture clarity using python. For more related content on python to improve picture clarity, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!