IOT

Industrial Product Counter using ESP32 CAM & OpenCV

In this article, we’ll use the ESP32 CAM Module and OpenCV to create an Industrial Product Counter. The detection is carried out using the OpenCV library and python code on the server, i.e. our computer. The objects are detected utilizing the basic principle of comparing the background color to the color of the object. For example, if the background is white and the object is white, it will not detect the object; however, if the background is white and the object is a different color, it will definitely detect the thing.

This project uses the ESP32-CAM module, which is a small camera module with the ESP32-S microprocessor. The OV2640 camera is included, as well as several GPIOs for connecting peripherals.

In this post, we’ll go over the device’s capabilities, pin descriptions, and how to program it with an FTDI module. Apart from that, we’ll install Python and the necessary libraries. Later, we’ll go over the Python code for the Industrial Product Counter with ESP32 CAM and OpenCV that we’ll be using. This is an important tutorial because it will allow you to apply any type of image processing or machine learning on live video without having to write code in the Arduino IDE.

Hardware Required:

  • ESP32-CAM Board-AI-Thinker ESP32 Camera Module
  • FTDI Module-USB-to-TTL Converter Module
  • USB Cable-5V Mini-USB Data Cable
  • Jumper Wires-Female to Female Connectors

ESP32 CAM Module

The ESP32 Based Camera Module was developed by AI-Thinker.  The controller contains a Wi-Fi + Bluetooth/BLE chip and is powered by a 32-bit CPU. It has a 520 KB internal SRAM and an external 4M PSRAM. UART, SPI, I2C, PWM, ADC, and DAC are all supported by its GPIO Pins.

The module is compatible with the OV2640 Camera Module, which has a camera resolution of 1600 x 1200 pixels. A 24-pin gold plated connector links the camera to the ESP32 CAM Board. A 4GB SD Card can be used on the board. The photographs captured are saved on the SD Card.

ESP32-CAM Features 

  • The smallest 802.11b/g/n Wi-Fi BT SoC module.
  • Low power 32-bit CPU, can also serve the application processor.
  • Up to 160MHz clock speed, summary computing power up to 600 DMIPS.
  • Built-in 520 KB SRAM, external 4MPSRAM.
  • Supports UART/SPI/I2C/PWM/ADC/DAC.
  • Support OV2640 and OV7670 cameras, built-in flash lamp.
  • Support image WiFI upload.
  • Supports TF card.
  • Supports multiple sleep modes.
  • Embedded Lwip and FreeRTOS.
  • Supports STA/AP/STA+AP operation mode.
  • Support Smart Config/AirKiss technology.
  • Support for serial port local and remote firmware upgrades (FOTA).

ESP32-CAM FTDI Connection

There is no programmer chip on the PCB. So, any form of USB-to-TTL Module can be used to program this board. FTDI Modules based on the CP2102 or CP2104 chip, or any other chip, are widely accessible.

  • Connect the FTDI Module to the ESP32 CAM Module as shown below.
ESP32 CAM FTDI Module Connection
ESP32-CAMFTDI Programmer
GNDGND
5VVCC
U0RTX
U0TRX
GPIO0GND

Connect the ESP32’s 5V and GND pins to the FTDI Module’s 5V and GND. Connect the Rx to UOT and the Tx to UOR Pin in the same way. The most crucial thing is that you must connect the IO0 and GND pins. The device will now be in programming mode. You can remove it once the programming is completed.

Project PCB Gerber File & PCB Ordering Online

If you don’t want to put the circuit together on a breadboard and instead prefer a PCB. EasyEDA s online Circuit Schematics & PCB Design tool was used to create the PCB Board for the ESP32 CAM Board. The PCB appears as seen below.

The Gerber File for the PCB is given below. You can simply download the Gerber File and order the PCB from https://www.nextpcb.com/

Download Gerber File: ESP32-CAM Multipurpose PCB

Now you can visit the NextPCB official website by clicking here: So you will be directed to the NextPCB website

  • You can now upload the Gerber File to the Website and place an order. The PCB quality is excellent. That is why the majority of people entrust NextPCB with their PCB and PCBA needs.
  • The components can be assembled on the PCB Board.

Installing ESP32CAM Library

Another streaming process will be used instead of the general ESP webserver example. As a result, another ESPCAM library is required. On the ESP32 microcontroller, the esp32cam library provides an object-oriented API for using the OV2640 camera. It’s an esp32-camera library wrapper.

Download the zip library as shown in the image from the following Github Link

After downloading, unzip the library and place it in the Arduino Library folder. To do so, follow the instructions below:

Open Arduino -> Sketch -> Include Library -> Add .ZIP Library… -> Navigate to downloaded zip file -> add

Source Code/Program for ESP32 CAM Module

Object Counting with ESP32 CAM Module source code is available here. Copy and paste the code into the Arduino IDE.

