Search code examples
pythonopencvpython-3.6opencv3.3

openCV3: Not getting the expected output on morphologically transforming an image in opencv


I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.

# Top Hat: difference between input image and opening
kernel = np.ones((5,5),np.float32)/25 
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat')
plt.xticks([]), plt.yticks([])
plt.show()

What is expected

What is expected

What I am getting

What I am getting

EDIT: Added the kernel.


Solution

  • kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ksize=(9,9))
    tophat = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, kernel)
    

    result

    Edit:

    For details please read the following:

    https://docs.opencv.org/3.3.1/d9/d61/tutorial_py_morphological_ops.html

    https://docs.opencv.org/3.3.1/d4/d86/group__imgproc__filter.html#gac342a1bb6eabf6f55c803b09268e36dc

    Iterations vs. Kernel Size in Morphological Operations (OpenCV)