Last active
September 23, 2022 11:25
-
-
Save cychitivav/5d5b0b672d346caf40d6037ec6a216ea to your computer and use it in GitHub Desktop.
A function to segment a binary image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using this code
We can obtain:
Where each gray level is a region in the right image.