fureunoir

Untitled

Dec 8th, 2021 (edited)
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. import sys
  2. import os
  3. import cv2
  4. import torch
  5. import warnings
  6. import numpy as np
  7. import albumentations as albs
  8. import segmentation_models_pytorch as smp
  9. from albumentations.pytorch.transforms import ToTensorV2
  10. from torch import nn
  11.  
  12.  
  13. MODEL_PATH = "model_final.pth"
  14. IMG_SIZE = 256
  15. FRAME_SIZE = 1024
  16.  
  17.  
  18. def predict(image, model, device):
  19.     image_shape = image.shape
  20.     alb_transforms = albs.Compose([albs.Resize(IMG_SIZE, IMG_SIZE), albs.Normalize(), ToTensorV2()])
  21.     now = alb_transforms(image=image)['image'].to(device).view(1, 3, IMG_SIZE, IMG_SIZE)
  22.     piction = model(now)
  23.     piction = nn.Sigmoid()(piction)
  24.     piction = (piction > 0.45)
  25.     piction = piction[0].detach().cpu().numpy().astype(float)[0]
  26.     piction = albs.Resize(image_shape[0], image_shape[1])(image=piction)['image']
  27.  
  28.     return piction.astype(bool)
  29.  
  30.  
  31. def get_model():
  32.     return smp.Unet(encoder_name="efficientnet-b6", encoder_weights=None, in_channels=3, classes=1)
  33.  
  34.  
  35. def get_shape(shape):
  36.     return (shape[0] + FRAME_SIZE - 1) // FRAME_SIZE * FRAME_SIZE, (shape[1] + FRAME_SIZE - 1) // FRAME_SIZE * FRAME_SIZE, shape[2]
  37.  
  38.  
  39. def main():
  40.     device = torch.device("cuda")
  41.     tips, output_path = sys.argv[1:]
  42.     model = get_model().to(device)
  43.     model.load_state_dict(torch.load(MODEL_PATH, map_location=device))
  44.     model = model.eval()
  45.     results = {}
  46.  
  47.     for i in os.listdir(tips):
  48.         img_path = os.path.join(tips, i)
  49.         im = cv2.imread(img_path)
  50.         image = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
  51.         mask = predict(image, model, device)
  52.         results[i] = mask
  53.     np.savez_compressed(os.path.join(output_path), **results)
  54.  
  55.  
  56. if __name__ == "__main__":
  57.     main()
  58.  
Advertisement
Add Comment
Please, Sign In to add comment