Image Effects How to Replace Colors in an Image How to Combine Two Images in Python 12 Tips for Effective HTML Image Optimization Restore Image: Common Issues and How to Fix Them Using Image Enhancement for Better Visual Content FLV vs WEBM: Which Video Format Should You Choose in 2025? A Beginner’s Guide to Image Comparison in Python Python Image Analysis Tools and Techniques: Where to Start Understanding How to Change the Aspect Ratio of an Image Unleashing the Power of Image Organizers in 2025 How to Make a Low-Quality Image Look Better Understanding Lossless Image Compression How to Set Up Image Registration in Python 8 Different Image Processing Techniques You Can Use 4 Ways to Make an Image Larger without Losing Quality 3 Easy Ways to Eliminate Duplicate Images The Basics of Face Detection in Python How to Implement Multiple File Upload in PHP Like a Pro Creating Custom Image Cropping Interfaces in Android How to Create Simple Yet Effective PHP Overlay Understanding Real-Time Image Recognition How to add a shadow effect to an image with CSS How to crop an image in Flutter with Cloudinary How To Rotate an Image with Java Image Processing with Python Rotating an image with CSS Enhancing User Experience with a Responsive Image Slider Building a Python Image Recognition System Building an Interactive JavaScript Image Manipulation Tool Image Align Centering with HTML and CSS Efficient Image Cropping Techniques with Angular and Cloudinary Ultimate Guide to Photo Gallery on Android A Comprehensive Guide to Adding Text to Images on Android Mastering Background Changes in React Applications Comprehensive Guide on Changing Background on Android Devices Mastering Image Rotation in Java A Guide to Adding Text to Images with Python A Guide to Converting Images to Grayscale with Python Introduction Creating an Image Overlay with JavaScript Rotating an Image in Python Creating a Dynamic Photo Gallery with jQuery Creating An Interactive Photo Gallery Using JavaScript Mastering Overlay in Android Mastering Angular Overlay: A Comprehensive Guide Comprehensive Guide to Overlay in Flutter Mastering Overlay React for Responsive Design Solutions Create a Blurred Image with PHP: A Comprehensive Guide Guide to Using Blur Image in Flutter Mastering Blur Image in React Native Mastering Image Blurring in Python Mastering the Art of Image Blurring Mastering the Art of Image Blurring in Java The Ultimate Guide to Blurring Images on Android Understanding and Implementing Blur Image in JQuery An Extensive Walkthrough of Blurring Images with JavaScript How to Use HTML, CSS, and JavaScript to Make an Image Slider HTML Image Tag How to Crop GIFs? How to Align Images with CSS Ken Burns Effect – Complete Guide and How to Apply It Cartoonify – Complete Guide on Cartoonify Image Effect Mastering Web Aesthetics: A Comprehensive Guide to Gradient Fades Sepia Effect: The Ultimate Guide to the Sepia Photo Effect What is Vignette? Guide to Vignette Image Editing Pixelate – The Ultimate Guide to the Pixelation Effect How to Outline an Image: Enhancing Visual Appeal and Depth Make Your Photos Pop with Image Effects Upscale Image – Developers guide to AI-driven image upscaling Image Manipulation: History, Concepts and a Complete Guide A Full Guide to Object-aware Cropping Simplify Your Life with Automatic Image Tagging How To Resize Images In WordPress How To Create a Progress Bar For Asset Uploads Animated GIFs – What They Are And How To Create Them How To Automatically Improve Image Resolution AI Drop Shadow Get Image Dimensions From URLs Automatically Add Sepia Effect To Images Automatically Make an Image a Cartoon Automatically Add Blur Faces Effect To Images Automatically Add Background Removal Effect to an Image How to Resize an Image with React How to Easily Resize an Image with React Native

How to Replace Colors in an Image

Think of every digital image as a collection of tiny square elements called pixels; each pixel holds a unique color and brightness level, arranged in a grid. Likewise, each image consists of a single color type, classifiable into three categories. That means images can be black and white, grayscale (shades of gray), or color (like RGB or CMYK), all with different detail levels.

But, what if you want to change these colors? Whether you’re looking to re-use product photos or simply just want to spice up your photos, knowing how to replace colors in an image can be a useful tool for developers working with images.

