File size: 1,561 Bytes
3d46bcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""Conservative source-only compositing and review images."""
import cv2
import numpy as np
from .common import gray


def compose(reference, aligned, valid, trusted, exposure):
    h, w = reference.shape[:2]
    rg, ag = gray(reference), gray(aligned)
    usable = valid & (rg > 25) & (rg < 230) & (ag > 15) & (ag < 230)
    gain = float(np.clip(np.median(rg[usable] / np.maximum(ag[usable], 1)), 1, 2.5)) if exposure and usable.any() else 1.
    adjusted = np.clip(aligned.astype(np.float32) * gain, 0, 255).astype(np.uint8)
    # Photometric agreement is a heuristic, NOT proof of anatomical correspondence.
    discrepancy = cv2.GaussianBlur(cv2.absdiff(gray(adjusted), rg).astype(np.float32), (0, 0), 2)
    safe = usable & trusted & (discrepancy < 12) & (gray(adjusted) < 245)
    safe = cv2.erode(safe.astype(np.uint8), np.ones((5, 5), np.uint8))
    weight = .5 * cv2.GaussianBlur(safe.astype(np.float32), (0, 0), 2) * safe
    composite = np.rint(reference * (1-weight[..., None]) + adjusted * weight[..., None]).astype(np.uint8)
    overlay = cv2.addWeighted(reference, .5, adjusted, .5, 0)
    yy, xx = np.indices((h, w), dtype=np.int32)
    checker = np.where((((xx//64 + yy//64) % 2 == 0) & valid)[..., None], adjusted, reference)
    return dict(aligned=aligned, adjusted=adjusted, composite=composite, overlay=overlay, checkerboard=checker, contribution=np.rint(weight*255).astype(np.uint8), difference=cv2.absdiff(reference, adjusted)), dict(exposure_gain=gain, overlap_fraction=float(valid.mean()), blended_fraction=float((weight > 0).mean()))