title: OpenCV: How to correctly apply morphologyEx operation?
body: <p>I am having a problem regarding the kernel size for <code>morphologyEx</code>. I have some <em>captcha</em> images and I want to do the same operation on them and get the same final result.</p>
  
  <p>code :</p>
  
  <pre><code>image = cv2.imread("Image.jpg")
  gray = cv2.cvtColor(image , cv2.COLOR_BGR2GRAY)
  
  
  ret, thresh1 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  
  k1 = np.ones((3,3))
  k2 = np.ones((5,5))
  bottom_image = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, k1)
  bottom_image =  255-bottom_image
  bottom_image = remove_boxes(bottom_image , True)
  
  
  ret,thresh2 = cv2.threshold(bottom_image,127,255,cv2.THRESH_BINARY_INV)
  opening = cv2.morphologyEx(thresh2, cv2.MORPH_OPEN, k1)
  
  
  #closing =  cv2.morphologyEx(opening, cv2.MORPH_CLOSE, k)
  # cv2.imshow('opening', opening)
  
  dilate = cv2.morphologyEx(opening, cv2.MORPH_DILATE, k2)
  dilate = cv2.bitwise_not(dilate)
  # cv2.imshow('dilation', dilate)
  
  
  bottom_image = cv2.morphologyEx(bottom_image, cv2.MORPH_CLOSE, k1)
  </code></pre>
  
  <p>The perfect result would be</p>
  
  <p>Input:<br>
  <a href="https://i.stack.imgur.com/vYcGz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vYcGz.png" alt="enter image description here"></a></p>
  
  <p>Output:<br>
  <a href="https://i.stack.imgur.com/BFSSK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BFSSK.png" alt="enter image description here"></a></p>
  
  <p>But the problem appears when I apply it to other images with the same structure output is distorted.</p>
  
  <h3>Example 1 :</h3>
  
  <p>Input:<br>
  <a href="https://i.stack.imgur.com/dwmAu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dwmAu.png" alt="enter image description here"></a></p>
  
  <p>Output:<br>
  <a href="https://i.stack.imgur.com/KaA4K.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KaA4K.png" alt="enter image description here"></a></p>
  
  <h3>Example 2 :</h3>
  
  <p>Input:<br>
  <a href="https://i.stack.imgur.com/wla3v.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wla3v.png" alt="enter image description here"></a></p>
  
  <p>Output:<br>
  <a href="https://i.stack.imgur.com/76ET2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/76ET2.png" alt="enter image description here"></a></p>
  
  <h3>Example 3:</h3>
  
  <p>Input:<br>
  <a href="https://i.stack.imgur.com/xDheN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xDheN.png" alt="enter image description here"></a></p>
  
  <p>Output:<br>
  <a href="https://i.stack.imgur.com/GqEbf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GqEbf.png" alt="enter image description here"></a></p>