In the ever-evolving landscape of programming languages, Python has established itself as a favorite among developers for its simplicity, readability, and extensive libraries. Moreover, we love Python. 

pybind11 — Seamless operability between C++11 and Python

Unlocking the Power of C++ with Python

In the ever-evolving landscape of programming languages, Python has established itself as a favorite among developers for its simplicity, readability, and extensive libraries. Moreover, we love Python. 

However, there are times when the raw speed and low-level control offered by languages like C++ become essential for optimizing performance-critical code. What if you could seamlessly combine the ease of Python with the raw power of C++? This remarkable synergy is precisely where Pybind11 takes centre stage. With Pybind11, a seamless integration of Python’s user-friendly elegance with the robust might of C++ unfolds before us.

Pybind11 or  Boost.Python ?

Pybind11 is a header-only library, meaning that you don’t need to compile a separate shared library, where as boost python has been around for a long time and may involve more complex syntax and setup.

Compared to Boost, pybind11 requires less boilerplate code. Its syntax is simpler and more concise. It has strong support for Python3, which is becoming the standard choice for python development. 

For detailed information on using pybind11, you can refer to the official documentation. Here, we are focussing more on how we can effectively use Pybind11 for some AI-based applications.

Topics We Will Cover

  • Getting started
  • Exposing C++ Class
  • Handling NumPy Arrays
  • Pybind11’s Pythonic Oasis
  • Common challenges in wrapping C++ APIs
  • Wrap-up

Getting Started

Before diving into the world of pybind11, you’ll need to set up your development environment.

Installing Python 3.10 Using Conda

  • Create Python 3.10 environment
  • Clone the Pybind11 repository

conda create -n pybind_env python=3.10
git clone https://github.com/pybind/pybind11.git

Exposing C++ Class

We’ll start by defining a C++ class using Pybind11 that encapsulates our image processing operations. Pybind11’s intuitive syntax makes it a breeze to create this bridge between Python and C++

Make sure you have OpenCV installed in your machine. If not, either build from source, or simply:

sudo apt-get install libopencv-dev

Define CmakeList:

cmake_minimum_required(VERSION 3.10)

set(PROJECT_NAME "myLib")
project(${PROJECT_NAME})
set(CMAKE_CXX_STANDARD 20)
set(PYBIND11_PYTHON_VERSION 3.10)
# set(CMAKE_CXX_FLAGS "-Wall -Wextra -fPIC")
add_subdirectory(pybind11)
find_package(OpenCV REQUIRED)
pybind11_add_module(${PROJECT_NAME} process.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC
${OpenCV_INCLUDE_DIRS})

target_link_libraries(${PROJECT_NAME} PUBLIC
${OpenCV_LIBS})
target_compile_definitions(${PROJECT_NAME}
PRIVATE VERSION_INFO=${EXAMPLE_VERSION_INFO})

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <opencv2/opencv.hpp>
#include <iostream>
namespace py = pybind11;
class CVutils
{
private:
    std::string filename;

public:
    py::array_t<uint8_t> process_image(std::string &filename, int width, intheight)

{
    cv::Mat input_image = cv::imread(filename, cv::IMREAD_COLOR);
    // Perform image processing, such as resizing
    cv::Mat resized_image;
    cv::resize(input_image, resized_image, cv::Size(width, height));
    return py::array({height, width,             static_cast<int>(resized_image.channels())}, resized_image.data);
}

Define a simple image utils class
Build

mkdir build && cd build
cmake ..
make

├── CMakeCache.txt
├── CMakeFiles
├── cmake_install.cmake
├── Makefile
├── myLib.cpython-310-x86_64-linux-gnu.so
└── pybind11

Python Test Suite

from build.myLib import CVutils
cv_obj = CVutils()
py_list_obj = PyListInt()
processed_image = cv_obj.process_image("flower.jpeg", 640, 480)
print("Resized: ", processed_image.shape)

Handling NumPy Arrays

A simple array addition

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <opencv2/opencv.hpp>
#include <iostream>
namespace py = pybind11;
using PyArrayFloat = py::array_t<double>;
PyArrayFloat add_arrays(PyArrayFloat input1, PyArrayFloat input2)
{
    py::buffer_info buf1 = input1.request();
    py::buffer_info buf2 = input2.request();
    if (buf1.ndim != 1 || buf2.ndim != 1)
        throw std::runtime_error("Number of dimensions must be one");
    if (buf1.size != buf2.size)
        throw std::runtime_error("Input shapes must match");
    PyArrayFloat result = PyArrayFloat(buf1.size);
    py::buffer_info buf3 = result.request();
    double *ptr1 = static_cast<double *>(buf1.ptr);
    double *ptr2 = static_cast<double *>(buf2.ptr);
    double *ptr3 = static_cast<double *>(buf3.ptr);
    for (size_t idx = 0; idx < buf1.shape[0]; idx++)
    ptr3[idx] = ptr1[idx] + ptr2[idx];
        return result;
}
};

