How to remove open curves in a binary image?

After some processing, I have this binary image:

enter image description here

I want to remove open curves, i.e. upper left and lower right curves. Can you suggest me an algorithm for this? Thank.

+5
source share
3 answers

As @John Zwinck mentions that this can be done using floodfill, but I believe your problem is that you want to go back to the original black background and keep the contours of the closed shapes. Although you can use contoursto understand this, here is a fairly simple approach that will remove all open and open line segments from the image, even if they are attached to a closed form. But keep the edges closed by curves.

  • - , .
  • ,
  • - , .

:

enter image description here

python, ++ cv2.

import cv2
import numpy as np

im = cv2.imread('I7qZP.png',cv2.CV_LOAD_IMAGE_GRAYSCALE)
im2 = im.copy()
mask = np.zeros((np.array(im.shape)+2), np.uint8)
cv2.floodFill(im, mask, (0,0), (255))
im = cv2.erode(im, np.ones((3,3)))
im = cv2.bitwise_not(im)
im = cv2.bitwise_and(im,im2)
cv2.imshow('show', im)
cv2.imwrite('fin.png',im)
cv2.waitKey()
+6

, . 300x300 , , , . opencv.

, - . , .

The criteria that I used to determine the pixel as the end of the line was to note the number of black-and-white changes around the cycle of that pixel. If there are less than 4 changes, this is the end of the line. This will not work if the lines are thicker than 1 px. I could probably come up with something better. It seemed that he was working with the provided picture.

do {
   res = 0;
   for (i = 1; i < 299; i++) {
      for (j = 1; j < 299; j++) {
         if (image[i][j] != 0) {
            count = 0;

            if (image[i-1][j-1] != image[i-1][j+0]) count++;
            if (image[i-1][j+0] != image[i-1][j+1]) count++;
            if (image[i-1][j+1] != image[i+0][j+1]) count++;
            if (image[i+0][j+1] != image[i+1][j+1]) count++;
            if (image[i+1][j+1] != image[i+1][j+0]) count++;
            if (image[i+1][j+0] != image[i+1][j-1]) count++;
            if (image[i+1][j-1] != image[i+0][j-1]) count++;
            if (image[i+0][j-1] != image[i-1][j-1]) count++;

            if (count < 4) {
               image[i][j] = 0;
               res = 1;
            }
         }
      }
   }
} while (res);
0
source

All Articles