Popular Posts

May 22, 2020

morphological transformation - python


Morphological transformations are some simple operations based on the image shape. Morphological transformations are normally performed on binary images.


import cv2
import numpy as np
from matplotlib import pyplot as plt

#img = cv2.imread('smarties.png', cv2.IMREAD_GRAYSCALE)
#_, mask = cv2.threshold(img, 220, 255, cv2.THRESH_BINARY_INV)

img = cv2.imread('j.png', cv2.IMREAD_GRAYSCALE)

#in the image titled 'mask' we found some dots on the balls. so we have to remove the dots .
kernal = np.ones((5,5), np.uint8)

dilation = cv2.dilate(img
, kernal, iterations = 2)
erosion = cv2.erode(img
, kernal, iterations = 1)
opening = cv2.morphologyEx(img
, cv2.MORPH_OPEN, kernal)
closing = cv2.morphologyEx(img
, cv2.MORPH_CLOSE, kernal)
mp = cv2.morphologyEx(img
, cv2.MORPH_GRADIENT, kernal)
th = cv2.morphologyEx(img
, cv2.MORPH_TOPHAT, kernal)

#Gradient: diff dialation and erosion
#Tophat: diff image and opeining image

titles = ['Gray scale image', 'mask', 'dilation', 'erosion', 'opening', 'closing', 'Gradient', 'Tophat']
images = [img
, img, dilation, erosion, opening, closing, mp, th]


for i in range(8):
    plt.subplot(
2, 4, i+1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([])
, plt.yticks([])

plt.show()





No comments:

Post a Comment