Using OpenCV in Python to Remove Colours in Images

I'm experimenting with the OpenCV programming library as part of the Computational Photography course I'm taking at Coursera. I don't know if I'll be able to finish the course due to my other obligations, but I just thought I would share my first little test program so that my students might benefit.

This program reads in a picture file, then simply strips off the red, green, and blue channels and saves the files.

I've written the program so it can easily be adapted for other picture files. Simply replace "flower" with the base part of your filename in the img_base_name variable and enter the path to your picture file in the img_path variable. Note that the OpenCV and the numpy libraries must be installed and that you need to be using Python 2.x.

Here's my program:

# imports
import cv2 # the computer vision library, from
import numpy as np # wasn't needed but is always imported in examples

# make it easy to modify the program to use other pictures
img_path = 'images/part0/'
img_base_name = 'flower' 

# ===== delete blue =====
# import the picture
img_array = cv2.imread(img_path+img_base_name+'.jpg')
# note that [:,:,0] is blue, [:,:,1] is green, [:,:,2] is red
img_array[:,:,0] = 0
# write the image

# ===== delete green =====
img_array = cv2.imread(img_path+img_base_name+'.jpg') 
img_array[:,:,1] = 0
cv2.imwrite(img_path+img_base_name+'_no_green.jpg', img_array) 

# ===== delete red =====
img_array = cv2.imread(img_path+img_base_name+'.jpg')
img_array[:,:,2] = 0
cv2.imwrite(img_path+img_base_name+'_no_red.jpg', img_array)

...and here are the resultant pictures:

No Blue
No Green
No Red


Popular posts from this blog

The Kiss of Death

Promoting "Eight Weeks To Web 2"