X
    Categories: Python OpenCV Tutorials

Swap colors in an image using OpenCV and Python

Hello,

In today’s post, we’ll discuss how to swap colors in an image using OpenCV and Python. Often, while writing OpenCV program, you’ll have a need to change the source color to a different color for maybe better understanding or computation. Here’s how you can easily achieve it.
There is a pre-requisite to have numpy installed. NumPy is awesome, because it allows you to manipulate tabular data, like tables and images, in a vectorized manner. In our example, we’ll use numpy so that we don’t have to write a for-loop to change all the pixels by iterating over them but instead, we can use a declarative selector which selects all black pixels in the image and then assign them a desired value which in our case is RED.

 

1
2
3
4
5
6
import numpy as np
import cv2

im = cv2.imread('your_input_image.png')
im[np.where((im == [0,0,0]).all(axis = 2))] = [0,33,166]
cv2.imwrite('your_output_image.png', im)

Result: 

 

Installation of OpenCV 3.3/3.2/3.0 and Python 2.7 on Windows 10 (64-bit)
Install OpenCV 3.3 and Python(2.7 & 3.5) bindings on Ubuntu 16.04
Editor :