EDIT: In the initial question the color map was reversed which caused some confusion, I changed the images and code to match so standard behavior.
Morphological opening and closing are idempotent operations (see Univ. Auckland):
Opening is an idempotent operation: once an image has been opened, subsequent openings with the same structuring element have no further effect on that image:
(f ∘ s) ∘ s = f ∘ s.
I have the following image:
When trying to remove the skinny rectangles on the top right using OpenCV, I noticed that when I apply Opening iteratively with the same kernel, I get the desired result. To my understanding of how Opening/Closing works this should not be the case. Did I misunderstand anything or is there something wrong with the implementation in OpenCV?
Here is my example code and the results:
import cv2 as cv
import numpy as np
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rc('image', cmap='gray')
# load image
img = cv.imread("image.jpg", 0)
# apply binary thresholding to circumvent jpg compression
img = (img > 128).astype(np.uint8)
# adding a border around the image solves the issue
# img = cv.copyMakeBorder(img, 1, 1, 1, 1, cv.BORDER_CONSTANT)
kernel = cv.getStructuringElement(cv.MORPH_RECT,(20,5))
A = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
B = cv.morphologyEx(A, cv.MORPH_OPEN, kernel)
C = cv.morphologyEx(B, cv.MORPH_OPEN, kernel)
f, ax = plt.subplots(1,3)
ax[0].imshow(A)
ax[0].set_title("A")
ax[1].imshow(B)
ax[1].set_title("B")
ax[2].imshow(C)
ax[2].set_title("C")
plt.show()
Here the result, notice the removed rectangles on the right border after each iteration:

