Monday 15 March 2021

opencv 14 Morphological Transformations


original image

applied adaptive mean thresholding

after threshold, applied dilation

after threshold, applied corrosion

after threshold, applied corrosion then dilation (opening)

after threshold, applied dilation then corrosion (closing)

morphological gradient is the difference between dilation and corrosion

top hat is the difference between opening and original image
#main.py
import numpy as np
import cv2

cap = cv2.VideoCapture("assets/Santa Barbara.mp4")

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #adaptive threshold (frame, max pixel value, adaptive method, threshold type, neighbour block size, c constant)
    th1 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
    #th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

    kernal = np.ones((5, 5), np.uint8)

    dilation = cv2.dilate(th1, kernal, iterations=1)
    erosion = cv2.erode(th1, kernal, iterations=1)

    #erosion then dilation
    opening = cv2.morphologyEx(th1, cv2.MORPH_OPEN, kernal)

    #dilation then erosion
    closing = cv2.morphologyEx(th1, cv2.MORPH_CLOSE, kernal)

    #morphological gredient, difference between dilation and erosion
    mg = cv2.morphologyEx(th1, cv2.MORPH_GRADIENT, kernal)

    #top hat, difference between image and opening of image
    top_hat = cv2.morphologyEx(th1, cv2.MORPH_TOPHAT, kernal)

    cv2.imshow('frame', frame)
    cv2.imshow('mask', th1)
    cv2.imshow('dilation', dilation)
    cv2.imshow('erosion', erosion)
    cv2.imshow('opening', opening)
    cv2.imshow('closing', closing)
    cv2.imshow('morphological', mg)
    cv2.imshow('top hat', top_hat)

    if cv2.waitKey(1) == ord('q'):
        break

    if cv2.waitKey(1) == ord('p'):
        # wait until any key is pressed
        cv2.waitKey(-1)

cap.release()
cv2.destroyAllWindows()

reference:

adaptive threshold

No comments:

Post a Comment