OpenCV watershed result not expected

196 Views Asked by At

I am testing the watershed OpenCV 3.0 implementation with some samples and I get strange results, or at least what I don't expect.

I'm applying the following:

Read the input image

import numpy as np
import cv2
from matplotlib import pyplot as plt
import numpy

#Reading original image
img = cv2.imread('c:\\tmp\\image.png')
img = 255-img

cv2.imshow('Input',img)
cv2.waitKey(0)
cv2.destroyAllWindows() 

Input image

Apply an Otsu binarization to discriminate foreground vs background

#Binarizing by applying threshold 
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

opening = ((opening - opening.min()) / (opening.max() - opening.min()) * 255).astype(numpy.uint8)

cv2.imshow('Threshold', opening)
cv2.waitKey(0)
cv2.destroyAllWindows()

Get the connected points to be applied as markers

# Marker labelling
ret, markers = cv2.connectedComponents(opening)

Run watershed

# Apply watershed
markers = cv2.watershed(img,markers)

#Show result
img[markers == -1] = [255,0,0]
cv2.imshow('Watershed', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result The result (blue line) is a bit shifted from what I would expect (red line)

0

There are 0 best solutions below