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
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
Paperback Mar 2018 306 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Aleksei Spizhevoi Profile Icon Rybnikov
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.3 (3 Ratings)
Paperback Mar 2018 306 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781788474443
Vendor :
Intel
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Mar 23, 2018
Length: 306 pages
Edition : 1st
Language : English
ISBN-13 : 9781788474443
Vendor :
Intel
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 116.97
Computer Vision with OpenCV 3 and Qt5
€41.99
OpenCV 3 Computer Vision with Python Cookbook
€36.99
OpenCV 3.x with Python By Example
€37.99
Total 116.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.