utilities.py
| 1 | import torch |
| 2 | import torch.nn.functional as F |
| 3 | from torchvision.transforms.functional import normalize |
| 4 | import numpy as np |
| 5 | |
| 6 | def preprocess_image(im: np.ndarray, model_input_size: list) -> torch.Tensor: |
| 7 | if len(im.shape) < 3: |
| 8 | im = im[:, :, np.newaxis] |
| 9 | # orig_im_size=im.shape[0:2] |
| 10 | im_tensor = torch.tensor(im, dtype=torch.float32).permute(2,0,1) |
| 11 | im_tensor = F.interpolate(torch.unsqueeze(im_tensor,0), size=model_input_size, mode='bilinear').type(torch.uint8) |
| 12 | image = torch.divide(im_tensor,255.0) |
| 13 | image = normalize(image,[0.5,0.5,0.5],[1.0,1.0,1.0]) |
| 14 | return image |
| 15 | |
| 16 | |
| 17 | def postprocess_image(result: torch.Tensor, im_size: list)-> np.ndarray: |
| 18 | result = torch.squeeze(F.interpolate(result, size=im_size, mode='bilinear') ,0) |
| 19 | ma = torch.max(result) |
| 20 | mi = torch.min(result) |
| 21 | result = (result-mi)/(ma-mi) |
| 22 | im_array = (result*255).permute(1,2,0).cpu().data.numpy().astype(np.uint8) |
| 23 | im_array = np.squeeze(im_array) |
| 24 | return im_array |
| 25 | |