SoFunction
Updated on 2025-04-10

Four ways to improve picture clarity in Python

1. Installation of the library

Library use Install
pillow Picture related pip install pillow -i /simple/
cv2 View related pip install opencv-python -i /simple/
torch View related ppip install torch -i /simple/
torchvision View related ppip install torchvision -i /simple/

2. Implementation method

Method 1—PIL

Library use Install
pillow Picture related pip install pillow -i /simple/

Sample code

from PIL import Image, ImageFilter

# Open the pictureimage = ('input_image.jpg')

# Apply sharp filterssharpened_image = ()

# Save the resultssharpened_image.save('sharpened_image.jpg')

Method 2—cv2

Library use Install
cv2 View related pip install opencv-python -i /simple/

Sample code

import cv2
import numpy as np

# Read picturesimage = ('input_image.jpg')

# Gaussian blurblurred = (image, (0, 0), 3)

# Sharpensharpened = (image, 1.5, blurred, -0.5, 0)

# Save the results('sharpened_image.jpg', sharpened)

Method 3—torch

Library use Install
cv2 View related pip install opencv-python -i /simple/
torch View related ppip install torch -i /simple/
torchvision View related ppip install torchvision -i /simple/

Sample code

import cv2
import torch
from  import ToTensor, ToPILImage

# Load the pretrained ESRGAN modelmodel = ('xinntao/ESRGAN', 'esrgan', pretrained=True)
()

# Read picturesimage = ('input_image.jpg')
image = (image, cv2.COLOR_BGR2RGB)
image = ToTensor()(image).unsqueeze(0)

# Use the model for super resolutionwith torch.no_grad():
    output = model(image)

# Save the resultsoutput_image = ToPILImage()((0))
output_image.save('super_resolution_image.jpg')

Method 4—waifu2x

Library use Install
waifu2x View related ppip install waifu2x -i /simple/

Sample code

from waifu2x import Waifu2x

# Create a waifu2x objectwaifu2x = Waifu2x()

# Improve image claritywaifu2x.upscale_image('input_image.jpg', 'output_image.jpg')

This is the end of this article about four methods to improve picture clarity in 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!