Spaces:
Runtime error
Runtime error
Commit
•
235d6cc
1
Parent(s):
e108866
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,39 @@
|
|
1 |
-
import
|
|
|
2 |
|
3 |
-
def
|
4 |
-
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
|
4 |
+
def watershed_segmentation(input_image):
|
5 |
+
# Convert the image to grayscale
|
6 |
+
gray = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
|
7 |
+
|
8 |
+
# Apply adaptive thresholding
|
9 |
+
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2)
|
10 |
|
11 |
+
# Morphological operations to remove small noise - use morphologyEx
|
12 |
+
kernel = np.ones((3, 3), np.uint8)
|
13 |
+
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
|
14 |
+
|
15 |
+
# Identify sure background area
|
16 |
+
sure_bg = cv2.dilate(opening, kernel, iterations=3)
|
17 |
+
|
18 |
+
# Find sure foreground area using distance transform
|
19 |
+
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
|
20 |
+
ret, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
|
21 |
+
|
22 |
+
# Find unknown region
|
23 |
+
sure_fg = np.uint8(sure_fg)
|
24 |
+
unknown = cv2.subtract(sure_bg, sure_fg)
|
25 |
+
|
26 |
+
# Marker labeling
|
27 |
+
ret, markers = cv2.connectedComponents(sure_fg)
|
28 |
+
|
29 |
+
# Add one to all labels so that sure background is not 0, but 1
|
30 |
+
markers = markers + 1
|
31 |
+
|
32 |
+
# Mark the unknown region with zero
|
33 |
+
markers[unknown == 255] = 0
|
34 |
+
|
35 |
+
# Apply watershed
|
36 |
+
cv2.watershed(input_image, markers)
|
37 |
+
input_image[markers == -1] = [0, 0, 255] # boundary region
|
38 |
+
|
39 |
+
return input_image
|