Python Test Suite

import numpy as np
from build.myLib import add_arrays

arr1 = np.array([1, 2])
arr2 = np.array([5, 6])
print(add_arrays(arr1, arr2))

Pybind11’s Pythonic Oasis

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <opencv2/opencv.hpp>
#include <iostream>

namespace py = pybind11;
using PyListInt = std::vector<int64_t>;
py::class_<PyListInt>(m, "MyList")
    .def(py::init<>())
    .def("append", (void(PyListInt::*)(const int &)) & PyListInt::push_back)
    .def("clear", (void(PyListInt::*)()) & PyListInt::clear)
    .def("pop", (void(PyListInt::*)()) & PyListInt::pop_back)
    .def("__len__", [](const PyListInt &v)
        { return v.size(); })
    .def("__get__", [](const PyListInt &v, int idx)
        { return v[idx]; })

    .def("print", [](const PyListInt &l)
    {
        fprintf(stderr, "[");
        auto it = l.begin();
        if (it != l.end()) {
            fprintf(stderr, "%d", *it++);            

}
        for (; it != l.end(); ++it) {
            fprintf(stderr, ", %d", *it);
            }

        fprintf(stderr, "]\n");   
})

Python Test Suite

from build.myLib import MyList
my_list = MyList()
my_list.append(1)
my_list.append(19)
my_list.print()
my_list.pop()
my_list.print()

Common challenges in wrapping C++ APIs

We might encounter several challenges which will require careful consideration and attention. These are some of the challanges you may face:

Type Representation Pybind11 provides tools for handling custom data structrures, Its important to understand them before using
Exception Handling C++ exceptions needs to be properly translated into python exceptions and vice versa
Callbacks and Lamdas Execution context and memory management can differ
Performance Optimization Achieving performance rewuire additional efforts, such as minimizing data copies / leveraging multi threading

These challanges offer a glimpse into the intricacies of binding C++ APIs with Pybind11.

Wrap-up

The examples presented here provide a foundational understanding; this merely scratches the surface of what PyBind11 can do. From the initial steps of setting up the environment and understanding the fundamental concepts to some more useful cases like handling NumPy and OpenCV libraries, you might have gained a comprehensive understanding of how Pybind11 bridges the gap between Python and C++.

The key takeaway is that Pybind11 empowers the user to harness the strengths of both C++ and Python, enabling to create high-performance, versatile and accessible software solutions. Especially in cases like developing AI applications, game engines, data analysis tools, or any other projects that demands the best of both languages, Pybind11 is a formidable ally.

References

  1. https://pybind11.readthedocs.io/en/stable/advanced/classes.html
  2. https://www.boost.org/doc/libs/1_81_0/libs/python/doc/html/index.html
  3. https://en.cppreference.com/w/cpp/language/reference
  4. https://chat.openai.com/chat

Scroll to Top

Human Pose Detection & Classification

Some Buildings in a city

Features:

  • Suitable for real time detection on edge devices
  • Detects human pose / key points and recognizes movement / behavior
  • Light weight deep learning models with good accuracy and performance

Target Markets:

  • Patient Monitoring in Hospitals
  • Surveillance
  • Sports/Exercise Pose Estimation
  • Retail Analytics

OCR / Pattern Recognition

Some Buildings in a city

Use cases :

  • Analog dial reading
  • Digital meter reading
  • Label recognition
  • Document OCR

Highlights :

  • Configurable for text or pattern recognition
  • Simultaneous Analog and Digital Dial reading
  • Lightweight implementation

