Skip to content

Instantly share code, notes, and snippets.

@cychitivav
Last active September 23, 2022 11:25
Show Gist options
  • Save cychitivav/5d5b0b672d346caf40d6037ec6a216ea to your computer and use it in GitHub Desktop.
Save cychitivav/5d5b0b672d346caf40d6037ec6a216ea to your computer and use it in GitHub Desktop.
A function to segment a binary image
import numpy as np
import matplotlib.pyplot as plt
import cv2
def segment(src=None):
img = cv2.copyMakeBorder(src, 1, 1, 1, 1, cv2.BORDER_REPLICATE)
tags = np.zeros(img.shape)
for i in range(1,img.shape[0]-1):
for j in range(1,img.shape[1]-1):
for k in range(i-1, i+2):
for l in range(j-1, j+2):
if tags[k, l] != 0 and img[k, l] == img[i, j]:
if tags[i, j] != 0:
tags[tags == tags[i, j]] = tags[k, l]
else:
tags[i, j] = tags[k, l]
if k == i+1 and l == j+1 and tags[i, j] == 0:
tags[i, j] = np.max(tags) + 1
return tags[1:-1,1:-1]/np.max(tags)*255
@cychitivav
Copy link
Author

cychitivav commented Sep 19, 2022

Using this code

img = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                [0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                [0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
                [0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                [0, 0, 1, 1, 0, 0, 1, 1, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])*255


plt.subplot(1, 2, 1)
plt.imshow(img, cmap='gray')

plt.subplot(1, 2, 2)
plt.imshow(segment(img), cmap='gray')
plt.show()

We can obtain:

Where each gray level is a region in the right image.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment