forked from isl-org/MiDaS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpredict.py
71 lines (60 loc) · 2.07 KB
/
predict.py
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
import torch
import cv2
from PIL import Image
import numpy as np
from cog import BasePredictor, Input, Path
import utils
from midas.model_loader import load_model
MODEL_CACHE = "weights"
class Predictor(BasePredictor):
def setup(self):
"""Load the model into memory to make running multiple predictions efficient"""
self.device = "cuda"
models = [
"dpt_beit_large_512",
"dpt_swin2_large_384",
"dpt_swin2_tiny_256",
"dpt_levit_224",
]
self.models = {
model: load_model(
self.device, model_path=f"weights/{model}.pt", model_type=model
)
for model in models
}
def predict(
self,
model_type: str = Input(
default="dpt_beit_large_512",
choices=[
"dpt_beit_large_512",
"dpt_swin2_large_384",
"dpt_swin2_tiny_256",
"dpt_levit_224",
],
),
image: Path = Input(description="Input image"),
) -> Path:
"""Run a single prediction on the model"""
model, transform, net_w, net_h = self.models[model_type]
model.to(self.device)
model.eval()
original_image_rgb = utils.read_image(str(image))
image = transform({"image": original_image_rgb})["image"]
target_size = original_image_rgb.shape[1::-1]
with torch.no_grad():
sample = torch.from_numpy(image).to(self.device).unsqueeze(0)
height, width = sample.shape[2:]
prediction = model.forward(sample)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=target_size[::-1],
mode="bicubic",
align_corners=False,
).squeeze()
output_path = "/tmp/out.png"
output = prediction.cpu().numpy()
formatted = (output * 255 / np.max(output)).astype("uint8")
img = Image.fromarray(formatted)
img.save(output_path)
return Path(output_path)