Behavior Monitoring

Some Buildings in a city

Use cases :

  • Fall Detection
  • Social Distancing

Highlights :

  • Can define region of interest to monitor
  • Multi-subject monitoring
  • Multi-camera monitoring
  • Alarm triggers

Attire & PPE Detection

Some Buildings in a city

Use cases :

  • PPE Checks
  • Disallowed attire checks

Use cases :

  • Non-intrusive adherence checks
  • Customizable attire checks
  • Post-deployment trainable

 

Request for Video





    Real Time Color Detection​

    Use cases :

    • Machine vision applications such as color sorter or food defect detection

    Highlights :

    • Color detection algorithm with real time performance
    • Detects as close to human vison as possible including color shade discrimination
    • GPGPU based algorithm on NVIDIA CUDA and Snapdragon Adreno GPU
    • Extremely low latency (a few 10s of milliseconds) for detection
    • Portable onto different hardware platforms

    Missing Artifact Detection

    Use cases :

    • Detection of missing components during various stages of manufacturing of industrial parts
    • Examples include : missing nuts and bolts, missing ridges, missing grooves on plastic and metal blocks

    Highlights :

    • Custom neural network and algorithms to achieve high accuracy and inference speed
    • Single-pass detection of many categories of missing artifacts
    • In-field trainable neural networks with dynamic addition of new artifact categories
    • Implementation using low cost cameras and not expensive machine-vision cameras
    • Learning via the use of minimal training sets
    • Options to implement the neural network on GPU or CPU based systems

    Real Time Manufacturing Line Inspection

    Use cases :

    • Detection of defects on the surface of manufactured goods (metal, plastic, glass, food, etc.)
    • Can be integrated into the overall automated QA infrastructure on an assembly line.

    Highlights :

    • Custom neural network and algorithms to achieve high accuracy and inference speed
    • Use of consumer or industrial grade cameras
    • Requires only a few hundred images during the training phase
    • Supports incremental training of the neural network with data augmentation
    • Allows implementation on low cost GPU or CPU based platforms

    Ground Based Infrastructure analytics

    Some Buildings in a city

    Use cases :

    • Rail tracks (public transport, mining, etc.)
    • Highways
    • Tunnels

    Highlights :

    • Analysis of video and images from 2D & 3D RGB camera sensors
    • Multi sensor support (X-ray, thermal, radar, etc.)
    • Detection of anomalies in peripheral areas of core infrastructure (Ex: vegetation or stones near rail tracks)

    Aerial Analytics

    Use cases :

    • Rail track defect detection
    • Tower defect detection: Structural analysis of Power
      transmission towers
    • infrastructure mapping

    Highlights :

    • Defect detection from a distance
    • Non-intrusive
    • Automatic video capture with perfectly centered ROI
    • No manual intervention is required by a pilot for
      camera positioning

    SANJAY JAYAKUMAR

    Co-founder & CEO

     

    Founder and Managing director of Ignitarium, Sanjay has been responsible for defining Ignitarium’s core values, which encompass the organisation’s approach towards clients, partners, and all internal stakeholders, and in establishing an innovation and value-driven organisational culture.

     

    Prior to founding Ignitarium in 2012, Sanjay spent the initial 22 years of his career with the VLSI and Systems Business unit at Wipro Technologies. In his formative years, Sanjay worked in diverse engineering roles in Electronic hardware design, ASIC design, and custom library development. Sanjay later handled a flagship – multi-million dollar, 600-engineer strong – Semiconductor & Embedded account owning complete Delivery and Business responsibility.

     

    Sanjay graduated in Electronics and Communication Engineering from College of Engineering, Trivandrum, and has a Postgraduate degree in Microelectronics from BITS Pilani.

     

    Request Free Demo




      RAMESH EMANI Board Member

      RAMESH EMANI

      Board Member

      Ramesh was the Founder and CEO of Insta Health Solutions, a software products company focused on providing complete hospital and clinic management solutions for hospitals and clinics in India, the Middle East, Southeast Asia, and Africa. He raised Series A funds from Inventus Capital and then subsequently sold the company to Practo Technologies, India. Post-sale, he held the role of SVP and Head of the Insta BU for 4 years. He has now retired from full-time employment and is working as a consultant and board member.

       

      Prior to Insta, Ramesh had a 25-year-long career at Wipro Technologies where he was the President of the $1B Telecom and Product Engineering Solutions business heading a team of 19,000 people with a truly global operations footprint. Among his other key roles at Wipro, he was a member of Wipro's Corporate Executive Council and was Chief Technology Officer.

       

      Ramesh is also an Independent Board Member of eMIDs Technologies, a $100M IT services company focused on the healthcare vertical with market presence in the US and India.

       

      Ramesh holds an M-Tech in Computer Science from IIT-Kanpur.

      ​Manoj Thandassery

      VP – Sales & Business Development

      Manoj Thandassery is responsible for the India business at Ignitarium. He has over 20 years of leadership and business experience in various industries including the IT and Product Engineering industry. He has held various responsibilities including Geo head at Sasken China, Portfolio head at Wipro USA, and India & APAC Director of Sales at Emeritus. He has led large multi-country teams of up to 350 employees. Manoj was also an entrepreneur and has successfully launched and scaled, via multiple VC-led investment rounds, an Edtech business in the K12 space that was subsequently sold to a global Edtech giant.
      An XLRI alumnus, Manoj divides his time between Pune and Bangalore.

       

      MALAVIKA GARIMELLA​

      General Manager - Marketing

      A professional with a 14-year track record in technology marketing, Malavika heads marketing in Ignitarium. Responsible for all branding, positioning and promotional initiatives in the company, she has collaborated with technical and business teams to further strengthen Ignitarium's positioning as a key E R&D services player in the ecosystem.

      Prior to Ignitarium, Malavika has worked in with multiple global tech startups and IT consulting companies as a marketing consultant. Earlier, she headed marketing for the Semiconductor & Systems BU at Wipro Technologies and worked at IBM in their application software division.

      Malavika completed her MBA in Marketing from SCMHRD, Pune, and holds a B.E. degree in Telecommunications from RVCE, Bengaluru.

       

      PRADEEP KUMAR LAKSHMANAN

      VP - Operations

      Pradeep comes with an overall experience of 26 years across IT services and Academia. In his previous role at Virtusa, he played the role of Delivery Leader for the Middle East geography. He has handled complex delivery projects including the transition of large engagements, account management, and setting up new delivery centers.

      Pradeep graduated in Industrial Engineering and Management, went on to secure an MBA from CUSAT, and cleared UGN Net in Management. He also had teaching stints at his alma mater, CUSAT, and other management institutes like DCSMAT. A certified P3O (Portfolio, Program & Project Management) from the Office of Government Commerce, UK, Pradeep has been recognized for key contributions in the Management domain, at his previous organizations, Wipro & Virtusa.

      In his role as the Head of Operations at Ignitarium, Pradeep leads and manages operational functions such as Resource Management, Procurement, Facilities, IT Infrastructure, and Program Management office.

       

      SONA MATHEW Director – Human Resources

      SONA MATHEW

      AVP – Human Resources

      Sona heads Human Resource functions - Employee Engagement, HR Operations and Learning & Development – at Ignitarium. Her expertise include deep and broad experience in strategic people initiatives, performance management, talent transformation, talent acquisition, people engagement & compliance in the Information Technology & Services industry.

       

      Prior to Ignitarium, Sona has had held diverse HR responsibilities at Litmus7, Cognizant and Wipro.

       

      Sona graduated in Commerce from St. Xaviers College and did her MBA in HR from PSG College of Technology.

       

      ASHWIN RAMACHANDRAN

      Vice President - Sales

      As VP of Sales, Ashwin is responsible for Ignitarium’s go-to-market strategy, business, client relationships, and customer success in the Americas. He brings in over a couple of decades of experience, mainly in the product engineering space with customers from a wide spectrum of industries, especially in the Hi-Tech/semiconductor and telecom verticals.

       

      Ashwin has worked with the likes of Wipro, GlobalLogic, and Mastek, wherein unconventional and creative business models were used to bring in non-linear revenue. He has strategically diversified, de-risked, and grown his portfolios during his sales career.

       

      Ashwin strongly believes in the customer-first approach and works to add value and enhance the experiences of our customers.

       

      AZIF SALY Director – Sales

      AZIF SALY

      Vice President – Sales & Business Development

      Azif is responsible for go-to-market strategy, business development and sales at Ignitarium. Azif has over 14 years of cross-functional experience in the semiconductor product & service spaces and has held senior positions in global client management, strategic account management and business development. An IIM-K alumnus, he has been associated with Wipro, Nokia and Sankalp in the past.

       

      Azif handled key accounts and sales process initiatives at Sankalp Semiconductors. Azif has pursued entrepreneurial interests in the past and was associated with multiple start-ups in various executive roles. His start-up was successful in raising seed funds from Nokia, India. During his tenure at Nokia, he played a key role in driving product evangelism and customer success functions for the multimedia division.

       

      At Wipro, he was involved in customer engagement with global customers in APAC and US.

       

      RAJU KUNNATH Vice President – Enterprise & Mobility

      RAJU KUNNATH

      Distinguished Engineer – Digital

      At Ignitarium, Raju's charter is to architect world class Digital solutions at the confluence of Edge, Cloud and Analytics. Raju has over 25 years of experience in the field of Telecom, Mobility and Cloud. Prior to Ignitarium, he worked at Nokia India Pvt. Ltd. and Sasken Communication Technologies in various leadership positions and was responsible for the delivery of various developer platforms and products.

       

      Raju graduated in Electronics Engineering from Model Engineering College, Cochin and has an Executive Post Graduate Program (EPGP) in Strategy and Finance from IIM Kozhikode.

       

      PRADEEP SUKUMARAN Vice President – Business Strategy & Marketing

      PRADEEP SUKUMARAN

      Vice President - Software Engineering

      Pradeep heads the Software Engineering division, with a charter to build and grow a world-beating delivery team. He is responsible for all the software functions, which includes embedded & automotive software, multimedia, and AI & Digital services

      At Ignitarium, he was previously part of the sales and marketing team with a special focus on generating a sales pipeline for Vision Intelligence products and services, working with worldwide field sales & partner ecosystems in the U.S  Europe, and APAC.

      Prior to joining Ignitarium in 2017, Pradeep was Senior Solutions Architect at Open-Silicon, an ASIC design house. At Open-Silicon, where he spent a good five years, Pradeep was responsible for Front-end, FPGA, and embedded SW business development, marketing & technical sales and also drove the IoT R&D roadmap. Pradeep started his professional career in 2000 at Sasken, where he worked for 11 years, primarily as an embedded multimedia expert, and then went on to lead the Multimedia software IP team.

      Pradeep is a graduate in Electronics & Communication from RVCE, Bangalore.

       

      SUJEET SREENIVASAN Vice President – Embedded

      SUJEET SREENIVASAN

      Vice President – Automotive Technology

       

      Sujeet is responsible for driving innovation in Automotive software, identifying Automotive technology trends and advancements, evaluating their potential impact, and development of solutions to meet the needs of our Automotive customers.

      At Ignitarium, he was previously responsible for the growth and P&L of the Embedded Business unit focusing on Multimedia, Automotive, and Platform software.

      Prior to joining Ignitarium in 2016, Sujeet has had a career spanning more than 16 years at Wipro. During this stint, he has played diverse roles from Solution Architect to Presales Lead covering various domains. His technical expertise lies in the areas of Telecom, Embedded Systems, Wireless, Networking, SoC modeling, and Automotive. He has been honored as a Distinguished Member of the Technical Staff at Wipro and has multiple patents granted in the areas of Networking and IoT Security.

      Sujeet holds a degree in Computer Science from Government Engineering College, Thrissur.

       

      RAJIN RAVIMONY Distinguished Engineer

      RAJIN RAVIMONY

      Distinguished Engineer

       

      At Ignitarium, Rajin plays the role of Distinguished Engineer for complex SoCs and systems. He's an expert in ARM-based designs having architected more than a dozen SoCs and played hands-on design roles in several tens more. His core areas of specialization include security and functional safety architecture (IEC61508 and ISO26262) of automotive systems, RTL implementation of math intensive signal processing blocks as well as design of video processing and related multimedia blocks.

       

      Prior to Ignitarium, Rajin worked at Wipro Technologies for 14 years where he held roles of architect and consultant for several VLSI designs in the automotive and consumer domains.

       

      Rajin holds an MS in Micro-electronics from BITS Pilani.

       

      SIBY ABRAHAM Executive Vice President, Strategy

      SIBY ABRAHAM

      Executive Vice President, Strategy

       

      As EVP, of Strategy at Ignitarium, Siby anchors multiple functions spanning investor community relations, business growth, technology initiatives as well and operational excellence.

       

      Siby has over 31 years of experience in the semiconductor industry. In his last role at Wipro Technologies, he headed the Semiconductor Industry Practice Group where he was responsible for business growth and engineering delivery for all of Wipro’s semiconductor customers. Prior to that, he held a vast array of crucial roles at Wipro including Chief Technologist & Vice President, CTO Office, Global Delivery Head for Product Engineering Services, Business Head of Semiconductor & Consumer Electronics, and Head of Unified Competency Framework. He was instrumental in growing Wipro’s semiconductor business to over $100 million within 5 years and turning around its Consumer Electronics business in less than 2 years. In addition, he was the Engineering Manager for Enthink Inc., a semiconductor IP-focused subsidiary of Wipro. Prior to that, Siby was the Technical Lead for several of the most prestigious system engineering projects executed by Wipro R&D.

       

      Siby has held a host of deeply impactful positions, which included representing Wipro in various World Economic Forum working groups on Industrial IOT and as a member of IEEE’s IOT Steering Committee.

       

      He completed his MTech. in Electrical Engineering (Information and Control) from IIT, Kanpur and his BTech. from NIT, Calicut

       

      SUJEETH JOSEPH Chief Product Officer

      SUJEETH JOSEPH

      Chief Technology Officer

       

      As CTO, Sujeeth is responsible for defining the technology roadmap, driving IP & solution development, and transitioning these technology components into practically deployable product engineering use cases.

       

      With a career spanning over 30+ years, Sujeeth Joseph is a semiconductor industry veteran in the SoC, System and Product architecture space. At SanDisk India, he was Director of Architecture for the USD $2B Removable Products Group. Simultaneously, he also headed the SanDisk India Patenting function, the Retail Competitive Analysis Group and drove academic research programs with premier Indian academic Institutes. Prior to SanDisk, he was Chief Architect of the Semiconductor & Systems BU (SnS) of Wipro Technologies. Over a 19-year career at Wipro, he has played hands-on and leadership roles across all phases of the ASIC and System design flow.

       

      He graduated in Electronics Engineering from Bombay University in 1991.

       

      SUJITH MATHEW IYPE Co-founder & CTO

      SUJITH MATHEW IYPE

      Co-founder & COO

       

      As Ignitarium's Co-founder and COO, Sujith is responsible for driving the operational efficiency and streamlining process across the organization. He is also responsible for the growth and P&L of the Semiconductor Business Unit.

       

      Apart from establishing a compelling story in VLSI, Sujith was responsible for Ignitarium's foray into nascent technology areas like AI, ML, Computer Vision, and IoT, nurturing them in our R&D Lab - "The Crucible".

       

      Prior to founding Ignitarium, Sujith played the role of a VLSI architect at Wipro Technologies for 13 years. In true hands-on mode, he has built ASICs and FPGAs for the Multimedia, Telecommunication, and Healthcare domains and has provided technical leadership for many flagship projects executed by Wipro.

       

      Sujith graduated from NIT - Calicut in the year 2000 in Electronics and Communications Engineering and thereafter he has successfully completed a one-year executive program in Business Management from IIM Calcutta.

       

      RAMESH SHANMUGHAM Co-founder & COO

      RAMESH SHANMUGHAM

      Co-founder & CRO

      As Co-founder and Chief Revenue Officer of Ignitarium, Ramesh has been responsible for global business and marketing as well as building trusted customer relationships upholding the company's core values.

      Ramesh has over 25 years of experience in the Semiconductor Industry covering all aspects of IC design. Prior to Ignitarium, Ramesh was a key member of the senior management team of the semiconductor division at Wipro Technologies. Ramesh has played key roles in Semiconductor Delivery and Pre-sales at a global level.

      Ramesh graduated in Electronics Engineering from Model Engineering College, Cochin, and has a Postgraduate degree in Microelectronics from BITS Pilani.