Color Thresholding in OpenCV

Christos Kyrkou
2 min readOct 30, 2017

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()

--

--

Christos Kyrkou

Research Lecturer at the KIOS Research & Innovation Center of Excellence at the University of Cyprus. Research in the areas of Computer Vision and Deep Learning