search
HomeBackend DevelopmentPython TutorialHow to color match images using Python

How to color match images using Python

Aug 19, 2023 pm 02:10 PM
pythonpicturecolor matching

How to color match images using Python

How to use Python to color match images

Introduction:
In modern society, image processing has been widely used in many fields, such as movie special effects, medicine Image diagnosis, etc. Among them, image color matching is an important technology, which can make the colors between different pictures consistent, thereby improving user experience. This article will introduce how to use Python to color match images, and explain it in detail through code examples.

1. Install dependent libraries

Before we begin, we need to ensure that the Python environment has been installed and the PIL library (Python Imaging Library) has been installed. If the PIL library is not installed, you can install it through the following command:

pip install pillow

2. Read the image data

First, we need to read the data of the image to be matched and the reference image, and add Convert it into a data structure that can be manipulated. Suppose we have two pictures: image.jpg is the picture to be matched, reference.jpg is the reference picture, the code example is as follows:

from PIL import Image

def read_image(filename):
    image = Image.open(filename)
    data = list(image.getdata())
    width, height = image.size
    return data, width, height

image_data, image_width, image_height = read_image('image.jpg')
reference_data, reference_width, reference_height = read_image('reference.jpg')

3. Calculate each The average and standard deviation of each channel

In order to achieve color matching, we need to calculate the average and standard deviation of each channel of the image to be matched and the reference image. The code example is as follows:

import numpy as np

def calculate_mean_std(data):
    pixels = np.array(data, dtype=np.float32)
    mean = np.mean(pixels, axis=0)
    std = np.std(pixels, axis=0)
    return mean, std

image_mean, image_std = calculate_mean_std(image_data)
reference_mean, reference_std = calculate_mean_std(reference_data)

4. Color matching

With the mean and standard deviation of each channel, we can use the following formula for color matching:

matched_data = (image_data - image_mean) / image_std * reference_std + reference_mean

The code example is as follows:

def match_color(data, mean, std, reference_mean, reference_std):
    matched_data = np.array(data, dtype=np.float32)
    matched_data = (matched_data - mean) / std * reference_std + reference_mean
    matched_data = matched_data.clip(0, 255)
    return list(matched_data.astype(np.uint8))

matched_image_data = match_color(image_data, image_mean, image_std, reference_mean, reference_std)

5. Save the matched image

Finally, we save the matched image data as a new image file. The code example is as follows:

def save_image(data, width, height, filename):
    image = Image.new('RGB', (width, height))
    image.putdata(data)
    image.save(filename)

save_image(matched_image_data, image_width, image_height, 'matched_image.jpg')

Conclusion:
Through the above steps, we have learned how to use Python to color match images. This technology has wide applications in image processing, design and other fields, and can effectively improve the quality and consistency of images. I hope this article is helpful to you, and you are welcome to try it and apply it to actual projects.

The above is the detailed content of How to color match images using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools