Color Thresholding in OpenCV

Filtering and feature extraction are both very important tasks for efficient object recognition in embedded vision systems.

Perhaps one of the simplest, but also effective, forms of filtering is using color information which can be a very important factor in recognizing and detecting specific objects. For example, if you are interested in developing an app to detecting a red car then a wise first step during pre-processing is to first try and identify regions within the image that are mostly red. Of course, things are not always this simple but such approaches can be effective in many applications.

Below is an example of a code written in python using the OpenCV computer vision library that interfaces with a camera and recognizes the red color in the video stream. Using the same code you can recognize different colors by changing the lower and upper color bounds.

OpenCV Thresholding Code

Below you can see the result of the code, where the blue color is thresholded and preserved in the right image.

Color Thresholding Result

Code as text:

import numpy as np
import cv2
import cv2.cv as cv

im_width = 320
im_height = 240

cap = cv2.VideoCapture(0)
cap.set(cv.CV_CAP_PROP_FRAME_WIDTH,im_width)
cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT,im_height)

cv.NamedWindow(“Video”, 0)
# The order of the colors is blue, green, red
lower_color_bounds = cv.Scalar(100, 0, 0)
upper_color_bounds = cv.Scalar(225,80,80)

print ‘Press <q> to quit’

while(True):
ret,frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
mask = cv2.inRange(frame,lower_color_bounds,upper_color_bounds )
mask_rgb = cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)
frame = frame & mask_rgb
cv2.imshow(‘Video’,frame)
if(cv2.waitKey(1) & 0xFF == ord(‘q’)):
cv.DestroyWindow(“video”)
break

cap.release()
cv2.destroyAllWindows()

PhD in Computer Engineering, Self-Driving Car Engineering Nanodegree, Computer Vision, Visual Perception and Computing

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store