DmitryPlant's picture
Deploy local
e04bbc2 verified
Raw History Blame Contribute Delete
17.8 kB
"""Pipeline stage functions ported from analysis.ipynb.
DO NOT modify algorithm behaviour here. If you need to change a stage,
prototype in the notebook first, then re-port.
"""
import cv2
import numpy as np
from skimage.morphology import reconstruction
def create_circular_mask_v2(img, hue_range=(10, 35), min_hue_fraction=0.05, shrink_factor=0.95):
"""
Detect the circular microscope field of view with hue validation.
After finding candidate circles (sorted by area), validates each by checking
that its interior contains at least min_hue_fraction pixels with amber/golden
hue. Rejects false circles from the bright microscope surround.
Parameters:
- hue_range: (low, high) OpenCV hue range for amber/golden fiber color
- min_hue_fraction: minimum fraction of pixels inside circle that must have amber hue
- shrink_factor: shrink the final circle radius to avoid edge artifacts
"""
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h_channel = hsv[:, :, 0]
img_h, img_w = gray.shape
_, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)
kernel = np.ones((5, 5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=3)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
best_cx, best_cy, best_radius = img_w // 2, img_h // 2, min(img_h, img_w) // 3
for contour in contours:
area = cv2.contourArea(contour)
if area < 1000:
break
(cx, cy), radius = cv2.minEnclosingCircle(contour)
cx, cy, radius = int(cx), int(cy), int(radius)
temp_mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.circle(temp_mask, (cx, cy), radius, 255, -1)
inside_pixels = temp_mask > 0
total_inside = inside_pixels.sum()
if total_inside == 0:
continue
hue_inside = h_channel[inside_pixels]
amber_count = np.sum((hue_inside >= hue_range[0]) & (hue_inside <= hue_range[1]))
amber_fraction = amber_count / total_inside
if amber_fraction >= min_hue_fraction:
best_cx, best_cy = cx, cy
best_radius = int(radius * shrink_factor)
break
mask = np.zeros(gray.shape, dtype=np.uint8)
cv2.circle(mask, (best_cx, best_cy), best_radius, 255, -1)
return mask, (best_cx, best_cy, best_radius)
def normalize_brightness(img, mask):
"""
Apply CLAHE (Contrast Limited Adaptive Histogram Equalization)
to normalize uneven lighting in the microscope image.
"""
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
l_clahe = clahe.apply(l)
lab_clahe = cv2.merge([l_clahe, a, b])
result = cv2.cvtColor(lab_clahe, cv2.COLOR_LAB2BGR)
result = cv2.bitwise_and(result, result, mask=mask)
return result
def denoise_jpeg_artifacts(img, d=9, sigmaColor=75, sigmaSpace=75):
"""
Apply bilateral filter to suppress JPEG compression block artifacts.
Bilateral filter smooths within flat regions (bridging 8x8 block boundaries)
while preserving true edges (bundle boundaries). Diameter d=9 spans JPEG
block boundaries (8px).
Parameters:
- d: diameter of pixel neighborhood (9 spans JPEG blocks)
- sigmaColor: filter sigma in the color space
- sigmaSpace: filter sigma in the coordinate space
"""
return cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)
def threshold_fibers_multichannel(img, mask, v_mode='otsu', s_mode='otsu',
v_threshold=150, s_threshold=50,
v_otsu_offset=0, s_otsu_offset=0,
use_hue_filter=True, hue_low=8, hue_high=28,
max_area_fraction=0.30,
bright_keep_threshold=180):
"""
Multi-channel thresholding with union strategy:
- Pixels above bright_keep_threshold are ALWAYS kept (preserves bright bundle shapes)
- Pixels below that must pass V_otsu + S_otsu + Hue filter (catches dim golden bundles)
final_mask = (V > bright_keep) OR (V > otsu AND S > otsu AND H in hue_range)
Parameters:
- bright_keep_threshold: V value above which pixels are always kept (no S/H filtering)
- v_mode/s_mode: 'otsu' or 'fixed' for the dim-bundle detection branch
- use_hue_filter: apply hue filter on the dim-bundle branch
- hue_low/hue_high: OpenCV hue range for golden/amber
- max_area_fraction: safety cap on total selected area
"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h_ch, s, v = cv2.split(hsv)
v_masked = cv2.bitwise_and(v, v, mask=mask)
s_masked = cv2.bitwise_and(s, s, mask=mask)
total_mask_pixels = cv2.countNonZero(mask)
_, bright_mask = cv2.threshold(v_masked, bright_keep_threshold, 255, cv2.THRESH_BINARY)
bright_mask = cv2.bitwise_and(bright_mask, mask)
if v_mode == 'otsu':
v_values = v_masked[mask > 0]
otsu_v, _ = cv2.threshold(v_values, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
v_thresh_used = int(np.clip(otsu_v + v_otsu_offset, 0, 255))
else:
v_thresh_used = v_threshold
if s_mode == 'otsu':
s_values = s_masked[mask > 0]
otsu_s, _ = cv2.threshold(s_values, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
s_thresh_used = int(np.clip(otsu_s + s_otsu_offset, 0, 255))
else:
s_thresh_used = s_threshold
_, v_binary = cv2.threshold(v_masked, v_thresh_used, 255, cv2.THRESH_BINARY)
_, s_binary = cv2.threshold(s_masked, s_thresh_used, 255, cv2.THRESH_BINARY)
dim_mask = cv2.bitwise_and(v_binary, s_binary)
if use_hue_filter:
h_binary = cv2.inRange(h_ch, hue_low, hue_high)
h_binary = cv2.bitwise_and(h_binary, mask)
dim_mask = cv2.bitwise_and(dim_mask, h_binary)
dim_mask = cv2.bitwise_and(dim_mask, mask)
fused_mask = cv2.bitwise_or(bright_mask, dim_mask)
for attempt in range(10):
area_fraction = cv2.countNonZero(fused_mask) / total_mask_pixels
if area_fraction <= max_area_fraction:
break
bright_keep_threshold += 5
_, bright_mask = cv2.threshold(v_masked, bright_keep_threshold, 255, cv2.THRESH_BINARY)
bright_mask = cv2.bitwise_and(bright_mask, mask)
fused_mask = cv2.bitwise_or(bright_mask, dim_mask)
thresholds = {'v_otsu': v_thresh_used, 's_otsu': s_thresh_used,
'bright_keep': bright_keep_threshold,
'hue_filter': f'H={hue_low}-{hue_high}' if use_hue_filter else 'off',
'area_fraction': f'{area_fraction:.1%}'}
return fused_mask, bright_mask, dim_mask, thresholds
def morphological_cleanup_v2(binary_mask, small_kernel=3, large_kernel=7,
close_iters=2, open_iters=1, smooth_kernel=9,
min_component_area=50):
"""
Multi-scale morphological cleanup with contour smoothing.
Steps:
1. Large CLOSE (7x7, 2 iters) - bridges JPEG compression gaps
2. Small OPEN (3x3, 1 iter) - removes small noise specks
3. Small CLOSE (3x3, 1 iter) - fills remaining pinholes
4. Gaussian blur + re-threshold - smooths jagged contour edges
5. Remove tiny connected components below min_component_area
Parameters:
- small_kernel: kernel size for fine operations
- large_kernel: kernel size for gap-bridging close
- close_iters: iterations for the large close operation
- open_iters: iterations for the noise removal open
- smooth_kernel: Gaussian blur kernel for contour smoothing (odd number)
- min_component_area: remove components smaller than this (pixels)
"""
k_large = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (large_kernel, large_kernel))
k_small = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (small_kernel, small_kernel))
result = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, k_large, iterations=close_iters)
result = cv2.morphologyEx(result, cv2.MORPH_OPEN, k_small, iterations=open_iters)
result = cv2.morphologyEx(result, cv2.MORPH_CLOSE, k_small, iterations=1)
blurred = cv2.GaussianBlur(result, (smooth_kernel, smooth_kernel), 0)
_, result = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(result, connectivity=8)
for i in range(1, num_labels):
if stats[i, cv2.CC_STAT_AREA] < min_component_area:
result[labels == i] = 0
return result
def find_seeds_hmaxima(binary_mask, h=5, min_seed_area=5):
"""
Find watershed seeds using h-maxima transform on the distance map.
Instead of thresholding at a fraction of the global max (which kills small
bundle seeds), h-maxima finds ALL local maxima with prominence >= h pixels.
A small bundle with peak=12 and local trough=2 (prominence=10) gets its
own seed even when the global max distance is 50.
Parameters:
- h: minimum peak prominence in distance-transform units (pixels)
- min_seed_area: minimum connected component area for a valid seed
Returns:
- seeds: binary mask of seed regions
- dist: distance transform map
"""
dist = cv2.distanceTransform(binary_mask, cv2.DIST_L2, 5)
dist_f = dist.astype(np.float64)
marker = np.clip(dist_f - h, 0, None)
reconstructed = reconstruction(marker, dist_f, method='dilation')
hmaxima_map = dist_f - reconstructed
seeds = (hmaxima_map > 0).astype(np.uint8) * 255
if min_seed_area > 1:
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(seeds, connectivity=8)
for i in range(1, num_labels):
if stats[i, cv2.CC_STAT_AREA] < min_seed_area:
seeds[labels == i] = 0
return seeds, dist
def segment_bundles_v2(binary_mask, original_img, min_area=100, h=5, min_seed_area=5):
"""
Segment fiber bundles using watershed with h-maxima seed detection.
Parameters:
- binary_mask: white = fibers, black = background
- original_img: original BGR image for watershed edge detection
- min_area: minimum bundle area in pixels
- h: h-maxima prominence threshold (distance-transform pixels)
- min_seed_area: minimum seed connected component area
Returns:
- bundles: list of detected bundles with contours and properties
- markers: watershed marker image
"""
seeds, dist = find_seeds_hmaxima(binary_mask, h=h, min_seed_area=min_seed_area)
kernel = np.ones((3, 3), np.uint8)
sure_bg = cv2.dilate(binary_mask, kernel, iterations=3)
unknown = cv2.subtract(sure_bg, seeds)
num_labels, markers = cv2.connectedComponents(seeds)
markers = markers + 1
markers[unknown == 255] = 0
markers = cv2.watershed(original_img, markers)
bundles = []
for i in range(2, num_labels + 1):
bundle_mask = (markers == i).astype(np.uint8) * 255
area = cv2.countNonZero(bundle_mask)
if area < min_area:
continue
contours, _ = cv2.findContours(bundle_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
continue
contour = max(contours, key=cv2.contourArea)
M = cv2.moments(contour)
if M["m00"] == 0:
continue
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
bundles.append({
'id': len(bundles) + 1,
'area': area,
'center': (cx, cy),
'contour': contour,
'mask': bundle_mask
})
return bundles, markers
def merge_fragments(bundles, original_img, merge_area_threshold=500,
proximity_threshold=15, color_similarity_threshold=30):
"""
Merge adjacent small watershed fragments that likely belong to the same bundle.
Conditions for merging: (a) at least one fragment has area < merge_area_threshold,
(b) contours are within proximity_threshold px, (c) mean LAB color difference <
color_similarity_threshold. Uses union-find for transitive merging.
Parameters:
- bundles: list of bundle dicts from segment_bundles_v2
- original_img: BGR image for color comparison
- merge_area_threshold: max area for a fragment to be merge-eligible
- proximity_threshold: max distance between contours (pixels)
- color_similarity_threshold: max mean LAB color difference
Returns:
- merged_bundles: new list of bundles after merging
"""
if len(bundles) <= 1:
return bundles
lab = cv2.cvtColor(original_img, cv2.COLOR_BGR2LAB).astype(np.float32)
n = len(bundles)
mean_colors = []
for b in bundles:
b_mask = b['mask'] > 0
if b_mask.sum() > 0:
mean_colors.append(lab[b_mask].mean(axis=0))
else:
mean_colors.append(np.array([0.0, 128.0, 128.0]))
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
kernel_prox = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
(2 * proximity_threshold + 1, 2 * proximity_threshold + 1))
bboxes = [cv2.boundingRect(b['mask']) for b in bundles]
inflate = proximity_threshold
H, W = bundles[0]['mask'].shape
tiles: list[tuple[int, int, np.ndarray]] = []
for idx in range(n):
x, y, w, h = bboxes[idx]
x0 = max(0, x - inflate)
y0 = max(0, y - inflate)
x1 = min(W, x + w + inflate)
y1 = min(H, y + h + inflate)
crop = bundles[idx]['mask'][y0:y1, x0:x1]
dil = cv2.dilate(crop, kernel_prox, iterations=1)
tiles.append((x0, y0, dil))
for i in range(n):
xi, yi, wi, hi = bboxes[i]
x0i, y0i, dil_i = tiles[i]
h_i, w_i = dil_i.shape
for j in range(i + 1, n):
if bundles[i]['area'] >= merge_area_threshold and bundles[j]['area'] >= merge_area_threshold:
continue
xj, yj, wj, hj = bboxes[j]
if (xi + wi + inflate <= xj or xj + wj + inflate <= xi
or yi + hi + inflate <= yj or yj + hj + inflate <= yi):
continue
ax0 = max(x0i, xj)
ay0 = max(y0i, yj)
ax1 = min(x0i + w_i, xj + wj)
ay1 = min(y0i + h_i, yj + hj)
if ax0 >= ax1 or ay0 >= ay1:
continue
tile_i = dil_i[ay0 - y0i:ay1 - y0i, ax0 - x0i:ax1 - x0i]
tile_j = bundles[j]['mask'][ay0:ay1, ax0:ax1]
overlap = cv2.bitwise_and(tile_i, tile_j)
if cv2.countNonZero(overlap) == 0:
continue
color_diff = np.linalg.norm(mean_colors[i] - mean_colors[j])
if color_diff > color_similarity_threshold:
continue
union(i, j)
groups = {}
for i in range(n):
root = find(i)
if root not in groups:
groups[root] = []
groups[root].append(i)
merged_bundles = []
for root, indices in groups.items():
if len(indices) == 1:
b = bundles[indices[0]].copy()
b['id'] = len(merged_bundles) + 1
merged_bundles.append(b)
else:
combined_mask = np.zeros_like(bundles[0]['mask'])
for idx in indices:
combined_mask = cv2.bitwise_or(combined_mask, bundles[idx]['mask'])
area = cv2.countNonZero(combined_mask)
contours, _ = cv2.findContours(combined_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
continue
contour = max(contours, key=cv2.contourArea)
M = cv2.moments(contour)
if M["m00"] == 0:
continue
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
merged_bundles.append({
'id': len(merged_bundles) + 1,
'area': area,
'center': (cx, cy),
'contour': contour,
'mask': combined_mask
})
return merged_bundles
def draw_bundles(img_rgb, bundles):
"""
Draw contours around each bundle with green color.
"""
result = img_rgb.copy()
green = (0, 200, 0)
h, w = result.shape[:2]
thickness = max(2, int(max(w, h) / 800 * 3))
for bundle in bundles:
cv2.drawContours(result, [bundle['contour']], -1, green, thickness)
return result
def colorize_markers(markers: np.ndarray) -> np.ndarray:
"""Convert watershed marker map to a colored BGR visualization."""
rng = np.random.default_rng(seed=42)
out = np.zeros((*markers.shape, 3), dtype=np.uint8)
unique = np.unique(markers)
for label in unique:
if label <= 1:
continue
color = rng.integers(50, 255, size=3, dtype=np.uint8)
out[markers == label] = color
out[markers == -1] = (255, 255, 255)
return out