Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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.x with Python By Example
OpenCV 3.x with Python By Example

OpenCV 3.x with Python By Example: Make the most of OpenCV and Python to build applications for object recognition and augmented reality , Second Edition

Arrow left icon
Profile Icon Gabriel Garrido Calvo Profile Icon Prateek Joshi
Arrow right icon
€8.99 €28.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
eBook Jan 2018 268 pages 2nd Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Gabriel Garrido Calvo Profile Icon Prateek Joshi
Arrow right icon
€8.99 €28.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5 (2 Ratings)
eBook Jan 2018 268 pages 2nd Edition
eBook
€8.99 €28.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €28.99
Paperback
€37.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
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.x with Python By Example

Chapter 2. Detecting Edges and Applying Image Filters

In this chapter, we are going to see how to apply cool visual effects to images. We will learn how to use fundamental image processing operators, discuss edge detection, and see how we can use image filters to apply various effects to photos.

By the end of this chapter, you will know:

  • What 2D convolution is, and how to use it
  • How to blur an image
  • How to detect edges in an image
  • How to apply motion blur to an image
  • How to sharpen and emboss an image
  • How to erode and dilate an image
  • How to create a vignette filter
  • How to enhance image contrast

2D convolution


Convolution is a fundamental operation in image processing. We basically apply a mathematical operator to each pixel, and change its value in some way. To apply this mathematical operator, we use another matrix called a kernel. The kernel is usually much smaller in size than the input image. For each pixel in the image, we take the kernel and place it on top so that the center of the kernel coincides with the pixel under consideration. We then multiply each value in the kernel matrix with the corresponding values in the image, and then sum it up. This is the new value that will be applied to this position in the output image.

Here, the kernel is called the image filter and the process of applying this kernel to the given image is called image filtering. The output obtained after applying the kernel to the image is called the filtered image. Depending on the values in the kernel, it performs different functions such as blurring, detecting edges, and so on. The following figure...

Blurring


Blurring refers to averaging the pixel values within a neighborhood. This is also called a low pass filter. A low pass filter is a filter that allows low frequencies, and blocks higher frequencies. Now, the next question that comes to our mind is: what does frequency mean in an image? Well, in this context, frequency refers to the rate of change of pixel values. So we can say that the sharp edges would be high-frequency content because the pixel values change rapidly in that region. Going by that logic, plain areas would be low-frequency content. Going by this definition, a low pass filter would try to smooth the edges.

A simple way to build a low pass filter is by uniformly averaging the values in the neighborhood of a pixel. We can choose the size of the kernel depending on how much we want to smooth the image, and it will correspondingly have different effects. If you choose a bigger size, then you will be averaging over a larger area. This tends to increase the smoothing effect...

Motion blur


When we apply the motion blurring effect, it will look like you captured the picture while moving in a particular direction. For example, you can make an image look like it was captured from a moving car.

The input and output images will look like the following ones:

Following is the code to achieve this motion blurring effect:

import cv2 
import numpy as np 
 
img = cv2.imread('images/input.jpg') 
cv2.imshow('Original', img) 
 
size = 15 
 
# generating the kernel 
kernel_motion_blur = np.zeros((size, size)) 
kernel_motion_blur[int((size-1)/2), :] = np.ones(size) 
kernel_motion_blur = kernel_motion_blur / size 
 
# applying the kernel to the input image 
output = cv2.filter2D(img, -1, kernel_motion_blur) 
 
cv2.imshow('Motion Blur', output) 
cv2.waitKey(0)

Under the hood

We are reading the image as usual. We are then constructing a motion blur kernel. A motion blur kernel averages the pixel values in a particular direction. It's like a directional low pass filter. A 3x3 horizontal...

Sharpening


Applying the sharpening filter will sharpen the edges in the image. This filter is very useful when we want to enhance the edges of an image that's not crisp enough. Here are some images to give you an idea of what the image sharpening process looks like:

As you can see in the preceding figure, the level of sharpening depends on the type of kernel we use. We have a lot of freedom to customize the kernel here, and each kernel will give you a different kind of sharpening. To just sharpen an image, as we are doing in the top-right image in the preceding picture, we would use a kernel like this:

If we want to do excessive sharpening, as in the bottom-left image, we would use the following kernel:

But the problem with these two kernels is that the output image looks artificially enhanced. If we want our images to look more natural, we would use an edge enhancement filter. The underlying concept remains the same, but we use an approximate Gaussian kernel to build this filter. It will help...

Embossing


An embossing filter will take an image and convert it to an embossed image. We basically take each pixel, and replace it with a shadow or a highlight. Let's say we are dealing with a relatively plain region in the image. Here, we need to replace it with a plain gray color because there's not much information there. If there is a lot of contrast in a particular region, we will replace it with a white pixel (highlight), or a dark pixel (shadow), depending on the direction in which we are embossing.

This is what it will look like:

Let's take a look at the code and see how to do this:

import cv2 
import numpy as np 
 
img_emboss_input = cv2.imread('images/input.jpg') 
 
# generating the kernels 
kernel_emboss_1 = np.array([[0,-1,-1], 
                            [1,0,-1], 
                            [1,1,0]]) 
kernel_emboss_2 = np.array([[-1,-1,0], 
                            [-1,0,1], 
                            [0,1,1]]) 
kernel_emboss_3 = np.array([[1,0,0], 
                   ...

Edge detection


The process of edge detection involves detecting sharp edges in the image, and producing a binary image as the output. Typically, we draw white lines on a black background to indicate those edges. We can think of edge detection as a high pass filtering operation. A high pass filter allows high-frequency content to pass through and blocks the low-frequency content. As we discussed earlier, edges are high-frequency content. In edge detection, we want to retain these edges and discard everything else. Hence, we should build a kernel that is the equivalent of a high pass filter.

Let's start with a simple edge detection filter known as the Sobel filter. Since edges can occur in both horizontal and vertical directions, the Sobel filter is composed of the following two kernels:

The kernel on the left detects horizontal edges and the kernel on the right detects vertical edges. OpenCV provides a function to directly apply the Sobel filter to a given image. Here is the code to use Sobel...

Erosion and dilation


Erosion and dilation are morphological image processing operations. Morphological image processing basically deals with modifying geometric structures in the image. These operations are primarily defined for binary images, but we can also use them on grayscale images. Erosion basically strips out the outermost layer of pixels in a structure, whereas dilation adds an extra layer of pixels to a structure.

Let's see what these operations look like:

Following is the code to achieve this:

import cv2 
import numpy as np 
 
img = cv2.imread('images/input.jpg', 0) 
 
kernel = np.ones((5,5), np.uint8) 
 
img_erosion = cv2.erode(img, kernel, iterations=1) 
img_dilation = cv2.dilate(img, kernel, iterations=1) 
 
cv2.imshow('Input', img) 
cv2.imshow('Erosion', img_erosion) 
cv2.imshow('Dilation', img_dilation) 
 
cv2.waitKey(0) 

Afterthought

OpenCV provides functions to directly erode and dilate an image. They are called erode and dilate, respectively. The interesting thing to note is...

Creating a vignette filter


Using all the information we have, let's see if we can create a nice vignette filter. The output will look something like the following:

Here is the code to achieve this effect:

import cv2 
import numpy as np 
 
img = cv2.imread('images/input.jpg') 
rows, cols = img.shape[:2] 
 
# generating vignette mask using Gaussian kernels 
kernel_x = cv2.getGaussianKernel(cols,200) 
kernel_y = cv2.getGaussianKernel(rows,200) 
kernel = kernel_y * kernel_x.T 
mask = 255 * kernel / np.linalg.norm(kernel) 
output = np.copy(img) 
 
# applying the mask to each channel in the input image 
for i in range(3): 
    output[:,:,i] = output[:,:,i] * mask 
 
cv2.imshow('Original', img) 
cv2.imshow('Vignette', output) 
cv2.waitKey(0) 

What's happening underneath?

The vignette filter basically focuses the brightness on a particular part of the image and the other parts look faded. In order to achieve this, we need to filter out each channel in the image using a Gaussian kernel. OpenCV provides...

Enhancing the contrast in an image


Whenever we capture images in low-light conditions, the images turn out to be dark. This typically happens when you capture images in the evening, or in a dimly lit room. You must have seen this happen many times! The reason this happens is because the pixel values tend to concentrate near zero when we capture the images under such conditions. When this happens, a lot of details in the image are not clearly visible to the human eye. The human eye likes contrast, and so we need to adjust the contrast to make the image look nice and pleasant. A lot of cameras and photo applications implicitly do this already. We use a process called histogram equalization to achieve this.

To give an example, this is what it looks like before and after contrast enhancement:

As we can see here, the input image on the left is really dark. To rectify this, we need to adjust the pixel values so that they are spread across the entire spectrum of values, that is, between 0-255.

Following...

Summary


In this chapter, we learned how to use image filters to apply cool visual effects to images. We discussed the fundamental image processing operators, and how we can use them to build various things. We learned how to detect edges using various methods. We understood the importance of 2D convolution and how we can use it in different scenarios. We discussed how to smooth, motion-blur, sharpen, emboss, erode, and dilate an image. We learned how to create a vignette filter, and how we can change the region of focus as well. We discussed contrast enhancement and how we can use histogram equalization to achieve it.

In the next chapter, we will discuss how to cartoonize a given image.

 

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn how to apply complex visual effects to images with OpenCV 3.x and Python
  • Extract features from an image and use them to develop advanced applications
  • Build algorithms to help you understand image content and perform visual searches
  • Get to grips with advanced techniques in OpenCV such as machine learning, artificial neural network, 3D reconstruction, and augmented reality

Description

Computer vision is found everywhere in modern technology. OpenCV for Python enables us to run computer vision algorithms in real time. With the advent of powerful machines, we have more processing power to work with. Using this technology, we can seamlessly integrate our computer vision applications into the cloud. Focusing on OpenCV 3.x and Python 3.6, this book will walk you through all the building blocks needed to build amazing computer vision applications with ease. We start off by manipulating images using simple filtering and geometric transformations. We then discuss affine and projective transformations and see how we can use them to apply cool advanced manipulations to your photos like resizing them while keeping the content intact or smoothly removing undesired elements. We will then cover techniques of object tracking, body part recognition, and object recognition using advanced techniques of machine learning such as artificial neural network. 3D reconstruction and augmented reality techniques are also included. The book covers popular OpenCV libraries with the help of examples. This book is a practical tutorial that covers various examples at different levels, teaching you about the different functions of OpenCV and their actual implementation. By the end of this book, you will have acquired the skills to use OpenCV and Python to develop real-world computer vision applications.

Who is this book for?

This book is intended for Python developers who are new to OpenCV and want to develop computer vision applications with OpenCV and Python. This book is also useful for generic software developers who want to deploy computer vision applications on the cloud. It would be helpful to have some familiarity with basic mathematical concepts such as vectors, matrices, and so on.

What you will learn

  • Detect shapes and edges from images and videos
  • How to apply filters on images and videos
  • Use different techniques to manipulate and improve images
  • Extract and manipulate particular parts of images and videos
  • Track objects or colors from videos
  • Recognize specific object or faces from images and videos
  • How to create Augmented Reality applications
  • Apply artificial neural networks and machine learning to improve object recognition

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 17, 2018
Length: 268 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788396769
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 : Jan 17, 2018
Length: 268 pages
Edition : 2nd
Language : English
ISBN-13 : 9781788396769
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
OpenCV 3 Computer Vision with Python Cookbook
€36.99
Machine Learning for OpenCV
€41.99
OpenCV 3.x with Python By Example
€37.99
Total 116.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Applying Geometric Transformations to Images Chevron down icon Chevron up icon
Detecting Edges and Applying Image Filters Chevron down icon Chevron up icon
Cartoonizing an Image Chevron down icon Chevron up icon
Detecting and Tracking Different Body Parts Chevron down icon Chevron up icon
Extracting Features from an Image Chevron down icon Chevron up icon
Seam Carving Chevron down icon Chevron up icon
Detecting Shapes and Segmenting an Image Chevron down icon Chevron up icon
Object Tracking Chevron down icon Chevron up icon
Object Recognition Chevron down icon Chevron up icon
Augmented Reality Chevron down icon Chevron up icon
Machine Learning by an Artificial Neural Network 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.5
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 50%
1 star 0%
Andrew Zappella Jun 09, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book! I highly recommend it! The book helps the reader navigate the complex world of computer vision through OpenCV and Python. It gradually introduces the concepts and tools necessary to do object recognition and object tracking. It lends itself very well as an introductory book for more advanced artificial intelligence computer vision topics.
Amazon Verified review Amazon
Reading Thusly Jul 01, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Good:Good attempt at producing an up to date (openCV3.X) reference for python. There arent man. Pyimagesearch is probably the best.Good coding examples, probably even for a beginner that has been through codeacademy or something like it.Bad:The grammar...I mean what the heck editors? I didnt even know what they were talking about sometimes because it was like they didnt even put the variables they were talking about into the sentence. Makes the book feel amateurish amd harder to take seriously.
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.