Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
OpenCV By Example
OpenCV By Example

OpenCV By Example: Enhance your understanding of Computer Vision and image processing by developing real-world projects in OpenCV 3

Arrow left icon
Profile Icon Millán Escrivá Profile Icon Joshi Profile Icon Vinícius G. Mendonça
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
eBook Jan 2016 296 pages 1st Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Millán Escrivá Profile Icon Joshi Profile Icon Vinícius G. Mendonça
Arrow right icon
€32.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (5 Ratings)
eBook Jan 2016 296 pages 1st Edition
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

OpenCV By Example

Chapter 2. An Introduction to the Basics of OpenCV

After covering the installation of OpenCV on different operating systems in Chapter 1, Getting Started with OpenCV, we are going to introduce the basics of OpenCV development in this chapter.

In this chapter, you will learn how to create your project using CMake.

We will also introduce the image basic data structures, matrices, and other structures that are required in our projects.

We will learn how to save our variables and data in files using the XML/YAML persistence OpenCV functions.

In this chapter, we will cover the following topics:

  • Configuring projects with CMake
  • Reading/writing images from/to disk
  • Reading videos and accessing camera devices
  • The main image structures (matrices)
  • Other important and basic structures (vectors, scalars, and so on)
  • An introduction to basic matrix operations
  • File storage operations with the XML/YAML persistence OpenCV API

Basic CMake configuration files

To configure and check all the required dependencies of our project, we are going to use CMake; but it is not mandatory, so we can configure our project in any other tool or IDE such as Makefiles or Visual Studio. However, CMake is the most portable way to configure multiplatform C++ projects.

CMake uses configuration files called CMakeLists.txt, where the compilation and dependency processes are defined. For a basic project, based on an executable build from one source code file, a two-line CMakeLists.txt file is all that is needed. The file looks like this:

cmake_minimum_required (VERSION 2.6)
project (CMakeTest)
add_executable(${PROJECT_NAME} main.cpp)

The first line defines the minimum version of CMake required. This line is mandatory in our CMakeLists.txt file and allows you to use the cmake functionality defined from a given version defined in the second line; it defines the project name. This name is saved in a variable called PROJECT_NAME.

The last line...

Creating a library

CMake allows you to create libraries, which are indeed used by the OpenCV build system. Factorizing the shared code among multiple applications is a common and useful practice in software development. In big applications or when the common code is shared in multiple applications, this practice is very useful.

In this case, we do not create a binary executable; instead, we create a compiled file that includes all the functions, classes, and so on, developed. We can then share this library file with the other applications without sharing our source code.

CMake includes the add_library function for this purpose:

# Create our hello library
add_library(Hello hello.cpp hello.h)

# Create our application that uses our new library
add_executable(executable main.cpp)

# Link our executable with the new library
target_link_libraries( executable Hello )

The lines starting with # add comments and are ignored by CMake.

The add_library(Hello hello.cpp hello.h) command defines our new library...

Managing dependencies

CMake has the ability to search our dependencies and external libraries, giving us the facility to build complex projects depending on external components in our projects and by adding some requirements.

In this book, the most important dependency is, of course, OpenCV, and we will add it to all our projects:

cmake_minimum_required (VERSION 2.6)
cmake_policy(SET CMP0012 NEW)
PROJECT(Chapter2)
# Requires OpenCV
FIND_PACKAGE( OpenCV 3.0.0 REQUIRED )
# Show a message with the opencv version detected
MESSAGE("OpenCV version : ${OpenCV_VERSION}")
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
# Create a variable called SRC
SET(SRC main.cpp )
# Create our executable
ADD_EXECUTABLE( ${PROJECT_NAME} ${SRC} )
# Link our library
TARGET_LINK_LIBRARIES( ${PROJECT_NAME} ${OpenCV_LIBS} )

Now, let's understand the working of the script:

cmake_minimum_required (VERSION 2.6)
cmake_policy(SET CMP0012 NEW)
PROJECT(Chapter2)

The first line defines...

Making the script more complex

In this section, we will show you a more complex script that includes subfolders, libraries, and executables, all in only two files and a few lines, as shown in this script.

It's not mandatory to create multiple CMakeLists.txt files because we can specify everything in the main CMakeLists.txt file. It is more common to use different CMakeLists.txt files for each project subfolder, making it more flexible and portable.

This example has a code structure folder that contains one folder for the utils library and the other for the root folder, which contains the main executable:

CMakeLists.txt
main.cpp
utils/
  CMakeLists.txt
  computeTime.cpp
  computeTime.h
  logger.cpp
  logger.h
  plotting.cpp
  plotting.h

Then, we need to define two CMakeLists.txt files: one in the root folder and the other in the utils folder. The CMakeLists.txt root folder file has the following contents:

cmake_minimum_required (VERSION 2.6)
project (Chapter2)

# Opencv Package required...

Images and matrices

