📚
DLIP
  • Introduction
  • Prerequisite
  • Image Processing Basics
    • Notes
      • Thresholding
      • Spatial Filtering
      • Masking with Bitwise Operation
      • Model n Calibration
    • Tutorial
      • Tutorial: Install OpenCV C++
      • Tutorial: Create OpenCV Project
      • Tutorial: C++ basics
      • Tutorial: OpenCV Basics
      • Tutorial: Image Watch for Debugging
      • Tutorial: Spatial Filter
      • Tutorial: Thresholding and Morphology
      • Tutorial: Camera Calibration
      • Tutorial: Color Image Processing
      • Tutorial: Edge Line Circle Detection
      • Tutorial: Corner Detection and Optical Flow
      • Tutorial: OpenCV C++ Cheatsheet
      • Tutorial: Installation for Py OpenCV
      • Tutorial: OpenCv (Python) Basics
    • LAB
      • Lab Report Template
      • Lab Report Grading Criteria
      • LAB Report Instruction
      • LAB: Grayscale Image Segmentation
        • LAB: Grayscale Image Segmentation -Gear
        • LAB: Grayscale Image Segmentation - Bolt and Nut
      • LAB: Color Image Segmentation
        • LAB: Facial Temperature Measurement with IR images
        • LAB: Magic Cloak
      • LAB: Straight Lane Detection and Departure Warning
      • LAB: Dimension Measurement with 2D camera
      • LAB: Tension Detection of Rolling Metal Sheet
  • Deep Learning for Perception
    • Notes
      • Lane Detection with Deep Learning
      • Overview of Deep Learning
        • Object Detection
        • Deep Learning Basics: Introduction
        • Deep Learning State of the Art
        • CNN, Object Detection
      • Perceptron
      • Activation Function
      • Optimization
      • Convolution
      • CNN Overview
      • Evaluation Metric
      • LossFunction Regularization
      • Bias vs Variance
      • BottleNeck Unit
      • Object Detection
      • DL Techniques
        • Technical Strategy by A.Ng
    • Tutorial - PyTorch
      • Tutorial: Install PyTorch
      • Tutorial: Python Numpy
      • Tutorial: PyTorch Tutorial List
      • Tutorial: PyTorch Example Code
      • Tutorial: Tensorboard in Pytorch
      • Tutorial: YOLO in PyTorch
        • Tutorial: Yolov8 in PyTorch
        • Tutorial: Train Yolo v8 with custom dataset
          • Tutorial: Train Yolo v5 with custom dataset
        • Tutorial: Yolov5 in Pytorch (VS code)
        • Tutorial: Yolov3 in Keras
    • LAB
      • Assignment: CNN Classification
      • Assignment: Object Detection
      • LAB: CNN Object Detection 1
      • LAB: CNN Object Detection 2
      • LAB Grading Criteria
    • Tutorial- Keras
      • Train Dataset
      • Train custom dataset
      • Test model
      • LeNet-5 Tutorial
      • AlexNet Tutorial
      • VGG Tutorial
      • ResNet Tutorial
    • Resource
      • Online Lecture
      • Programming tutorial
      • Books
      • Hardware
      • Dataset
      • Useful sites
  • Must Read Papers
    • AlexNet
    • VGG
    • ResNet
    • R-CNN, Fast-RCNN, Faster-RCNN
    • YOLOv1-3
    • Inception
    • MobileNet
    • SSD
    • ShuffleNet
    • Recent Methods
  • DLIP Project
    • Report Template
    • DLIP 2021 Projects
      • Digital Door Lock Control with Face Recognition
      • People Counting with YOLOv4 and DeepSORT
      • Eye Blinking Detection Alarm
      • Helmet-Detection Using YOLO-V5
      • Mask Detection using YOLOv5
      • Parking Space Management
      • Vehicle, Pedestrian Detection with IR Image
      • Drum Playing Detection
      • Turtle neck measurement program using OpenPose
    • DLIP 2022 Projects
      • BakeryCashier
      • Virtual Mouse
      • Sudoku Program with Hand gesture
      • Exercise Posture Assistance System
      • People Counting Embedded System
      • Turtle neck measurement program using OpenPose
    • DLIP Past Projects
  • Installation Guide
    • Installation Guide for Pytorch
      • Installation Guide 2021
    • Anaconda
    • CUDA cuDNN
      • CUDA 10.2
    • OpenCV
      • OpenCV Install and Setup
        • OpenCV 3.4.13 with VS2019
        • OpenCV3.4.7 VS2017
        • MacOS OpenCV C++ in XCode
      • Python OpenCV
      • MATLAB-OpenCV
    • Framework
      • Keras
      • TensorFlow
        • Cheat Sheet
        • Tutorial
      • PyTorch
    • IDE
      • Visual Studio Community
      • Google Codelab
      • Visual Studio Code
        • Python with VS Code
        • Notebook with VS Code
        • C++ with VS Code
      • Jupyter Notebook
        • Install
        • How to use
    • Ubuntu
      • Ubuntu 18.04 Installation
      • Ubuntu Installation using Docker in Win10
      • Ubuntu Troubleshooting
    • ROS
  • Programming
    • Python_Numpy
      • Python Tutorial - Tips
      • Python Tutorial - For Loop
      • Python Tutorial - List Tuple, Dic, Set
    • Markdown
      • Example: API documentation
    • Github
      • Create account
      • Tutorial: Github basic
      • Tutorial: Github Desktop
    • Keras
      • Tutorial Keras
      • Cheat Sheet
    • PyTorch
      • Cheat Sheet
      • Autograd in PyTorch
      • Simple ConvNet
      • MNIST using LeNet
      • Train ConvNet using CIFAR10
  • Resources
    • Useful Resources
    • Github
