e2 = cv2.erode(1 - im, k2, borderType=cv2.BORDER_CONSTANT)
return e1 & e2
if __name__ == '__main__':
    im = cv2.imread('blobs.png', cv2.CV_LOAD_IMAGE_GRAYSCALE)
_, im_binary = cv2.threshold(im, 50, 255, cv2.THRESH_BINARY)
kernel = np.array([[-1, -1, 1], [-1, 1, 1], [-1, -1, 1]])
im_mask = np.zeros(im_binary.shape, np.uint8)
im_mask |= hitmiss(im_binary, kernel)
im_mask |= hitmiss(im_binary, np.fliplr(kernel))
im_mask |= hitmiss(im_binary, kernel.T)
im_mask |= hitmiss(im_binary, np.flipud(kernel.T))
im_dst = im_binary & (1 - im_mask) * 255
cv2.imwrite('dst.png', im_dst)
How to remove single pixels on the borders of a blob?