|
a |
|
b/tissue_detection.py |
|
|
1 |
import numpy as np |
|
|
2 |
import cv2 |
|
|
3 |
|
|
|
4 |
|
|
|
5 |
def tissue_detection(img, remove_top_percentage=0.2): |
|
|
6 |
|
|
|
7 |
assert 0 <= remove_top_percentage < 1, (f"remove_top_percentage needs to be in [0, 1). You passed " |
|
|
8 |
f"{remove_top_percentage}.") |
|
|
9 |
|
|
|
10 |
kernel_size = 3 |
|
|
11 |
|
|
|
12 |
# remove alpha channel |
|
|
13 |
img = img[:, :, 0:3] |
|
|
14 |
|
|
|
15 |
top_border = int(len(img)*remove_top_percentage) |
|
|
16 |
# hack for removing border artifacts |
|
|
17 |
img[0:top_border, :, :] = [0, 0, 0] |
|
|
18 |
|
|
|
19 |
# remove black background pixel |
|
|
20 |
black_px = np.where((img[:, :, 0] <= 5) & (img[:, :, 1] <= 5) & (img[:, :, 2] <= 5)) |
|
|
21 |
img[black_px] = [255, 255, 255] |
|
|
22 |
|
|
|
23 |
# apply median filter to remove artifacts created by transitions to background pixels |
|
|
24 |
median_filtered_img = cv2.medianBlur(img, 11) |
|
|
25 |
|
|
|
26 |
# convert to HSV color space |
|
|
27 |
hsv_image = cv2.cvtColor(median_filtered_img, cv2.COLOR_RGB2HSV) |
|
|
28 |
|
|
|
29 |
# get saturation channel |
|
|
30 |
saturation = hsv_image[:, :, 1] |
|
|
31 |
|
|
|
32 |
# Otsu's thresholding |
|
|
33 |
_, threshold_image = cv2.threshold(saturation, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) |
|
|
34 |
|
|
|
35 |
# apply dilation to image to close spots inside mask regions |
|
|
36 |
kernel = np.ones(shape=(kernel_size, kernel_size)) |
|
|
37 |
tissue_mask = cv2.dilate(threshold_image, kernel, iterations=1) |
|
|
38 |
# tissue_mask = cv2.erode(tissue_mask, kernel) |
|
|
39 |
|
|
|
40 |
return tissue_mask |