Color Sorting Robot
Color Sorting Robot
Version: 1.1.0
Copyright 2024, PRAGYATMIKA, The Power of Intelligence
1
Web : www.pragyatmika.co.in Email : [email protected]
Colour Sorting Robot using OpenCV
1. PROBLEM STATEMENT
In the field of automated systems and robotics, colour detection and sorting is a
fundamental task that can be applied to various industrial and commercial applications. The
goal of this project is to design and develop a Colour Sorting Robot using OpenCV, a
computer vision library, which can accurately detect and count the number of different
coloured objects in real-time video streams. The system should be capable of:
The system aims to serve as a foundation for a colour sorting robot, where the colour
detection capabilities can be used to identify and categorize objects based on their colours.
This project will utilize OpenCV for image processing and colour detection in the HSV colour
space, allowing for robust colour identification under various lighting conditions.
The final output should display the live video feed with overlaid colour count information,
updating in real-time as the camera captures new frames. The system should be able to
handle multiple colours simultaneously and be easily extendable to include additional
colours if needed.
2. THE DESCRIPTION
This project implements a real-time colour detection system using computer vision
techniques, specifically leveraging the OpenCV library. The system is designed to identify
and quantify the presence of various colours in a live video stream, serving as a foundation
for a colour sorting robot.
2
Web : www.pragyatmika.co.in Email : [email protected]
Key features of the project include:
1. Real-time Video Processing: The system captures live video input from a webcam or
camera, processing each frame to detect colours.
2. Multi-Colour Detection: It can simultaneously detect multiple colours, including red,
green, blue, orange, black, pink, yellow, purple, and brown.
3. HSV Colour Space: The colour detection is performed in the HSV (Hue, Saturation,
Value) colour space, which is more robust to lighting variations compared to RGB.
4. Colour Counting: For each frame, the system counts the number of pixels that fall
within the defined colour ranges, providing a quantitative measure of each colour’s
presence.
5. Live Display: The processed video feed is displayed in real-time, with overlaid text
showing the count for each detected colour.
6. User Interface: A simple graphical interface shows the live video feed with colour
detection results, allowing users to visually confirm the system's performance.
7. Extensibility: The colour range definitions are stored in a dictionary, making it easy
to add or modify colour definitions.
The system is designed to run continuously, processing and displaying results in real-time
until the user chooses to exit the application. This real-time capability makes it suitable for
integration with physical robotic systems for immediate colour-based decision making and
sorting.
3
Web : www.pragyatmika.co.in Email : [email protected]
3. SOFTWARE AND HARDWARE REQUIREMENTS
A. Software Tools Required:
1.Arduino IDE:
The Arduino IDE (Integrated Development Environment) is an
open-source software platform designed primarily for
programming Arduino boards, but it also supports a wide
range of other microcontroller platforms, including ESP32. It
provides a user-friendly interface for writing, compiling, and
uploading code to various microcontrollers. The IDE is cross-
platform, available for Windows, macOS, and Linux, making it accessible to a broad user base.
It comes with a text editor for writing code, a message area for feedback, a text console for
output, and a toolbar with common function buttons. The Arduino IDE uses a simplified
version of C++, making it easier for beginners to start programming microcontrollers. It
includes a rich set of built-in libraries for common tasks and supports the addition of third-
party libraries, expanding its capabilities. For more advanced users, the IDE also allows
integration with external tools and supports programming in standard C++ when needed.
With its extensive documentation, large community support, and compatibility with
numerous hardware platforms, the Arduino IDE has become a popular choice for both
hobbyists and professionals working on embedded systems projects.The Arduino IDE
(Integrated Development Environment) is an open-source software platform designed
primarily for programming Arduino boards, but it also supports a wide range of other
microcontroller platforms, including ESP32. It provides a user-friendly interface for writing,
compiling, and uploading code to various microcontrollers. The IDE is cross-platform,
available for Windows, macOS, and Linux, making it accessible to a broad user base. It comes
with a text editor for writing code, a message area for feedback, a text console for output,
and a toolbar with common function buttons. The Arduino IDE uses a simplified version of
C++, making it easier for beginners to start programming microcontrollers. It includes a rich
set of built-in libraries for common tasks and supports the addition of third-party libraries,
4
Web : www.pragyatmika.co.in Email : [email protected]
expanding its capabilities. For more advanced users, the IDE also allows integration with
external tools and supports programming in standard C++ when needed. With its extensive
documentation, large community support, and compatibility with numerous hardware
platforms, the Arduino IDE has become a popular choice for both hobbyists and professionals
working on embedded systems projects.
2. Python IDE:
5
Web : www.pragyatmika.co.in Email : [email protected]
Key features of Python include:
Python is widely used in various fields, including web and software development, data
analysis, artificial intelligence, scientific computing, and automation.
6
Web : www.pragyatmika.co.in Email : [email protected]
6. Customizability: Allows users to adjust settings, keybindings, and appearance to their
preferences.
7. Integrated terminal: Provides a built-in command-line interface.
8. Live Share: Enables real-time collaborative editing and debugging.
The editor also features regular updates, bringing new features and improvements based on
user feedback and evolving development practices. This responsiveness to the developer
community has contributed significantly to its widespread adoption across various
programming domains.
B. Hardware Required:
The ESP32 camera module is a compact, low-cost, and versatile development board that
combines the powerful ESP32 microcontroller with a digital camera. It's designed for
Internet of Things (IoT) applications, especially those requiring image capture and
processing capabilities.
7
Web : www.pragyatmika.co.in Email : [email protected]
3. Programmability: Can be programmed using the Arduino IDE, ESP-IDF, or
MicroPython.
4. Connectivity: Built-in Wi-Fi allows for wireless image transmission and remote
control.
5. GPIO pins: Provides access to various GPIO pins for additional sensors or actuators.
6. Low power consumption: Suitable for battery-powered applications.
7. Small form factor: Compact size makes it ideal for space-constrained projects.
8. Cost-effective: Offers a good balance of features and affordability.
The base board for the ESP32-CAM is an auxiliary board designed to enhance the
functionality and ease of use of the ESP32-CAM module. This board serves several important
purposes:
8
Web : www.pragyatmika.co.in Email : [email protected]
4. Pin Breakout: The base board often exposes the GPIO pins of the ESP32-CAM in a
more accessible format, sometimes using standard pin headers.
5. Antenna Connector: Certain models provide an external antenna connector to
improve Wi-Fi range.
6. SD Card Slot: While the ESP32-CAM has an onboard microSD slot, some base boards
offer an additional, more accessible SD card slot.
7. LED Indicators: Often include LEDs for power, data transmission, and other status
indications.
8. Camera Lens Options: Some base boards are designed to accommodate different
camera lenses or lens holders.
The base board significantly improves the usability of the ESP32-CAM by addressing its main
limitations, particularly in terms of power supply and programming interface. It transforms
the compact camera module into a more robust development platform, making it easier to
prototype and develop projects without the need for additional circuitry or adapters.
B.3.USB cable
A USB cable is an essential tool for programming and powering the ESP32 CAM module.
While the ESP32 CAM itself does not have a built-in USB-to-serial interface, a USB cable can
be used in conjunction with a USB-to-serial converter to program the module and upload
code from a computer.
This project leverages two main programming languages: Arduino C and Python. Each
language plays a distinct and crucial role in the development and functionality of the Smart
Color sorting Robot using the ESP32 CAM module.
4.1. C++: For Generating Dynamic IP Address on ESP32 CAM using Arduino IDE
C++ is the primary language used for programming the ESP32 CAM module. The ESP32 CAM
is initially configured using the Arduino IDE, a popular development environment for
9
Web : www.pragyatmika.co.in Email : [email protected]
embedded programming. The setup involves writing and uploading Arduino code (sketch) to
the ESP32 CAM, enabling it to connect to a Wi-Fi network and stream video data.
● Network Configuration: The Arduino C++ code is used to configure the ESP32 CAM to
connect to a local Wi-Fi network. The code typically includes the SSID (network
name) and password of the Wi-Fi network. When the ESP32 CAM is powered on, it
uses this information to connect to the network and requests a dynamic IP address
from the router using DHCP (Dynamic Host Configuration Protocol). This allows the
ESP32 CAM to obtain an IP address automatically, making it accessible over the
network.
● Camera Initialization and Stream Setup: The C++ code initializes the camera module
and sets up an HTTP server to stream the video feed. Once the ESP32 CAM has a
dynamic IP address, the video stream can be accessed via this IP address using any
web browser or a software client like OpenCV.
● Dynamic IP Address Assignment: By using the DHCP functionality, the ESP32 CAM
automatically receives an IP address from the router each time it connects. This IP
address can be used to access the camera's live video stream. The dynamic IP makes
the system more flexible and easier to integrate into different network
environments without manual IP configuration.
4.2. Python: For Colour sorting Using ESP32 CAM Video Stream
Python is pivotal in the development of the Colour Sorting Robot using OpenCV by enabling
efficient color detection and sorting through real-time video processing. Its combination of
simplicity and powerful libraries like OpenCV makes it an ideal choice for implementing
computer vision tasks. Here's how Python is used in this project:
Python uses the OpenCV library to capture the video stream from a webcam or any
compatible video capture device. By initializing the video capture object
(cv2.VideoCapture(0)), Python can access live video frames for further processing.
10
Web : www.pragyatmika.co.in Email : [email protected]
This allows the robot to analyze the visual input in real-time, making it suitable for
dynamic environments.
● Color Detection:
Once Python captures each frame from the video stream, it leverages OpenCV's
image processing functions to detect specific colors. The process involves:
➢ Converting the Frame to HSV Color Space: The frame is converted from BGR
(Blue, Green, Red) to HSV (Hue, Saturation, Value) color space using
cv2.cvtColor(frame, cv2.COLOR_BGR2HSV). HSV is more effective for color
detection as it separates chromatic content (color) from intensity.
➢ Applying Color Masks: Python applies predefined HSV range masks to isolate
different colors. Using cv2.inRange(), it creates a binary mask for each color
that highlights the regions in the frame matching the color's HSV range.
➢ Counting Color Pixels: The script counts the number of non-zero pixels in
each color mask using cv2.countNonZero(), providing a count of how many
pixels in the frame match each color. This count helps in identifying the
presence and quantity of different colors in real-time.
● Output and Visual Feedback:
The processed video stream is displayed with annotated text showing the color
counts. Python uses cv2.putText() to overlay the color names and their respective
counts onto the video frame. This visual feedback allows users to verify the accuracy
of the color detection and observe the results in real-time.
5. LIBRARIES USED
The Color Sorting Robot project utilizes a variety of libraries in both the Arduino C and
Python programming environments. These libraries play critical roles in enabling
functionalities such as connecting to Wi-Fi, streaming video, capturing, and processing
images, and performing color detection. Below is a detailed overview of the libraries used in
the project:
● WiFi.h
Purpose: The WiFi library is essential for enabling the ESP32 CAM to connect to a Wi-
Fi network. It provides the necessary functions to manage Wi-Fi connections,
including setting up the Wi-Fi credentials (SSID and password), connecting to the
network, and obtaining an IP address.
● esp_camera.h
Purpose: The esp_camera.h library provides functions and definitions specific to the
ESP32 CAM module. It handles the initialization of the camera hardware,
configuration settings, and capturing images. This library is crucial for setting up the
camera parameters and starting the video stream.
12
Web : www.pragyatmika.co.in Email : [email protected]
Description: The requests library is a simple and elegant HTTP library for Python. It
provides a simple and intuitive way to interact with web services and APIs, enabling
developers to send HTTP requests to servers and receive responses. The library is
known for its ease of use, readability, and reliability.
● opencv-python:
Description: OpenCV (Open Source Computer Vision Library) is a powerful library for
computer vision tasks. It provides tools to capture, process, and analyze images and
video streams. In this project, OpenCV is used to access the video stream from the
ESP32 CAM, perform image processing (e.g., grayscale conversion, blurring, edge
● NumPy Library
Command: pip install numpy
6. SOFTWARE LOGIC
This project involves two main components: generating a dynamic IP address using the
Arduino IDE for the ESP32-CAM module and using Python to detect shapes through the
video stream provided by the ESP32-CAM.
13
Web : www.pragyatmika.co.in Email : [email protected]
To allow the ESP32-CAM module to stream video over a network, it first needs to connect to
a Wi-Fi network and be assigned a dynamic IP address. This IP address will be used by the
Python script to access the video feed.
14
Web : www.pragyatmika.co.in Email : [email protected]
6.2.Color Detection in Python using OpenCV
The core functionality of the Color Sorting Robot involves detecting specific colors from a
video stream. Python, with the OpenCV library (`cv2`), is used for processing video frames
and identifying colors in real time.
● Use OpenCV’s `VideoCapture` function to access the video stream from a webcam or
video capture device.
● This step ensures that Python can read video frames continuously for color
detection.
● Read each frame from the video stream using the `read()` method.
● Convert each frame from BGR (Blue, Green, Red) color space to HSV (Hue,
Saturation, Value) using `cv2.cvtColor()`. HSV is more suitable for color detection as
it separates color information from intensity.
● Define HSV color ranges for the colors of interest (e.g., red, green, blue, etc.).
● Use `cv2.inRange()` to create binary masks for each color. Each mask highlights the
pixels in the frame that fall within the specified HSV range.
● For each color mask, count the number of non-zero pixels using
`cv2.countNonZero()`. This count indicates how many pixels in the current frame
match the specified color.
● Store the count in a dictionary to track the number of detected pixels for each color.
15
Web : www.pragyatmika.co.in Email : [email protected]
5. Display the Video with Detected Colors:
● Overlay text on the video frames to display the count of each detected color using
`cv2.putText()`. This provides real-time feedback on the color detection process.
● Use `cv2.imshow()` to display the video stream with annotated text showing the
detected color counts.
● Allow users to terminate the loop and close the video window by pressing the 'q'
key. This is implemented using the `cv2.waitKey()` function, which waits for a key
press event.
7. Release Resources:
● After the color detection is complete, release the video capture object using
`cap.release()` to free up resources.
● Close all OpenCV windows using `cv2.destroyAllWindows()`.
This approach allows the Color Sorting Robot to efficiently detect and count specific colors
in real time using Python and OpenCV. By following these steps, the robot can be integrated
into various applications requiring automated color sorting, demonstrating the power of
Python for practical computer vision tasks.
7. PROGRAM CODE
16
Web : www.pragyatmika.co.in Email : [email protected]
#include "esp_camera.h"
#include <WiFi.h>
//
// WARNING!!! PSRAM IC required for UXGA resolution and high JPEG quality
//
// You must select partition scheme from the board menu that has at least 3MB APP
space.
// Face Recognition is DISABLED for ESP32 and ESP32-S2, because it takes up from
15
// ===================
// ===================
//#define CAMERA_MODEL_ESP32_CAM_BOARD
//#define CAMERA_MODEL_ESP32S2_CAM_BOARD
//#define CAMERA_MODEL_ESP32S3_CAM_LCD
#include "camera_pins.h"
// ===========================
// ===========================
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
19
Web : www.pragyatmika.co.in Email : [email protected]
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sccb_sda = SIOD_GPIO_NUM;
config.pin_sccb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_UXGA;
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;
// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
if (config.pixel_format == PIXFORMAT_JPEG) {
if (psramFound()) {
config.jpeg_quality = 10;
20
Web : www.pragyatmika.co.in Email : [email protected]
config.fb_count = 2;
config.grab_mode = CAMERA_GRAB_LATEST;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
} else {
config.frame_size = FRAMESIZE_240X240;
#if CONFIG_IDF_TARGET_ESP32S3
config.fb_count = 2;
#endif
#if defined(CAMERA_MODEL_ESP_EYE)
pinMode(13, INPUT_PULLUP);
pinMode(14, INPUT_PULLUP);
#endif
// camera init
21
Web : www.pragyatmika.co.in Email : [email protected]
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
return;
sensor_t *s = esp_camera_sensor_get();
// initial sensors are flipped vertically and colors are a bit saturated
if (s->id.PID == OV3660_PID) {
if (config.pixel_format == PIXFORMAT_JPEG) {
s->set_framesize(s, FRAMESIZE_QVGA);
#if defined(CAMERA_MODEL_M5STACK_WIDE) ||
defined(CAMERA_MODEL_M5STACK_ESP32CAM)
s->set_vflip(s, 1);
22
Web : www.pragyatmika.co.in Email : [email protected]
s->set_hmirror(s, 1);
#endif
#if defined(CAMERA_MODEL_ESP32S3_EYE)
s->set_vflip(s, 1);
#endif
#if defined(LED_GPIO_NUM)
setupLedFlash(LED_GPIO_NUM);
#endif
WiFi.begin(ssid, password);
WiFi.setSleep(false);
delay(500);
Serial.print(".");
Serial.println("");
Serial.println("WiFi connected");
23
Web : www.pragyatmika.co.in Email : [email protected]
startCameraServer();
Serial.print(WiFi.localIP());
Serial.println("' to connect");
void loop() {
delay(10000);
import cv2
import numpy as np
import time
Import requests
# ESP32 URL
URL = "http://192.168.0.106"
AWB = True
24
Web : www.pragyatmika.co.in Email : [email protected]
# Define the color ranges in HSV
color_ranges = {
'red2': ([170, 120, 70], [180, 255, 255]), # Second range for red
def detect_colors(frame):
'red': 0,
'green': 0,
'blue': 0,
'orange': 0,
'black': 0,
'pink': 0,
'yellow': 0,
'purple': 0,
'brown': 0,
if color == 'red':
else:
color_count[color] = count
return color_count
def main():
if not cap.isOpened():
return
last_update_time = time.time()
27
Web : www.pragyatmika.co.in Email : [email protected]
# Initialize the cumulative color counts
cumulative_color_count = {
'red': 0,
'green': 0,
'blue': 0,
'orange': 0,
'black': 0,
'pink': 0,
'yellow': 0,
'purple': 0,
'brown': 0,
while True:
# Capture frame-by-frame
if not ret:
break
28
Web : www.pragyatmika.co.in Email : [email protected]
# Detect colors in the current frame
color_count = detect_colors(frame)
current_time = time.time()
cumulative_color_count[color] += 1
last_update_time = current_time
y_position = 30
y_position += 30
29
Web : www.pragyatmika.co.in Email : [email protected]
cv2.imshow('Color Detection', frame)
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
8. TEST STEPS
These test steps ensure that the color sorting robot functions correctly, detecting and
counting various colors in real-time from the video stream. By following this testing
procedure, you can validate that the system meets its requirements and can be reliably used
for color sorting applications.
Step1: To use the ESP32-CAM, or any ESP32, with the Arduino IDE, you must first install the
ESP32 board (also known as the ESP32 Arduino Core) via the Arduino Board Manager.
30
Web : www.pragyatmika.co.in Email : [email protected]
Step 2: Go to the files menu and then select examples. From the example’s menu, select the
ESP32 and then Camera. Then finally open the CameraWebServer Sketch.
Step 3 : You need to modify this code a little bit. Select the Camera Module by
uncommenting the model that you are using. If you are using AI-Thinker Board uncomment
the AI-Thinker Part and comment rest of the part.
31
Web : www.pragyatmika.co.in Email : [email protected]
Step 4 : change your WiFi SSID and Password.
Step 5: Now connect the ESP32-CAM to the Base Board and connect it to your computer
using a USB cable.
Step 6: navigate to Tools > Board > esp32 and select AI-Thinker ESP32-CAM also select the
COM port to which your esp32 cam is connected.
32
Web : www.pragyatmika.co.in Email : [email protected]
Step 7: Then, navigate to Tools > Port and choose the COM port to which the ESP32-CAM is
connected.
Step 8: upload the code. The code will take more than a minute to compile and upload.
Step 9: Once you have uploaded the sketch, open the serial monitor at baud rate 115200
and press the Reset button on the ESP32-CAM. You should see the IP address in the Serial
Monitor.
33
Web : www.pragyatmika.co.in Email : [email protected]
Step 10 : Launch a browser and enter the IP address shown on the serial monitor. Ensure
that the web browser is on the same network that the ESP32-CAM is connected to.
The ESP32-CAM should display a web page. To begin video streaming, press the Start
Stream button.
34
Web : www.pragyatmika.co.in Email : [email protected]
At the bottom you can see there is an option to start streaming, you can click con Start
Streaming and see yourself in the video. Maximize the resolution using the Camera Option.
You can move the camera in any direction to see yourself in the video. The Video data is live
Step 11: Copy the IP address since we will be using this IP address to integrate our esp32
35
Web : www.pragyatmika.co.in Email : [email protected]
Now our esp32 Cam is ready to interface with python code
Before starting to work with Python in Visual Studio Code, install the Python extension. This
can be done through the Extensions view (Ctrl+Shift+X), then search for and install the
Navigate to File -> New File and choose Python File. Name your file (e.g.,
color_sorting_robot.py).
Step 4: Copy and paste the color detection code into your newly created Python file.
36
Web : www.pragyatmika.co.in Email : [email protected]
Make sure to adjust the URL variable's value with the dynamic IP address obtained from the
Step 5: Run the Python Script:In the Terminal, navigate to the directory where your Python
cd path/to/your/script
Step 6: Ensure your ESP32-CAM is connected to the same network as your system.
python color_sorting_robot.py
Step 7: Verify Video Feed and Check for Errors. Confirm that a window titled “Color
Detection” appears, displaying the live video feed from the ESP32-CAM. Monitor the
terminal for any error messages related to video capture or network issues.
Step 8: Place multiple-coloured objects in front of the camera to check whether the
detection is accurate. Observe the color counts displayed on the output screen to verify if
the detection and increment are functioning correctly. While Detecting the color, make sure
that the background of object should be plain. There should be proper light in the test area
37
Web : www.pragyatmika.co.in Email : [email protected]
These steps should guide you through setting up, running, and testing the color detection
functionality effectively. Make sure to handle different lighting conditions and recalibrate if
OUTPUT SCREENS
Conclusion:
The color detection and sorting robot can detect the presence of colors available in a
multicolour object and count and display it on screen. We can mount this setup on a
wheeled robotic platform and it can traverse the area for color detection and sorting.
38
Web : www.pragyatmika.co.in Email : [email protected]