File size: 4,407 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
2ad60ce
 
f877698
 
 
 
 
2ad60ce
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
from __future__ import annotations

import math
import numpy as np

from .rgb import gt_float, scalar

MIN_PIXELS = 49


def weighted_mean(values, weight):
    import torch
    weight = weight.expand_as(values)
    total_weight = weight.sum()
    ones = torch.ones((), dtype=weight.dtype, device=weight.device)
    safe = torch.where(total_weight > 0, total_weight, ones)
    return (values * weight).sum() / safe


def pixel_errors(pred, gt):
    pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), np.clip(np.asarray(gt, np.float32), 0, 1)
    if pred.shape != gt.shape or pred.ndim not in (3, 4) or pred.shape[-1] != 3:
        raise ValueError('regional RGB expects matching HWC / NHWC three-channel arrays')
    if not np.isfinite(pred).all() or not np.isfinite(gt).all():
        raise ValueError('nonfinite RGB')
    return np.mean(np.square((pred - gt).astype(np.float64)), axis=-1)


def psnr(mse):
    return scalar(float('inf') if mse == 0 else -10 * math.log10(mse))


def ssim_map(pred, gt):
    from skimage.metrics import structural_similarity
    _, values = structural_similarity(pred, gt, channel_axis=2, data_range=1., full=True,
                                      win_size=7, gaussian_weights=False, sigma=1.5, use_sample_covariance=True)
    return values.mean(axis=-1)


def aggregate_region(frames, positions, *, min_pixels=MIN_PIXELS):
    selected = [frames[i] for i in positions]
    pixels = sum(f['pixels'] for f in selected)
    sse = sum(f['sse'] for f in selected)
    out = dict(pixels=pixels, sse=sse, mse=sse / pixels if pixels else None,
               psnr=None, ssim=None, lpips=None,
               status='ok' if pixels >= min_pixels else 'empty' if not pixels else 'below_min_pixels')
    if pixels < min_pixels:
        return out
    out['psnr'] = psnr(sse / pixels)
    for metric in ('ssim', 'lpips'):
        valid = [f for f in selected if f.get(metric) is not None and f['pixels']]
        out[metric] = sum(f[metric] * f['pixels'] for f in valid) / sum(f['pixels'] for f in valid) if valid else None
    return out


class RegionScorer:
    def __init__(self, device='cpu', *, min_pixels=MIN_PIXELS):
        self.device, self.min_pixels = device, min_pixels
        self._spatial = {}

    def lpips(self, net='alex'):
        if net not in self._spatial:
            import lpips
            model = lpips.LPIPS(net=net, spatial=True, verbose=False).eval().to(self.device)
            for parameter in model.parameters():
                parameter.requires_grad_(False)
            self._spatial[net] = model
        return self._spatial[net]

    def lpips_map(self, pred, gt, mask, *, blackout=True, net='alex'):
        import torch
        p = torch.from_numpy(np.ascontiguousarray(pred.transpose(2, 0, 1))).to(self.device)[None]
        g = torch.from_numpy(np.ascontiguousarray(gt.transpose(2, 0, 1))).to(self.device)[None]
        w = torch.as_tensor(mask.copy(), dtype=p.dtype, device=self.device)[None, None]
        if blackout:
            p, g = p * w, g * w
        with torch.inference_mode():
            distance = self.lpips(net)(p * 2 - 1, g * 2 - 1)
            return float(weighted_mean(distance, w).item())

    def score_region(self, pred, gt, mask, *, structural=True, perceptual=True):
        pred, gt, mask = np.clip(np.asarray(pred, np.float32), 0, 1), np.asarray(gt, np.float32), np.asarray(mask, bool)
        if pred.shape != gt.shape or mask.shape != pred.shape[:-1]:
            raise ValueError('mask shape must match every target frame, without channel axis')
        se = pixel_errors(pred, gt)
        frames = []
        for p, g, m, err in zip(pred, gt, mask, se):
            pixels = int(m.sum())
            f = dict(pixels=pixels, sse=float(err[m].sum(dtype=np.float64)), ssim=None, lpips=None)
            if pixels:
                pm, gm = p * m[..., None], g * m[..., None]
                if structural:
                    f['ssim'] = float(ssim_map(pm, gm)[m].mean(dtype=np.float64))
                if perceptual:
                    f['lpips'] = self.lpips_map(p, g, m)
            frames.append(f)
        return frames

    def region(self, pred, gt_u8, mask, *, structural=True, perceptual=True):
        frames = self.score_region(pred, gt_float(gt_u8), mask, structural=structural, perceptual=perceptual)
        return aggregate_region(frames, range(len(frames)), min_pixels=self.min_pixels)