syntax-video-infer / engine /preprocessing.py
MesserMMP's picture
Rebuild CardioSyntax with custom bilingual UI and verified inference
1024e04 verified
Raw History Blame Contribute Delete
2.05 kB
"""The published inference transforms, without augmentation or temporal resampling."""
import numpy as np
import torch
from torchvision.transforms import InterpolationMode
from torchvision.transforms.functional import resize
from .dicom import InferenceError
MEAN = (0.485, 0.456, 0.406)
STD = (0.229, 0.224, 0.225)
def to_uint8(video):
video = np.asarray(video)
if video.ndim != 3 or video.shape[0] == 0:
raise InferenceError("Expected a non-empty grayscale video with shape frames × height × width.")
if video.dtype.kind != "u" or video.dtype.itemsize not in (1, 2):
raise InferenceError("Only unsigned 8-bit and 16-bit videos are supported.")
if video.dtype.itemsize == 2:
vmax = int(video.max())
if vmax <= 0:
raise InferenceError("The 16-bit video has no usable pixel intensities.")
return (video.astype(np.float32) * (255.0 / vmax)).clip(0, 255).astype(np.uint8)
return video.astype(np.uint8, copy=False)
def _transform(video, size, *, antialias):
# Identical to ToTensorVideo -> Resize -> pytorchvideo.Normalize.
rgb = np.stack([video, video, video], axis=-1)
x = torch.from_numpy(rgb).permute(3, 0, 1, 2).to(dtype=torch.float32).div(255.0)
x = resize(x, [size, size], interpolation=InterpolationMode.BILINEAR, antialias=antialias)
mean = x.new_tensor(MEAN).view(3, 1, 1, 1)
std = x.new_tensor(STD).view(3, 1, 1, 1)
return (x - mean) / std
def preprocess_score(video):
video = to_uint8(video)
while video.shape[0] < 32:
video = np.concatenate([video, video], axis=0)
begin = (video.shape[0] - 32) // 2
return _transform(video[begin:begin + 32], 256, antialias=True)
def preprocess_classifier(video):
# The classifier uses every original frame, not the score model's 32-frame clip.
# Explicit legacy tensor resize reproduces the archived Philips classifier
# probabilities. Torchvision changed its unspecified default in version 0.17.
return _transform(to_uint8(video), 224, antialias=False)