| 3 | |
| 4 | |
| 5 | def connected_components_demo(src): |
| 6 | src = cv.GaussianBlur(src, (3, 3), 0) |
| 7 | gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY) |
| 8 | ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) |
| 9 | cv.imshow("binary", binary) |
| 10 | cv.imwrite('binary.png', binary) |
| 11 | |
| 12 | output = cv.connectedComponents(binary, connectivity=8, ltype=cv.CV_32S) |
| 13 | num_labels = output[0] |
| 14 | print(num_labels) # output: 5 |
| 15 | labels = output[1] |
| 16 | |
| 17 | # 构造颜色 |
| 18 | colors = [] |
| 19 | for i in range(num_labels): |
| 20 | b = np.random.randint(0, 256) |
| 21 | g = np.random.randint(0, 256) |
| 22 | r = np.random.randint(0, 256) |
| 23 | colors.append((b, g, r)) |
| 24 | colors[0] = (0, 0, 0) |
| 25 | |
| 26 | # 画出连通图 |
| 27 | h, w = gray.shape |
| 28 | image = np.zeros((h, w, 3), dtype=np.uint8) |
| 29 | for row in range(h): |
| 30 | for col in range(w): |
| 31 | image[row, col] = colors[labels[row, col]] |
| 32 | |
| 33 | cv.imshow("colored labels", image) |
| 34 | cv.imwrite("labels.png", image) |
| 35 | print("total componets : ", num_labels - 1) |
| 36 | |
| 37 | |
| 38 | |