OpenCV — Morphological Operations

How To Erode, Dilate, Edge Detect w/ Gradient — #PyVisionSeries — Episode #03

J3
Jungletronics
4 min readOct 7, 2022

--

Do you need help get rid of noise in certain images or maybe help with edge detection?

So here are morphological operators that we’re going to cover in this lecture.

INDEX:
00 step — Utility Functions
01 step — Loading & Display The Image to Work With
02 step — Resizing Images
03 step — Morphological Operations
A - Erosion

B - Dilation

C - Image Denoising
Remove Background Noise From WHITE_NOISE - OPENING

D - Image Denoising
Remove Foreground Noise From BLACK_NOISE - CLOSING

E - Gradient - EDGE DETECTION

00 step — Utility Functions

import cv2
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Here is the load image function:

def load_img():
blank_img = np.zeros(shape=(600,600), dtype=np.int16)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(blank_img, text='ABCDE', org=(40,350), fontFace=font,
fontScale=5, color=(255,255,255), thickness=25)
return blank_img

And know, display:

def display_img(img):
fig = plt.figure(figsize=(12,10))
ax = fig.add_subplot(111)
ax.imshow(img, cmap='gray')

01 step — Loading & Display The Image to Work With

img = load_img()
display_img(img)
Note that the first two letters are linked
img.shape[5]:(600, 600)

02 step — Resizing Images

img = cv2.resize(img, (255,255))
img.shape
(255, 255)

Coping images:

img_copy = img.copy()
display_img(img_copy)
type(img_copy)
numpy.ndarray

03 step — Morphological Operations

kernel = np.ones((5,5), dtype=np.uint8)

A — Erosion

result = cv2.erode(img_copy, kernel, iterations=2)display_img(result)
To erode is to chip away at the edges of the images

B — Dilation

result = cv2.dilate(img, kernel, iterations=2)display_img(result)
To dilate is to add borders to the images

C — Image Denoising

Remove Background Noise From WHITE_NOISE — OPENING

white_noise = np.random.randint(low=0, high=2, size=(600,600))

Background noise, creating some:

white_noise = white_noise * 255display_img(white_noise)
We are creating our own image with white noise; remember when the TV channel is out of tune?
white_noise.shape(600, 600)

Type?

type(white_noise)numpy.ndarray

Loading the original image:

img = load_img()

Adding the images:

# https://stackoverflow.com/questions/61583991/opencv-python-error-unsupported-data-type-4-in-function-cvopt-avx2getmonoise_img = white_noise + imgnoise_img = noise_img.astype('uint8')display_img(noise_img)
How to get rid of this kind of noise (around the image of interest)?

Opening technique, is the answer!

opening = cv2.morphologyEx(noise_img, cv2.MORPH_OPEN, kernel)display_img(opening)
The image is not perfect, but we get rid of the noise around, right?

D — Image Denoising

Remove Foreground Noise From BLACK_NOISE — CLOSE

img = load_img()

Creating a black noise (to foregraund):

black_noise = np.random.randint(low=0, high=2, size=(600,600))

Multiply by -255, so that 255–255 = 0 (wite region) and 0–255=-255 (black region):

black_noise = black_noise * -255black_noise.min()-255

Adding images:

noise_img = black_noise + imgnoise_img = noise_img.astype('uint8')

Some math :/

noise_img[noise_img==-255] = 0black_noise.min()-255display_img(noise_img)
#So previously we had a bunch of noise in the BACKGROUND. Now we have a bunch of noise soly in the FOREGROUND AND CLOSING is a good way of getting rid of this :)
closing = cv2.morphologyEx(noise_img, cv2.MORPH_CLOSE, kernel)

Let´s check it out:

display_img(closing)
Again, we still have some noise ( a link between the letters b and c) but the internal noises are gone :)

E — Gradient — EDGE DETECTION

img = load_img()

Applying Gradient:

gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)display_img(gradient)
It’s a secondary technique of detecting edges, that’s it, we’re done…
print("That´s it! Thank you once again!\nI hope will be helpful.")That´s it! Thank you once again!
I hope will be helpful.

👉Jupiter notebook link :)

👉Github (EX_03)

Credits & References:

Jose Portilla — Python for Computer Vision with OpenCV and Deep Learning — Learn the latest techniques in computer vision with Python, OpenCV, and Deep Learning!

Posts Related:

00 Episode#Hi Python Computer Vision — PIL! — An Intro To Python Imaging Library #PyVisionSeries

01 Episode# Jupyter-lab — Python — OpenCV — Image Processing Exercises #PyVisionSeries

02 Episode# OpenCV — Image Basics — Create Image From Scratch #PyVisionSeries

03 Episode# OpenCV — Morphological Operations — How To Erode, Dilate, Edge Detect w/ Gradient #PyVisionSeries

04 Episode# OpenCV — Histogram Equalization — HOW TO Equalize Histograms Of Images — #PyVisionSeries

05 Episode# OpenCV — OpenCV — Resize an Image — How To Resize Without Distortion

07 Episode# YOLO — Object Detection — The state of the art in object detection Framework!

08 Episode# OpenCV — HaashCascate — Object Detection — Viola–Jones object detection framework — #PyVisionSeries

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!