I have to connect the unfinished edges of the contours in the red color bounding box.
I used distance transform, watershed, and morphology, but still, edges are not connecting.
import cv2
import glob
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
og_path_test = ''
predicted_path = ''
IMG_WIDTH = 512
IMG_HEIGHT = 512
IMG_CHANNELS = 3
test = glob.glob(og_path_test + '*')
for image in test:
name = image.split('/')[-1]
name_new = name[:-4] + '.jpg'
im = Image.open(image)
im = im.resize((IMG_WIDTH, IMG_HEIGHT))
im = np.array(im, dtype=np.float32)
x_batch = np.array([im], np.float32)
prediction = model.predict(x_batch)
mask = np.zeros_like(im[:, :, 0])
for i in range(len(prediction)):
mask += np.reshape(prediction[i], (IMG_WIDTH, IMG_HEIGHT))
ret, mask = cv2.threshold(mask, np.mean(mask) + 1.2 * np.std(mask), 255, cv2.THRESH_BINARY)
# Distance transform and watershed algorithm
dist_transform = cv2.distanceTransform(mask.astype(np.uint8), cv2.DIST_L2, 5)
_, local_maxima = cv2.threshold(dist_transform, 0.5 * dist_transform.max(), 255, cv2.THRESH_BINARY)
_, markers = cv2.connectedComponents(local_maxima.astype(np.uint8))
markers = markers + 1
watershed_img = cv2.cvtColor(im.astype(np.uint8), cv2.COLOR_RGB2BGR)
cv2.watershed(watershed_img, markers)
mask[markers == -1] = 255
path = predicted_path
plt.imsave(os.path.join(path, name_new), np.squeeze(mask), vmin=0, vmax=255)