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.

2 answers

  • answered 2017-11-15 01:37 yapws87

    Do you need to normalize your kernel? Try removing the division by 25 from the kernel.

    Morphological kernels are supposed to be consist of "ones" and "zeros". Therefore, no normalization is required. It will work fine with type CV_8UC1 as well.

  • answered 2017-11-15 01:43 zindarod

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

    result