Book Image

OpenCV with Python By Example

By : Prateek Joshi
Book Image

OpenCV with Python By Example

By: Prateek Joshi

Overview of this book

Table of Contents (19 chapters)
OpenCV with Python By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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, where as dilation adds an extra layer of pixels on 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('input.png', 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 the third argument...