Powered by GitBook
On this page
  • Tutorial: Color Image Processing
  • I. Introduction
  • II. Tutorial
  • OpenCV: inRange()
  • Example: Color Segmentation
  • III. Exercise
  • Drawing the trajectory of a colored object with Webcam
  • Appendix

Was this helpful?

  1. Image Processing Basics
  2. Tutorial

Tutorial: Color Image Processing

PreviousTutorial: Camera CalibrationNextTutorial: Edge Line Circle Detection

Last updated 28 days ago

Was this helpful?

Tutorial: Color Image Processing

​

Tutorial: Color Image Segmentation

I. Introduction

In this tutorial, you are learn how to segment a colored object using a web-cam. We will use inRange() algorithm to segment the moving colored object and draw contour or boundary boxes around the tracked object.

II. Tutorial

OpenCV: inRange()

void cv::inRange	(	
    InputArray 	src,
    InputArray 	lowerb,
    InputArray 	upperb,
    OutputArray 	dst 
)	
    
// # python   
    dst= cv2.inRange(src, lowerb, upperb, dst=None)
	dst1 = cv2.inRange(src, (0, 128, 0), (100, 255, 100))

Parameters

  • src first input array.

  • lowerb inclusive lower boundary array or a scalar.

  • upperb inclusive upper boundary array or a scalar.

  • dst output array of the same size as src and CV_8U type.

Example: Color Segmentation

One way of choosing the appropriate InRange conditions is analyzing the pixel statistic of a small sub-window within the targeted colored area.

Download the tutorial source code file

Choose the target window to analyze with mouse click and drag.

See Appendix for the MouseEvent code

Analyze for the standard deviation and mean of the targeted color within the window.

  Mat roi_RGB(image, selection);           // Set ROI by the selection box       
  Mat roi_HSV;  
  cvtColor(roi_RGB, roi_HSV, CV_BGR2HSV);  
  Scalar means, stddev;  meanStdDev(roi_HSV, means, stddev);  
  cout << "\n  Selected ROI Means= " <<  means << " \n  stddev= " <<  stddev;  

Add slidebars to change the InRange values of each R, G, B or H, S, V and segment each colored ball.

/// set dst as the output of InRange
inRange(hsv, Scalar(MIN(hmin, hmax), MIN(smin, smax), MIN(vmin, vmax)),
	Scalar(MAX(hmin, hmax), MAX(smin, smax), MAX(vmin, vmax)), dst);

Apply appropriate morphology (i.e. dilation/erosion/fill holes) to the output binary images to cluster the detected objects into meaningful blobs.

Find all contours and select the contour with the largest area

Mat image_disp, hsv, hue, mask, dst;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
…
findContours(dst, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
/// Find the Contour with the largest area ///
int idx = 0, largestComp = 0;
double maxArea = 0;
for (; idx >= 0; idx = hierarchy[idx][0])
{
	const vector<Point>& c = contours[idx];
	double area = fabs(contourArea(Mat(c)));		
	if (area > maxArea)
	{
		maxArea = area;
		largestComp = idx;
	}
}

Draw the contour and a box over the target object

/// Draw the Contour Box on Original Image ///
drawContours(image_disp, contours, largestComp, Scalar(255, 255, 255), 4, 8, hierarchy);
Rect boxPoint = boundingRect(contours[largestComp]);
rectangle(image_disp, boxPoint, Scalar(255, 0, 255), 3);

Now, segment other color balls

III. Exercise

Drawing the trajectory of a colored object with Webcam

Modify your tutorial program to keep drawing the contour on a white or black background image.

  • Use your webcam for the source image data.

  • Use any colored object as the target.

  • Draw rectangles or circles for the output display.

Appendix

Sample code: On Mouse Event

/// On mouse event 
static void onMouse(int event, int x, int y, int, void*)
{
   if (selectObject)  // for any mouse motion
   {
   	selection.x = MIN(x, origin.x);
   	selection.y = MIN(y, origin.y);
   	selection.width = abs(x - origin.x) + 1;
   	selection.height = abs(y - origin.y) + 1;
   	selection &= Rect(0, 0, image.cols, image.rows);  
// Bitwise AND  check selection is within the image coordinate
   }

   switch (event)
   {
   case CV_EVENT_LBUTTONDOWN:
   	selectObject = true;
   	origin = Point(x, y);
   	break;
   case CV_EVENT_LBUTTONUP:
   	selectObject = false;
   	if (selection.area())
   		trackObject = true;
   	break;
   }
}

First, read the OpenCV documentation

read here
tutorial code
test image