#include <WebServer.h>
#include <WiFi.h>
#include <esp32cam.h>
const char* WIFI_SSID = “ssid”;
const char* WIFI_PASS = “password”;
WebServer server(80);
static auto loRes = esp32cam::Resolution::find(320, 240);
static auto midRes = esp32cam::Resolution::find(350, 530);
static auto hiRes = esp32cam::Resolution::find(800, 600);
void serveJpg()
{
auto frame = esp32cam::capture();
if (frame == nullptr) {
Serial.println(“CAPTURE FAIL”);
server.send(503, “”, “”);
return;
}
Serial.printf(“CAPTURE OK %dx%d %db\n”, frame->getWidth(), frame->getHeight(),
static_cast<int>(frame->size()));
server.setContentLength(frame->size());
server.send(200, “image/jpeg”);
WiFiClient client = server.client();
frame->writeTo(client);
}
Void handleJpgLo()
{
if (!esp32cam::Camera.changeResolution(loRes)) {
Serial.println(“SET-LO-RES FAIL”);
}
serveJpg();
}
Void handleJpgHi()
{
if (!esp32cam::Camera.changeResolution(hiRes)) {
Serial.println(“SET-HI-RES FAIL”);
}
serveJpg();
}
Void handleJpgMid()
{
if (!esp32cam::Camera.changeResolution(midRes)) {
Serial.println(“SET-MID-RES FAIL”);
}
serveJpg();
}
Void setup(){
Serial.begin(115200);
Serial.println();
{
using namespace esp32cam;
Config cfg;
cfg.setPins(pins::AiThinker);
cfg.setResolution(hiRes);
cfg.setBufferCount(2);
cfg.setJpeg(80);
bool ok = Camera.begin(cfg);
Serial.println(ok ? “CAMERA OK” : “CAMERA FAIL”);
}
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.print(“http://”);
Serial.println(WiFi.localIP());
Serial.println(” /cam-lo.jpg”);
Serial.println(” /cam-hi.jpg”);
Serial.println(” /cam-mid.jpg”);
server.on(“/cam-lo.jpg”, handleJpgLo);
server.on(“/cam-hi.jpg”, handleJpgHi);
server.on(“/cam-mid.jpg”, handleJpgMid);
server.begin();
}
Void loop()
{
server.handleClient();
}

You must make a little adjustment to the code before uploading it. Change the SSID and password variables to match the WiFi network you’re using.

Compile the code and upload it to the ESP32 CAM Board. However, you must follow a few steps each time you post.

  • When you push the upload button, make sure the IO0 pin is shorted to the ground.
  • If you notice dots and dashes during uploading, immediately press the reset button.
  • Remove the I01 pin shorting with Ground and push the reset button one more after the code has been uploaded.
  • If the output is still not the Serial monitor, push the reset button once again.

Now you can see a similar output as in the image below.

Now, you’ve completed half of the task.

Python Library Installation

  • In order for the live video stream to appear on our computer, we must develop a Python script that allows us to retrieve the video frames. The first step is to get Python installed. Go to python.org and download Python.
  • Once downloaded, install Python.

Install NumPy and OpenCV libraries from the command prompt.

  • type: pip install numpy and press enter. After the installation is done.
  • type: pip install OpenCV-python and press enter.

Now open Idle or another Python code editor.

Python Code + Industrial Product Counter with ESP32 CAM

In the previous post, we discussed color detection and object tracking methods. For further information, see ESP32 CAM Color Detection & Tracking. We’ll use the same way for the Product Counter with ESP32 CAM as well.

The python code employs a step-by-step picture or frame conversion approach to detect the object. It tries to convert the RGB image to Grayscale first so that the difference in color-magnitude is immediately seen and mathematical operations are simple. After that, we blur the image to blend in the colors; now comes the canny edge detection, which quickly recognizes the edges; last, we dilate the image to appropriately combine the edges discovered. After detecting edges, we retrieve the number of closed figures.

The whole Python Script code for Industrial Product Counter or Object Counting with ESP32 CAM and OpenCV is available here. Now open Idle or any other Python code editor. Then, in the editor, copy and paste the code below.

import cv2
import urllib.request
import numpy as np
url=’http://192.168.1.61/’
##”’cam.bmp / cam-lo.jpg /cam-hi.jpg / cam.mjpeg ”’
cv2.namedWindow(“live transmission”, cv2.WINDOW_AUTOSIZE)
while True:
img_resp=urllib.request.urlopen(url+’cam-lo.jpg’)
imgnp=np.array(bytearray(img_resp.read()),dtype=np.uint8)
img=cv2.imdecode(imgnp,-1)

gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
canny=cv2.Canny(cv2.GaussianBlur(gray,(11,11),0),30,150,3)
dilated=cv2.dilate(canny,(1,1),iterations=2)
(Cnt,_)=cv2.findContours(dilated.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
k=img
cv2.drawContours(k,cnt,-1,(0,255,0),2)
cv2.imshow(“mit contour”,canny)


cv2.imshow(“live transmission”,img)
key=cv2.waitKey(5)

if key==ord(‘q’):
break
elif key==ord(‘a’):
cow=len(cnt)
print(cow)


cv2.destroyAllWindows()

Update the URL variable in the above code with the IP address copied from the Arduino Serial Monitor. Then save and run the code.

Testing the Object Counting with ESP32 CAM

When you run the code, a pop-up window called “Live Transmission” appears on the desktop, displaying live video, and another window called “mit contour” emerges on the desktop, displaying detected edges.

I tried to count playing cards in the images below.

Python Monitor displays the counted object. I utilized 6 playing cards in front of the ESP32 CAM in this experiment. Six cards were displayed on the monitor.

As shown above, you can count a variety of objects. Using ESP32 CAM and OpenCV, you can create your own Industrial Product Counter.

Conclusion: 

I hope all of you understand how to design an Industrial Product Counter using ESP32 CAM & OpenCV/. We will be back soon with more informative blogs soon

Leave a Reply

Your email address will not be published.