In this guide, we’ll dive into what color replacement is, why it’s important, and how to replace colors in an image using python libraries like OpenCV, as well as Cloudinary, a cloud-based image transformation tool.

What is Color Replacement?

Color replacement is a common technique in image editing that allows you to change specific colors in an image to another, to achieve a desired effect. Color replacement can be done for various reasons.

For instance, if an image has incorrect or unwanted colors due to lighting issues or camera settings, a photographer or designer can replace the colors using software tools like Photoshop or Gimp. Or if you have a product image that needs to match your brand’s color scheme, you can replace the existing colors with your brand’s colors to maintain consistency for marketing.

How Does Color Replacement Work?

A typical color replacement process involves three main steps:

  1. Color identification: First, the software or program analyzes the image to detect the specific color you want to replace within an image.
  2. Mask creation: Once the color is identified, the program generates a mask—a kind of filter that highlights only the areas containing the selected color.
  3. Color substitution: After isolating the color, the program replaces it with a new one by changing the pixel values.

In the next sections, we’ll walk you through how to replace colors in an image with Python, using OpenCV and Cloudinary.

Color Replacement in Python

Python is a versatile programming language with a wide range of applications, including image processing and manipulation. Python offers several libraries that can be used for color replacement in image, with one of the most commonly used ones being OpenCV.

OpenCV

OpenCV is an open source computer vision and machine learning software library. Its extensive library includes algorithms used in image and video processing, object detection, and other applications. What’s more, we can use it to replace colors in an image by converting the image to HSV color space and then using inRange to mask the color we want to replace.

Let’s go through an example. But first, install the required libraries using the command below:

pip install opencv-python numpy

In this demo, we’re going to replace the hair color of the woman in this picture with green using OpenCV.

Before we proceed, it’s important to note that a major drawback of manually replacing colors with OpenCV is that real-world images often have color variations across different areas, making it difficult to achieve high precision.

In other words, when replacing a color (like red [255, 0, 0]), you won’t find every pixel with that exact RGB value in a real-world image–this is often referred to as color shifts. Instead, you’ll find slightly different shades of red.

One way to solve this problem would be defining an upper and lower bound, where we create a range of colors so that our program will consider a match instead of just one exact color.

Here’s the code to replace the hair color in the image above with green:

import cv2
import numpy as np

# Convert the hair color RGB (23, 14, 12) value to HSV
rgb_color = np.uint8([[[23, 14, 12]]]) 
hsv_color = cv2.cvtColor(rgb_color, cv2.COLOR_RGB2HSV) 
h, s, v = map(int, hsv_color[0][0])

# Define upper and lower HSV bounds
hue_range = 10  # Adjust range based on lighting
sat_range = 40
val_range = 40

lower_bound = np.array([max(h - hue_range, 0), max(s - sat_range, 0), max(v - val_range, 0)])
upper_bound = np.array([min(h + hue_range, 179), min(s + sat_range, 255), min(v + val_range, 255)])

image = cv2.imread("cld-sample.jpg")

# Convert image to HSV
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Create a mask to detect the target color
mask = cv2.inRange(hsv, lower_bound, upper_bound)

# Replace the hair color with green 
replacement_color = [0, 255, 0] 

image[mask > 0] = replacement_color

#Save the result
cv2.imwrite("output.jpg", image)

And here’s the result:

Notice how some parts of the hair didn’t turn green, while some areas of the dog’s body did? This happens because not all hair colors fit within the range we defined, and some dark patches on the dog do fall within that range.

This shows that a manual color replacement may not always yield the desired results, unlike alternatives like Cloudinary’s Generative Recolor, which uses generative AI to manipulate colors in images at scale, with high precision.

Using Cloudinary To Replace Colors in an Image

Cloudinary is a cloud-based image and video management platform that offers a wide range of image manipulation features, including color replacement. Cloudinary’s Generative Recolor allows you to easily recolor items within an image using natural language prompts to identify objects, and specify the desired color through a hex code or simple descriptions like “pink” or “light orange.”

For example, this transformation URL changes the jacket of the man on the right to pink:

