Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learn OpenCV 4 by Building Projects
Learn OpenCV 4 by Building Projects

Learn OpenCV 4 by Building Projects: Build real-world computer vision and image processing applications with OpenCV and C++ , Second Edition

Arrow left icon
Profile Icon Millán Escrivá Profile Icon Joshi Profile Icon Vinícius G. Mendonça
Arrow right icon
$9.99 $39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5 (2 Ratings)
eBook Nov 2018 310 pages 2nd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Millán Escrivá Profile Icon Joshi Profile Icon Vinícius G. Mendonça
Arrow right icon
$9.99 $39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5 (2 Ratings)
eBook Nov 2018 310 pages 2nd Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learn OpenCV 4 by Building Projects

An Introduction to the Basics of OpenCV

After covering OpenCV installation on different operating systems in Chapter 1, Getting Started with OpenCV, we are going to introduce the basics of OpenCV development in this chapter. It begins with showing how to create our project using CMake. We are going to introduce the basic image data structures and matrices, along with other structures that are required to work in our projects. We are going to introduce how to save our variables and data into 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 (for example, matrices)
  • Other important and basic structures (for example, vectors and scalars)
  • An introduction to basic matrix operations
  • File storage...

Technical requirements

Basic CMake configuration file

To configure and check all the requisite dependencies for our project, we are going to use CMake, but it is not the only way that this can be done; we can configure our project in any other tool or IDE, such as Makefiles or Visual Studio, but CMake is a more portable way to configure multiplatform C++ projects.

CMake uses configuration files called CMakeLists.txt, where the compilation and dependencies process is defined. For a basic project based on an executable built from a single source code file, a CMakeLists.txt file comprising three lines is all that is required. The file looks as follows:

cmake_minimum_required (VERSION 3.0) 
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 us to use the functionality of...

Creating a library

CMake allows us to create libraries used by the OpenCV build system. Factorizing shared code among multiple applications is a common and useful practice in software development. In big applications, or common code shared in multiple applications, this practice is very useful. In this case, we do not create a binary executable, but instead we create a compiled file that includes all the functions, classes, and so on. We can then share this library file with other applications without sharing our source code.

CMake includes the add_library function to this end:

# 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...

Managing dependencies

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

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

    cmake_minimum_required (VERSION 3.0) 
    PROJECT(Chapter2) 
# Requires OpenCV 
    FIND_PACKAGE( OpenCV 4.0.0 REQUIRED ) 
# Show a message with the opencv version detected 
    MESSAGE("OpenCV version : ${OpenCV_VERSION}") 
# Add the paths to the include directories/to the header files include_directories(${OpenCV_INCLUDE_DIRS})
# Add the paths to the compiled libraries/objects link_directories(${OpenCV_LIB_DIR}) # Create a variable called SRC SET(SRC main.cpp) # Create our executable ADD_EXECUTABLE(${PROJECT_NAME...

Making the script more complex

In this section, we are showing a more complex script that includes subfolders, libraries, and executables; all told, just two files and a few lines, as demonstrated in this script. It's not mandatory to create multiple CMakeLists.txt files, because we can specify everything in the main CMakeLists.txt file. However, it is more common to use different CMakeLists.txt files for each project subfolder, thereby making it more flexible and portable.

This example has a code structure folder, which contains one folder for a utils library and 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 have to define two CMakeLists.txt files, one in the root folder and the other in the utils folder. The...

Images and matrices

The most important structure in computer vision is, without doubt, the images. The image in a computer vision is the representation of the physical world captured with a digital device. This picture is only a sequence of numbers stored in a matrix format (refer to the following diagram). 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). Every 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 black and white image (also referred to as a binary image) that stores only one value, such as 0 or 1, a grayscale-level image that stores two values, or a color image that stores three values. These values are usually between 0 and 255 in an integer number...

Reading/writing images

Following the introduction to matrices, we are going to start with the OpenCV code basics. The first thing that we have to learn is 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",CV_LOAD_IMAGE_GRAYSCALE); 

if(! color.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
} // Write images imwrite("lenaGray.jpg", gray); // Get same pixel with opencv function int myRow=color.cols-1; int myCol=color...

Reading videos and cameras

This section introduces you to video and camera reading using this simple example. Before explaining how to read videos or camera input, we want to introduce a new, very useful class that helps us to manage the input command-line parameters. This new class was introduced in OpenCV version 3.0, and is the CommandLineParser class:

// OpenCV command line parser functions 
// Keys accepted by command line parser 
const char* keys = 
{ 
   "{help h usage ? | | print this message}" 
    "{@video | | Video file, if not defined try to use webcamera}" 
}; 

The first thing that we have to do for CommandLineParser is define what parameters we need or allow in a constant char vector; each line has the following pattern:

"{name_param | default_value | description}"

name_param can be preceded with @, which defines this parameter as a...

Other basic object types

We have learned about the Mat and Vec3b classes, but there are many more classes that we have to learn.

In this section, we will learn the most basic object types required in the majority of projects:

  • Vec
  • Scalar
  • Point
  • Size
  • Rect
  • RotatedRect

Vec object type

Vec is a template class mainly for numerical vectors. We can define any type of vector and the number of components:

Vec<double,19> myVector; 

We can also use any of the predefined types:

typedef Vec<uchar, 2> Vec2b; 
typedef Vec<uchar, 3> Vec3b; 
typedef Vec<uchar, 4> Vec4b; 
 
typedef Vec<short, 2> Vec2s; 
typedef Vec<short, 3> Vec3s; 
typedef Vec<short, 4> Vec4s; 
 
typedef Vec<int, 2> Vec2i;...

Basic matrix operations

In this section, we will learn a number of basic and important matrix operations that we can apply to images or any matrix data. We learned how to load an image and store it in a Mat variable, but we can create Mat manually. The most common constructor is giving the matrix a size and type, as follows:

Mat a= Mat(Size(5,5), CV_32F); 
You can create a new matrix linking with a stored buffer from third-party libraries without copying data using this constructor: Mat(size, type, pointer_to_buffer).

The types supported depend on the type of number you want to store and the number of channels. The most common types are as follows:

CV_8UC1 
CV_8UC3 
CV_8UC4 
CV_32FC1 
CV_32FC3 
CV_32FC4
You can create any type of matrix using CV_number_typeC(n), where the number_type is 8 bits unsigned (8U) to 64 float (64F), and where (n) is the number of channels; the number...

Basic data persistence and storage

Before finishing this chapter, we will explore the OpenCV functions to store and read our data. In many applications, such as calibration or machine learning, when we finish performing a number of calculations, we need to save these results to retrieve them in subsequent operations. OpenCV provides an XML/YAML persistence layer to this end.

Writing to FileStorage

To write a file with some OpenCV or other numeric data, we can use the FileStorage class, using a streaming << operator such as STL streaming:

#include "opencv2/opencv.hpp" 
using namespace cv; 
 
int main(int, char** argv) 
{ 
   // create our writer 
    FileStorage fs("test.yml", FileStorage::WRITE);...

Summary

In this chapter, we learned the basics and the most important types and operations of OpenCV, access to images and videos, and how they are stored in matrices. We learned the basic matrix operations and other basic OpenCV classes to store pixels, vectors, and so on. Finally, we learned how to save our data in files to allow them to be read in other applications or other executions.

In the next chapter, we are going to learn how to create our first application, learning the basics of graphical user interfaces that OpenCV provides. We will create buttons and sliders, and introduce some image processing basics.

Left arrow icon Right arrow icon

Key benefits

  • Understand basic OpenCV 4 concepts and algorithms
  • Grasp advanced OpenCV techniques such as 3D reconstruction, machine learning, and artificial neural networks
  • Work with Tesseract OCR, an open-source library to recognize text in images

Description

OpenCV is one of the best open source libraries available, and can help you focus on constructing complete projects on image processing, motion detection, and image segmentation. Whether you’re completely new to computer vision, or have a basic understanding of its concepts, Learn OpenCV 4 by Building Projects – Second edition will be your guide to understanding OpenCV concepts and algorithms through real-world examples and projects. You’ll begin with the installation of OpenCV and the basics of image processing. Then, you’ll cover user interfaces and get deeper into image processing. As you progress through the book, you'll learn complex computer vision algorithms and explore machine learning and face detection. The book then guides you in creating optical flow video analysis and background subtraction in complex scenes. In the concluding chapters, you'll also learn about text segmentation and recognition and understand the basics of the new and improved deep learning module. By the end of this book, you'll be familiar with the basics of Open CV, such as matrix operations, filters, and histograms, and you'll have mastered commonly used computer vision techniques to build OpenCV projects from scratch.

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 OpenCV, Learn OpenCV 4 by Building Projects for you. Prior knowledge of C++ will help you understand the concepts covered in this book.

What you will learn

  • Install OpenCV 4 on your operating system
  • Create CMake scripts to compile your C++ application
  • Understand basic image matrix formats and filters
  • Explore segmentation and feature extraction techniques
  • Remove backgrounds from static scenes to identify moving objects for surveillance
  • Employ various techniques to track objects in a live video
  • Work with new OpenCV functions for text detection and recognition with Tesseract
  • Get acquainted with important deep learning tools for image classification

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2018
Length: 310 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789347623
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
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 30, 2018
Length: 310 pages
Edition : 2nd
Language : English
ISBN-13 : 9781789347623
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 146.97
Hands-On Image Processing with Python
$48.99
Learn OpenCV 4 by Building Projects
$48.99
Mastering OpenCV 4
$48.99
Total $ 146.97 Stars icon
Banner background image

Table of Contents

13 Chapters
Getting Started with OpenCV Chevron down icon Chevron up icon
An Introduction to the Basics of OpenCV Chevron down icon Chevron up icon
Learning Graphical User Interfaces Chevron down icon Chevron up icon
Delving into Histogram and Filters Chevron down icon Chevron up icon
Automated Optical Inspection, Object Segmentation, and Detection Chevron down icon Chevron up icon
Learning Object Classification Chevron down icon Chevron up icon
Detecting Face Parts and Overlaying Masks Chevron down icon Chevron up icon
Video Surveillance, Background Modeling, and Morphological Operations Chevron down icon Chevron up icon
Learning Object Tracking Chevron down icon Chevron up icon
Developing Segmentation Algorithms for Text Recognition Chevron down icon Chevron up icon
Text Recognition with Tesseract Chevron down icon Chevron up icon
Deep Learning with OpenCV Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.5
(2 Ratings)
5 star 0%
4 star 50%
3 star 0%
2 star 0%
1 star 50%
Kohei Yoshida Apr 24, 2019
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I'm almost finishing up this book, and I think I have seen enough to give it a review. I'm new to OpenCV but I'm pretty experienced with CMake, and I built OpenCV directly from its source from its github repo in order to follow this book. So, I can't comment on the quality and accuracy of the installation guide in this book since I skipped that part.The rest of the book's content is quite decent, and gave me a very good overview of what sort of functionality is provided by OpenCV. I've noticed some minor errors in the example codes, but nothing that some debugging can't resolve.I also recommend you follow this book on Linux if you have that option. You need access to a webcam since many of the examples do make use of video feeds from camera.I'm also planning on buying a copy of Mastering OpenCV 4 after I finish this book, to further deepen my knowledge of OpenCV.
Amazon Verified review Amazon
Bad Review Apr 01, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Installation guide is not useful. Either it is not updated or incomplete. Some libraries on the dependencies are no longer there.
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.