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:
- Color identification: First, the software or program analyzes the image to detect the specific color you want to replace within an image.
- 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.
- 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.