1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import cv2 import numpy as np
img = cv2.imread('./img_24bit.bmp', 0) thresh = cv2.threshold(img, 25, 255, cv2.THRESH_BINARY)[1] cv2.imwrite('./thresh.bmp', thresh)
thresh_copy = thresh.copy()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
max_2_count = [] max_2_thresh = []
index = 0
while thresh_copy.any(): print('第{}个连通分量'.format(index)) thresh_black = np.zeros(img.shape, np.uint8)
X_copy, Y_copy = np.where(thresh_copy > 0) thresh_black[X_copy[0]][Y_copy[0]] = 255
for i in range(2000): dilation_black = cv2.dilate(thresh_black, kernel, iterations=1) thresh_black = cv2.bitwise_and(thresh, dilation_black)
X_black, Y_black = np.where(thresh_black > 0) thresh_copy[X_black, Y_black] = 0
if index > 1: if len(X_black) > min(max_2_count): min_index = max_2_count.index(min(max_2_count)) max_2_count[min_index] = len(X_black) max_2_thresh[min_index] = thresh_black else: max_2_count.append(len(X_black)) max_2_thresh.append(thresh_black) index += 1
thresh_res = cv2.bitwise_or(max_2_thresh[0], max_2_thresh[1]) cv2.imwrite('./max_2_thresh.bmp', thresh_res)
|