As this is the output from the watershed and I want to mark the labels like 1,2,3 etc on the regions identified. I have tried to use cv2.puttext as well by using cv2.boudingrect but the labels are not coming in the center of the region identified
JavaScript
x
22
22
1
for i in range(2, ret3+1):
2
a=0
3
b=0
4
mask = np.where(markers==i, np.uint8(255), np.uint8(0))
5
x,y,w,h = cv2.boundingRect(mask)
6
area = cv2.countNonZero(mask[y:y+h,x:x+w])
7
print ("Label %d at (%d, %d) size (%d x %d) area %d pixels" % (i,x,y,w,h,area))
8
9
# Visualize
10
color = np.uint8(np.random.random_integers(0, 0, 3)).tolist()
11
output[mask!=0] = color
12
13
14
15
cv2.putText(img2,'%d'%i,(int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 3.9, color, 15, cv2.LINE_AA)
16
17
18
19
plt.imshow(img2, cmap='jet')
20
plt.show()
21
22
Through the above code the generated labels are as follows
What i want is that to mark the labels 3,4,5 etc in the center of the objects identified by watershed.
Advertisement
Answer
You can find the center of each region like this:
JavaScript
1
8
1
markers = cv2.watershed(img, markers)
2
3
labels = np.unique(markers)
4
for label in labels:
5
y, x = np.nonzero(markers == label)
6
cx = int(np.mean(x))
7
cy = int(np.mean(y))
8
The result:
Complete example:
JavaScript
1
42
42
1
import cv2
2
import numpy as np
3
4
img = cv2.imread("water_coins.jpg")
5
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
6
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
7
8
# noise removal
9
kernel = np.ones((3, 3), np.uint8)
10
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
11
# sure background area
12
sure_bg = cv2.dilate(opening, kernel, iterations=3)
13
# Finding sure foreground area
14
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
15
ret, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
16
# Finding unknown region
17
sure_fg = np.uint8(sure_fg)
18
unknown = cv2.subtract(sure_bg, sure_fg)
19
20
21
# Marker labelling
22
ret, markers = cv2.connectedComponents(sure_fg)
23
# Add one to all labels so that sure background is not 0, but 1
24
markers = markers + 1
25
# Now, mark the region of unknown with zero
26
markers[unknown == 255] = 0
27
28
markers = cv2.watershed(img, markers)
29
30
labels = np.unique(markers)
31
for label in labels:
32
y, x = np.nonzero(markers == label)
33
cx = int(np.mean(x))
34
cy = int(np.mean(y))
35
color = (255, 255, 255)
36
img[markers == label] = np.random.randint(0, 255, size=3)
37
cv2.circle(img, (cx, cy), 2, color=color, thickness=-1)
38
cv2.putText(img, f"{label}", (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, 0.35, color, 1, cv2.LINE_AA)
39
40
41
cv2.imwrite("out.jpg", img)
42