https://res.cloudinary.com/demo/image/upload/e_gen_recolor:prompt_the jacket on the right;to-color_pink/docs/jackets.jpg

Let’s write some code to see generative recolor in action. First, we need to install the necessary libraries for our code to work:

pip install cloudinary requests
  • cloudinary: The Python SDK that allows us to interact with Cloudinary API.
  • requests: An HTTP client library for Python. We’ll use it to download the transformed image to disk.

Next, using the same image from the OpenCV example, here’s the code to replace the woman’s hair color with green using the gen_recolor transformation parameter:

import cloudinary
import cloudinary.uploader
import cloudinary.api
from cloudinary import CloudinaryImage
import requests

# Replace with your Cloudinary credentials
cloudinary.config(  
    cloud_name="your_cloud_name",  
    api_key="your_api_key",  
    api_secret="your_api_secret"  
)

# Upload the image to Cloudinary
upload_response = cloudinary.uploader.upload("cld-sample.jpg")
if "secure_url" in upload_response:
    uploaded_url = upload_response["secure_url"] 
else:
    print("Failed to upload image")
    exit()

# Apply Generative Recolor transformation using the uploaded image URL
transformed_url = cloudinary.CloudinaryImage(upload_response["public_id"]).build_url(
    effect="gen_recolor:prompt_hair;to-color_green" # Tells Cloudinary to change the hair color to green

)

# Download and save the recolored image
image_response = requests.get(transformed_url, stream=True)
if image_response.status_code == 200:
    with open("colored-hair.jpg", "wb") as file:
        for chunk in image_response.iter_content(1024):
            file.write(chunk)
    print("Imaged saved as colored-hair.jpg")
else:
    print("Failed to download the image")

Now when you run the code, you should see the image saved to your working directory. Here’s what the result looks like:

Wrapping Up

Color replacement has many applications in the real world including image processing, photography, marketing, accessibility, and more. Compared to traditional methods like OpenCV, Cloudinary simplifies the process by using AI-powered recoloring, eliminating the need for manual color detection and masking. While this approach works best for clearly visible objects, it also offers a fast and efficient way to modify images without complex coding.

To explore more about generative recolor and some other cool things Cloudinary can do, such as generative fill, generative replace and more, feel free to sign up for a free account to get started.

QUICK TIPS
Colby Fayock
Cloudinary Logo Colby Fayock

In my experience, here are tips that can help you better replace colors in images using OpenCV and Cloudinary:

  1. Use k-means clustering for color segmentation
    For complex images with many shades, k-means clustering can isolate dominant colors more effectively than HSV thresholding, improving the accuracy of your replacement mask.
  2. Apply Gaussian blur to masks for smoother blending
    Blurring the binary mask before applying color replacement creates a feathered edge, reducing harsh transitions between replaced and original colors.
  3. Work in LAB color space for perceptual accuracy
    LAB space separates luminance from color information. Replacing colors in this space can produce more visually consistent results, especially for subtle hues.
  4. Use adaptive thresholding for dynamic environments
    In scenes with varied lighting, adaptive thresholding can adjust mask sensitivity based on local pixel intensities, improving color targeting.
  5. Combine masks from multiple color spaces
    Sometimes, combining HSV and RGB-based masks (using logical AND/OR operations) can improve precision by capturing overlapping but complementary regions.
  6. Train a color classifier for object-specific recoloring
    Instead of using hard-coded thresholds, a simple SVM or decision tree classifier can learn color patterns specific to objects (like skin or clothing), making recoloring smarter.
  7. Add transparency to your replacement layer
    If you’re replacing color but want to retain some texture or lighting information, use cv2.addWeighted() to blend the new color with the original image.
  8. Leverage Cloudinary’s layer-based transformations
    With Cloudinary, you can apply effects like recolor only to specific overlays or components using chained transformations, allowing multi-part image editing in one request.
  9. Automate recolor accuracy tests with perceptual hashing
    Use image hashing (like pHash) to compare before and after images and detect unintended region changes after recoloring—this is great for QA automation.
  10. Script interactive color selection for non-programmers
    Build a simple GUI using OpenCV’s trackbars or use Jupyter widgets to let users dynamically pick target and replacement colors for faster iteration in production workflows.
Last updated: Mar 22, 2025