Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering

Matlab Red Color Detection

By Suraj Garg

Description

This article explains how to detect and track red objects in a live video. There are different approaches to detect the red color in every single frame. One of these popular approaches includes the conversion of whole RGB frame into corresponding HSV (Hue-Saturation-Value) plane followed by extraction of pixel values only for red. One can choose a range that reflects all existing shades of red so as to detect and differentiate all colors in the frame.
 
However, this approach is practically difficult to apply especially in Live video due to the ambient light. There is one more solution where one can detect a particular color say red, blue or green.   Although this is not versatile for all colors, but it easily eliminates the issue of ambient light. Here, we are going to use the same approach in order to detect red color. 
 
For newbie people
 
“ Do coding into ‘editor’ of Matlab “
 
Flow diagram 
 

Flow Diagram of Matlab Code used for Color Detection

Fig. 1: Flow Diagram of Matlab Code used for Color Detection

Steps Required

Step 1: First acquire an RGB Frame from the Video.
Matlab code :

Image showing blocks of different shapes in red color

Fig. 2: Image showing blocks of different shapes in red color

A=imread(a.jpg);
 
 
 
Step 2: Extract the Red Layer Matrix from the RGB frame.
MATLAB Code:

Image showing extracting red layer matrix

Fig. 3: Image showing extracting red layer matrix

redA = A(:,:,1);
Step 3: Get the grey image of the RGB frame.
MATLAB Code:

Image showing transformation of captured image after adding grey frame

Fig. 4: Image showing transformation of captured image after adding grey frame

grayFrame = rgb2gray(A);
Step 4: Subtract the grayFrame from the redFrame.
MATLAB Code: 

Image showing transformation of captured image after subtracting grey frame from red matrix

Fig. 5: Image showing transformation of captured image after substracting grey frame from red matrix

diffFrame=imsubtract(redA, grayFrame);

Step 5: Filter out unwanted noises using Median Filter
MATLAB Code: 

Image showing transformation of captured image after filtering out unwanted noises

Fig. 6: Image showing transformation of captured image after filtering out unwanted noises

diffFrame = medfilt2(diffFrame, [3 3]);
Step 6: Now convert the diffFrame into corresponding Binary Image using proper threshold value. Change its value for different light conditions. In my code I have used its value as 0.15.
MATLAB Code:

Image showing final binary image

Fig. 7: Image showing final binary image

binFrame = im2bw(diffFrame, 0.15);

Step 7: Now your Red color has been detected. You can put any blob statistics analysis on this image or calculate the centroid, area or bounding box of those blobs.
I have introduced the same algorithm in the code of this project that you can see below. 
 
Software & hardare Required

1 Matlab (here I am using R2011 b)

2 Webcam ( inbulid or external)

Screenshot of Matlab Code used for Red Color Detection

Fig. 8: Screenshot of Matlab Code used for Red Color Detection

 

Screenshot of Matlab Command Window implementing color detection program

Fig. 9: Screenshot of Matlab Command Window implementing color detection program

 

Project Source Code

###

%%take video from webcam

vid=videoinput('Winvideo',1,'YUY2_320x240');

%set frames trigger

set(vid, 'FramesPerTrigger', Inf);

% video output is rgb color

set(vid,'ReturnedColorspace','rgb';

% set video frame interval 1

vid.FrameGrabinterval=1

% start video

start(vid);

%start loop till frame 10000

while(vid.FramesAcquired<=1000)

% get snapshot of video

data=getsnapshot(vid);

% red color extraction

red=data(:,:,1);

% convert picture into gray

gray=rgb2gray(data);

% subtract red to gray frame

diff_im=imsubtract(red,gray);

% use median filter

diff_im=medfilt2(diff_im,[3,3]);

% convert image into binary

diff_im=im2bw(diff_im,0.10);

% use blob statistics analysis on this image

diff_im=bwareaopen(diff_im,1000);

bw=bwlabel(diff_im,8);

% use boundbox to enbox red color object

stats=regionprops(bw,'BoundingBox','Centroid');

image(data);

 

hold on

% identify no of red object in image

for(object=1:length(stats))

bb=stats(object).BoundingBox;

bc=stats(object).Centroid;

 

rectangle('Position',bb,'EdgeColor','r','LineWidth',2)

plot(bc(1),bc(2),'-m+')

a=text(bc(1)+15,bc(2),strcat('X: ',num2str(round(bc(1))),' Y: ',num2str(round(bc(2)))));

set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','yellow');

if(length(stats)==1)

% show label one with one object

a=text(50,60,strcat('One'));

set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','red');

end

if(length(stats)==2)

% show label two with two red object

a=text(50,60,strcat('Two'));

set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','red');

end

if(length(stats)==3)

% show label three with three red object

a=text(50,60,strcat('three'));

set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','red');

end

if(length(stats)==4)

% show label four with four red object

a=text(50,60,strcat('four'));

set(a,'FontName','Arial','FontWeight','bold','FontSize',12,'Color','red');

end

end

hold off

% end loop

end

% stop video

stop(vid);

% flush data

flushdata(vid);

% clear all

clear all; 

###

 


Project Video


Filed Under: Electronic Projects

 

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • Introduction to Brain Waves & its Types (Part 1/13)
  • Understanding NeuroSky EEG Chip in Detail (Part 2/13)
  • Performing Experiments with Brainwaves (Part 3/13)
  • Amplification of EEG Signal and Interfacing with Arduino (Part 4/13)
  • Controlling Led brightness using Meditation and attention level (Part 5/13)
  • Control Motor’s Speed using Meditation and Attention Level of Brain (Part 6/13)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • What are the battery-selection criteria for low-power design?
  • Key factors to optimize power consumption in an embedded device
  • EdgeLock A5000 Secure Authenticator
  • How to interface a DS18B20 temperature sensor with MicroPython’s Onewire driver
  • Introduction to Brain Waves & its Types (Part 1/13)

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr bluetooth dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • Op amp non inverting amplifier not working
  • Measure AC current accurateley (100mA to 10A)
  • Avalanche Pulser
  • Fpga wake up
  • RCF Subwoofer Amplifier PIC16F870-I/SP please help me about hex code

RSS Electro-Tech-Online.com Discussions

  • How to search component to replace my burn RF inductor?
  • Need a ducted soldering fan for solder smoke extraction
  • Someone please explain how this BMS board is supposed to work?
  • bluetooth jammer
  • Disabled son needs advice please
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering