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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
OpenCV 3 Computer Vision with Python Cookbook
OpenCV 3 Computer Vision with Python Cookbook

OpenCV 3 Computer Vision with Python Cookbook: Leverage the power of OpenCV 3 and Python to build computer vision applications

Arrow left icon
Profile Icon Aleksei Spizhevoi Profile Icon Rybnikov
Arrow right icon
$27.98 $39.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
eBook Mar 2018 306 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Aleksei Spizhevoi Profile Icon Rybnikov
Arrow right icon
$27.98 $39.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
eBook Mar 2018 306 pages 1st Edition
eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $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

OpenCV 3 Computer Vision with Python Cookbook

Matrices, Colors, and Filters

In this chapter, we will cover the following recipes:

  • Manipulating matrices-creating, filling, accessing elements, and ROIs
  • Converting between different data types and scaling values
  • Non-image data persistence using NumPy
  • Manipulating image channels
  • Converting images from one color space to another
  • Gamma correction and per-element math
  • Mean/variance image normalization
  • Computing image histograms
  • Equalizing image histograms
  • Removing noise using Gaussian, median, and bilateral filters
  • Computing gradient images using Sobel filters
  • Creating and applying your own filter
  • Processing images with real-valued Gabor filters
  • Going from the spatial to the frequency domain (and back) using discrete Fourier transform
  • Manipulating image frequencies for image filtration
  • Processing images with different thresholds
  • Morphological operators
  • Binary images-image masks...

Introduction

In this chapter, we will see how to work with matrices. We will learn what we can do with a matrix on a pixel level and what operations and image-processing procedures we can apply to the whole matrix. You will know how to get access to any pixel, how to change data types and color spaces of matrices, how to apply built-in OpenCV filters, and how to create and use your own linear filter.

Manipulating matrices-creating, filling, accessing elements, and ROIs

This recipe covers the creation and initialization of matrices, access to its elements, pixels, and also how we can work with part of a matrix.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

To get the result, it's necessary to go through a few steps:

  1. Import all necessary modules:
import cv2, numpy as np
  1. Create a matrix of a certain shape and fill it with 255 as a value, which should display the following:
image = np.full((480, 640, 3), 255, np.uint8...

Converting between different data types and scaling values

This recipe tells you how to change the data type of matrix elements from uint8 to float32 and perform arithmetic operations without worrying about clamping values (and then convert everything back to uint8).

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

The following steps are required for this recipe:

  1. Import all necessary modules, open an image, print its shape and data type, and display it on the screen:
import cv2, numpy as np
image = cv2.imread('../data...

Non-image data persistence using NumPy

Previously, we've saved and loaded only images with OpenCV's cv2.imwrite and cv2.imread functions, respectively. But it's possible to save any matrix (not only with image content) of any type and shape with NumPy's data persistence. In this recipe, we will review how to do it.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

Perform the following steps:

  1. Import all necessary modules:
import cv2, numpy as np
  1. Create a matrix with random values initialization and print...

Manipulating image channels

This recipe is about dealing with matrix channels. Getting access to individual channels, swapping them, and performing algebraic operations are all covered here.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

Perform the following steps:

  1. Import all necessary modules, open the image, and output its shape:
import cv2, numpy as np
image = cv2.imread('../data/Lena.png').astype(np.float32) / 255
print('Shape:', image.shape)
  1. Swap the red and blue channels and display the result:
...

Converting images from one color space to another

This recipe tells you about color space conversion. By default, full color images in OpenCV are presented in RGB color space. But for some cases it's necessary to move to other color representations; for example, to have a separate channel for intensity. Here we consider ways to change the color space of an image.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

Use following steps:

  1. Import all necessary modules:
import cv2
import numpy as np
  1. Load an image and print its...

Gamma correction and per-element math

Gamma correction is used to skew pixels, value distribution in a non-linear manner. With gamma correction, it's possible to adjust the luminescence of the image to make it easier to see. In this recipe, you will learn how to apply gamma correction to images.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

The steps for this recipe are as follows:

  1. Load the image as grayscale and convert every pixel value to the np.float32 data type in the [0, 1] range:
import cv2
import numpy as np

image...

Mean/variance image normalization

Sometimes it's necessary to set certain values to the statistical moments of pixel values. When we set 0 for mean value of values and 1 for variance, the operation is called normalization. This can be useful in computer vision algorithms for dealing with values with a certain range and with certain statistics. Here we're going to check out image normalization.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

Perform the following steps:

  1. Import all necessary modules:
import cv2
import...

Computing image histograms

Histograms show the levels distribution in a set of values; for example, in an image. In this recipe, we understand how to compute histograms.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

How to do it...

Follow these steps:

  1. Import all necessary modules:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Load an image and display it:
grey = cv2.imread('../data/Lena.png', 0)
cv2.imshow('original grey', grey)
cv2.waitKey()
cv2.destroyAllWindows()
  1. Compute a histogram function:
hist,...

Equalizing image histograms

Image histograms are used to reflect intensity distribution. Properties of histograms depend on image properties. For example, low-contrast images have histograms where bins are clustered near a value: most of the pixels have their values within a narrow range. Low-contrast images are harder to work with because small details are poorly expressed. There is a technique that is able to address this issue. It's called histogram equalization. This recipe covers usage of the approach in OpenCV. We study how to perform histogram equalization for both grayscale and full color images.

Getting ready

You need to have OpenCV 3.x installed with Python API support.

...

Removing noise using Gaussian, median, and bilateral filters

All real images are noisy. Noise not only spoils the appearance of the image but also it makes harder for your algorithms to handle them as input. In this recipe, we consider how to get rid of noise or dramatically decrease it.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Load an image, convert it to floating-point, and scale it down to the [0...

Computing gradients using Sobel operator

In this recipe, you will learn how to compute the approximation of an image's gradient using Sobel filters.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the image as grayscale:
image = cv2.imread('../data/Lena.png', 0)
  1. Compute the gradient approximations using the Sobel operator:
dx = cv2.Sobel(image, cv2.CV_32F, 1, 0)
dy = cv2.Sobel(image, cv2...

Creating and applying your own filter

In this recipe, you will learn how to create your own linear filter and apply it to images.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import math
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the test image:
image = cv2.imread('../data/Lena.png')
  1. Create an 11x11 sharpening kernel:
KSIZE = 11
ALPHA = 2

kernel = cv2.getGaussianKernel(KSIZE, 0)
kernel = -ALPHA * kernel @ kernel.T
kernel[KSIZE//2, KSIZE...

Processing images with real-valued Gabor filters

In this recipe, you will learn how to construct a Gabor filter kernel (useful for detecting edges in images) and apply it to an image.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import math
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the test image as grayscale and convert it to np.float32:
image = cv2.imread('../data/Lena.png', 0).astype(np.float32) / 255
  1. Construct the real-valued...

Going from the spatial domain to the frequency domain (and back) using the discrete Fourier transform

In this recipe, you will learn how to convert a grayscale image from spatial representation to frequency representation, and back again, using the discrete Fourier transform.

Getting ready

Install the OpenCV 3.x Python package and the matplotlib package.

How to do it...

The following steps must be performed:

  1. Import the required packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the image as grayscale and convert it to np.float32 datatype:
image...

Manipulating image frequencies for image filtration

In this recipe, you will learn how to manipulate images in the frequency domain.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the image as grayscale and convert it to the np.float32 datatype:
image = cv2.imread('../data/Lena.png', 0).astype(np.float32) / 255
  1. Convert the image from the spatial domain to the frequency domain using the discrete...

Processing images with different thresholds

In this recipe, you will learn how to convert a grayscale image into a binary image using different thresholding approaches.

Getting ready

Install the OpenCV 3.x Python API package and the matplotlib package.

How to do it...

Perform the following steps:

  1. Import the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the test image:
image = cv2.imread('../data/Lena.png', 0)
  1. Apply a simple binary threshold:
thr, mask = cv2.threshold(image, 200, 1, cv2.THRESH_BINARY)
print('Threshold used...

Morphological operators

In this recipe, you will learn how to apply basic morphological operations to binary images.

Getting ready

Install the OpenCV Python API package and the matplotlib package.

How to do it...

Follow these steps:

  1. Import the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Read the test image and build a binary image using Otsu's method:
image = cv2.imread('../data/Lena.png', 0)
_, binary = cv2.threshold(image, -1, 1, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  1. Apply erosion and dilatation 10 times using a 3x3 rectangle...

Image masks and binary operations

In this recipe, you will learn how to work with binary images, including how to apply binary element-wise operations.

Getting ready

You need to have OpenCV 3.x installed with Python API support and, additionally, the matplotlib package.

How to do it...

The steps for this recipe are as follows:

  1. Import all the packages:
import cv2
import numpy as np
import matplotlib.pyplot as plt
  1. Create a binary image with a circle mask:
circle_image = np.zeros((500, 500), np.uint8)
cv2.circle(circle_image, (250, 250), 100, 255, -1)
  1. Create a binary image...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • ? Build computer vision applications with OpenCV functionality via Python API
  • ? Get to grips with image processing, multiple view geometry, and machine learning
  • ? Learn to use deep learning models for image classification, object detection, and face recognition

Description

OpenCV 3 is a native cross-platform library for computer vision, machine learning, and image processing. OpenCV's convenient high-level APIs hide very powerful internals designed for computational efficiency that can take advantage of multicore and GPU processing. This book will help you tackle increasingly challenging computer vision problems by providing a number of recipes that you can use to improve your applications. In this book, you will learn how to process an image by manipulating pixels and analyze an image using histograms. Then, we'll show you how to apply image filters to enhance image content and exploit the image geometry in order to relay different views of a pictured scene. We’ll explore techniques to achieve camera calibration and perform a multiple-view analysis. Later, you’ll work on reconstructing a 3D scene from images, converting low-level pixel information to high-level concepts for applications such as object detection and recognition. You’ll also discover how to process video from files or cameras and how to detect and track moving objects. Finally, you'll get acquainted with recent approaches in deep learning and neural networks. By the end of the book, you’ll be able to apply your skills in OpenCV to create computer vision applications in various domains.

Who is this book for?

This book is for developers who have a basic knowledge of Python. If you are aware of the basics of OpenCV and are ready to build computer vision systems that are smarter, faster, more complex, and more practical than the competition, then this book is for you.

What you will learn

  • ? Get familiar with low-level image processing methods
  • ? See the common linear algebra tools needed in computer vision
  • ? Work with different camera models and epipolar geometry
  • ? Find out how to detect interesting points in images and compare them
  • ? Binarize images and mask out regions of interest
  • ? Detect objects and track them in videos

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 23, 2018
Length: 306 pages
Edition : 1st
Language : English
ISBN-13 : 9781788478755
Vendor :
Intel
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 : Mar 23, 2018
Length: 306 pages
Edition : 1st
Language : English
ISBN-13 : 9781788478755
Vendor :
Intel
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 $ 152.97
Computer Vision with OpenCV 3 and Qt5
$54.99
OpenCV 3 Computer Vision with Python Cookbook
$48.99
OpenCV 3.x with Python By Example
$48.99
Total $ 152.97 Stars icon

Table of Contents

10 Chapters
I/O and GUI Chevron down icon Chevron up icon
Matrices, Colors, and Filters Chevron down icon Chevron up icon
Contours and Segmentation Chevron down icon Chevron up icon
Object Detection and Machine Learning Chevron down icon Chevron up icon
Deep Learning Chevron down icon Chevron up icon
Linear Algebra Chevron down icon Chevron up icon
Detectors and Descriptors Chevron down icon Chevron up icon
Image and Video Processing Chevron down icon Chevron up icon
Multiple View Geometry 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 Full star icon Half star icon Empty star icon 3.3
(3 Ratings)
5 star 33.3%
4 star 0%
3 star 33.3%
2 star 33.3%
1 star 0%
Lukáš Jun 14, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book with a lot of examples.
Subscriber review Packt
Uwe Jun 14, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Das Buch ist OK (also 5 Sterne): ein Buch mit einfachen Programmbeispielen, ohne die Algorithmen zu erläutern, eben ein "Kochbuch".Vielleicht liest der Verlag mit:Als Cookbook hat es der Autor leicht. Er schaut in die Opencv Dokumentation und überträgt die Beispiele. Die Theorie der Codes braucht er nicht herauszuarbieten.Den Preis finde ich unangemessen:250 Seiten, s/w Druck, auf fast jeder Seite der Hinweis, dass Opencv und Python installiiert sein soll ("Getting ready"). Alleine dies bläht das Volumen um fast 20% auf.Auch der Verweis auf die elektronische Version hilft wenig, wenn man in einem gedruckten Buch blättern möchte.Drei Sterne, um diesen Ärger hervorzuheben.
Amazon Verified review Amazon
EnryQuy Aug 13, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Il libro è interessante perchè riassume moltissime funzioni di OpenCV, e consente di farsi una idea abbastanza ampia sulle capacità, ma non ci sono assolutamente spiegazioni precise su come funzioni realmente OpenCV, e quindi come sfruttarlo, modificando le ricette proposte, per le proprie necessità. Per ogni spiegazione si rimanda al sito ufficiale di openCV, o a manuali più completi. Utile se si vuole fare copia incolla di codice, Totalmente inutile se si vuole approfondire le funzioni di OpenCV
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.