def remove_blobs(image, min_area=0, max_area=sys.maxsize, threshold=128,
method='8-connected', return_mask=False):
"""Binarize image using threshold, and remove (turn into black)
blobs of connected pixels of white of size bigger or equal than
min_area but smaller or equal than max_area from the original image,
returning it afterward."""
method = method.lower()
if method == '4-connected':
method = cv2.LINE_4
elif method in ('16-connected', 'antialiased'):
method = cv2.LINE_AA
else: # 8-connected
method = cv2.LINE_8
mono_image = binarize_image(image, method='boolean', threshold=threshold)
_, all_contours, _ = cv2.findContours(mono_image, cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
contours = np.array([contour for contour in all_contours
if min_area <= cv2.contourArea(contour) <= max_area])
mask = np.ones(mono_image.shape, np.uint8)
cv2.drawContours(mask, contours, -1, 0, -1, lineType=method)
return image, 255 * mask
评论列表
文章目录