The most important structure in a Computer Vision is without any doubt the images. The image in Computer Vision is a representation of the physical world captured with a digital device. This picture is only a sequence of numbers stored in a matrix format, as shown in the following image. Each number is a measurement of the light intensity for the considered wavelength (for example, red, green, or blue in color images) or for a wavelength range (for panchromatic devices). Each point in an image is called a pixel (for a picture element), and each pixel can store one or more values depending on whether it is a gray, black, or white image (called a binary image as well) that stores only one value, such as 0 or 1, a gray-scale-level image that can store only one value, or a color image that can store three values. These values are usually integer numbers between 0 and 255, but you can use the other range. For example, 0 to 1 in a floating point numbers such as HDRI (High...

Basic CMake configuration files


To configure and check all the required dependencies of our project, we are going to use CMake; but it is not mandatory, so we can configure our project in any other tool or IDE such as Makefiles or Visual Studio. However, CMake is the most portable way to configure multiplatform C++ projects.

CMake uses configuration files called CMakeLists.txt, where the compilation and dependency processes are defined. For a basic project, based on an executable build from one source code file, a two-line CMakeLists.txt file is all that is needed. The file looks like this:

cmake_minimum_required (VERSION 2.6)
project (CMakeTest)
add_executable(${PROJECT_NAME} main.cpp)

The first line defines the minimum version of CMake required. This line is mandatory in our CMakeLists.txt file and allows you to use the cmake functionality defined from a given version defined in the second line; it defines the project name. This name is saved in a variable called PROJECT_NAME.

The last line...

Creating a library


CMake allows you to create libraries, which are indeed used by the OpenCV build system. Factorizing the shared code among multiple applications is a common and useful practice in software development. In big applications or when the common code is shared in multiple applications, this practice is very useful.

In this case, we do not create a binary executable; instead, we create a compiled file that includes all the functions, classes, and so on, developed. We can then share this library file with the other applications without sharing our source code.

CMake includes the add_library function for this purpose:

# Create our hello library
add_library(Hello hello.cpp hello.h)

# Create our application that uses our new library
add_executable(executable main.cpp)

# Link our executable with the new library
target_link_libraries( executable Hello )

The lines starting with # add comments and are ignored by CMake.

The add_library(Hello hello.cpp hello.h) command defines our new library...

Managing dependencies


CMake has the ability to search our dependencies and external libraries, giving us the facility to build complex projects depending on external components in our projects and by adding some requirements.

In this book, the most important dependency is, of course, OpenCV, and we will add it to all our projects:

cmake_minimum_required (VERSION 2.6)
cmake_policy(SET CMP0012 NEW)
PROJECT(Chapter2)
# Requires OpenCV
FIND_PACKAGE( OpenCV 3.0.0 REQUIRED )
# Show a message with the opencv version detected
MESSAGE("OpenCV version : ${OpenCV_VERSION}")
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
# Create a variable called SRC
SET(SRC main.cpp )
# Create our executable
ADD_EXECUTABLE( ${PROJECT_NAME} ${SRC} )
# Link our library
TARGET_LINK_LIBRARIES( ${PROJECT_NAME} ${OpenCV_LIBS} )

Now, let's understand the working of the script:

cmake_minimum_required (VERSION 2.6)
cmake_policy(SET CMP0012 NEW)
PROJECT(Chapter2)

The first line defines the minimum...

Making the script more complex


In this section, we will show you a more complex script that includes subfolders, libraries, and executables, all in only two files and a few lines, as shown in this script.

It's not mandatory to create multiple CMakeLists.txt files because we can specify everything in the main CMakeLists.txt file. It is more common to use different CMakeLists.txt files for each project subfolder, making it more flexible and portable.

This example has a code structure folder that contains one folder for the utils library and the other for the root folder, which contains the main executable:

CMakeLists.txt
main.cpp
utils/
  CMakeLists.txt
  computeTime.cpp
  computeTime.h
  logger.cpp
  logger.h
  plotting.cpp
  plotting.h

Then, we need to define two CMakeLists.txt files: one in the root folder and the other in the utils folder. The CMakeLists.txt root folder file has the following contents:

cmake_minimum_required (VERSION 2.6)
project (Chapter2)

# Opencv Package required
FIND_PACKAGE...

Images and matrices


The most important structure in a Computer Vision is without any doubt the images. The image in Computer Vision is a representation of the physical world captured with a digital device. This picture is only a sequence of numbers stored in a matrix format, as shown in the following image. Each number is a measurement of the light intensity for the considered wavelength (for example, red, green, or blue in color images) or for a wavelength range (for panchromatic devices). Each point in an image is called a pixel (for a picture element), and each pixel can store one or more values depending on whether it is a gray, black, or white image (called a binary image as well) that stores only one value, such as 0 or 1, a gray-scale-level image that can store only one value, or a color image that can store three values. These values are usually integer numbers between 0 and 255, but you can use the other range. For example, 0 to 1 in a floating point numbers such as HDRI (High...

Reading/writing images


After the introduction of this matrix, we are going to start with the basics of the OpenCV code. Firstly, we need to learn how to read and write images:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

// OpenCV includes
#include "opencv2/core.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;

int main( int argc, const char** argv )
{
  // Read images
  Mat color= imread("../lena.jpg");
  Mat gray= imread("../lena.jpg", 0);
  
  // Write images
  imwrite("lenaGray.jpg", gray);
  
  // Get same pixel with opencv function
  int myRow=color.cols-1;
  int myCol=color.rows-1;
  Vec3b pixel= color.at<Vec3b>(myRow, myCol);
  cout << "Pixel value (B,G,R): (" << (int)pixel[0] << "," << (int)pixel[1] << "," << (int)pixel[2] << ")" << endl;
  
  // show images
  imshow("Lena BGR", color);
  imshow("Lena Gray", gray);
  // wait for any key press
  waitKey(0);
  return 0;...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get to grips with the basics of Computer Vision and image processing
  • This is a step-by-step guide to developing several real-world Computer Vision projects using OpenCV 3
  • This book takes a special focus on working with Tesseract OCR, a free, open-source library to recognize text in images

Description

Open CV is a cross-platform, free-for-use library that is primarily used for real-time Computer Vision and image processing. It is considered to be one of the best open source libraries that helps developers focus on constructing complete projects on image processing, motion detection, and image segmentation. Whether you are completely new to the concept of Computer Vision or have a basic understanding of it, this book will be your guide to understanding the basic OpenCV concepts and algorithms through amazing real-world examples and projects. Starting from the installation of OpenCV on your system and understanding the basics of image processing, we swiftly move on to creating optical flow video analysis or text recognition in complex scenes, and will take you through the commonly used Computer Vision techniques to build your own Open CV projects from scratch. By the end of this book, you will be familiar with the basics of Open CV such as matrix operations, filters, and histograms, as well as more advanced concepts such as segmentation, machine learning, complex video analysis, and text recognition.

Who is this book for?

If you are a software developer with a basic understanding of Computer Vision and image processing and want to develop interesting Computer Vision applications with Open CV, this is the book for you. Knowledge of C++ is required.

What you will learn

  • Install OpenCV 3 on your operating system
  • Create the required CMake scripts to compile the C++ application and manage its dependencies
  • Get to grips with the Computer Vision workflows and understand the basic image matrix format and filters
  • Understand the segmentation and feature extraction techniques
  • Remove backgrounds from a static scene to identify moving objects for video surveillance
  • Track different objects in a live video using various techniques
  • Use the new OpenCV functions for text detection and recognition with Tesseract

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 22, 2016
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287077
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Jan 22, 2016
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287077
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 115.97
OpenCV 3 Blueprints
€36.99
Arduino Wearable Projects
€36.99
OpenCV By Example
€41.99
Total 115.97 Stars icon

Table of Contents

12 Chapters
1. Getting Started with OpenCV Chevron down icon Chevron up icon
2. An Introduction to the Basics of OpenCV Chevron down icon Chevron up icon
3. Learning the Graphical User Interface and Basic Filtering Chevron down icon Chevron up icon
4. Delving into Histograms and Filters Chevron down icon Chevron up icon
5. Automated Optical Inspection, Object Segmentation, and Detection Chevron down icon Chevron up icon
6. Learning Object Classification Chevron down icon Chevron up icon
7. Detecting Face Parts and Overlaying Masks Chevron down icon Chevron up icon
8. Video Surveillance, Background Modeling, and Morphological Operations Chevron down icon Chevron up icon
9. Learning Object Tracking Chevron down icon Chevron up icon
10. Developing Segmentation Algorithms for Text Recognition Chevron down icon Chevron up icon
11. Text Recognition with Tesseract Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(5 Ratings)
5 star 40%
4 star 40%
3 star 0%
2 star 0%
1 star 20%
Placeholder Apr 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good book for beginners to explore both - OpenCV and Image Processing. I am a 9 years experienced .Net developer but I had no working knowledge of OpenCV - this book helped me a lot.
Amazon Verified review Amazon
Amazon Customer Mar 15, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had the opportunity to review the book "OpenCV by Example" written by Prateek Joshi, David Millan Escriva and Vinicius Godoy for Packt Publishing. The books helps you to integrate OpenCV 3 into your projects in the beginning by providing step by step instructions but also provides detailed background infor mations on various areas of computer vision. If you need to digg even deeper you also get links to the original scientific research papers. the areas covered range from computer vision basics like filtering or image manipulation to complex areas like object tracking or text recognition. So if you need to add vision to your robotics project, mobile application, media art project, desktop application, ... and always wondered how to do it this is a book you should read.
Amazon Verified review Amazon
Sandy Feb 09, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Good book for beginner & excellent code & example.Book print quality is good,But why Images are Black & White, it should be in colors.
Amazon Verified review Amazon
Pourya Hoseini Dec 10, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Useful book to get an initial hands on how OpenCV works, and how are its data types used.
Amazon Verified review Amazon
Keith Sloan Sep 26, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Do not buy this book . The example install information does not work and to get support you have to buy from packtpub.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.