def binary_morph(img, thresh=50, min_size=None, mask_only=True):
if min_size is None: # default to 10% of largest image dimension
min_size = float(max(img.shape)) * .1
if len(img.shape) == 3: # flatten if RGB image
img = np.mean(img, 2).astype(np.uint8)
# Apply binary threshold and erode
ret, thresh_im = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)
# Connected component labelling
n, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh_im)
mask = np.zeros_like(labels)
# Loop through areas in order of size
areas = [s[4] for s in stats]
sorted_idx = np.argsort(areas)
for lidx, cc in zip(sorted_idx, [areas[s] for s in sorted_idx][:-1]):
if cc > min_size:
mask[labels == lidx] = 1
if mask_only:
return mask * 255
return np.dstack([img * mask] * 3).astype(np.uint8)
评论列表
文章目录