singam96 commited on
Commit
ee85408
·
verified ·
1 Parent(s): 6933b5e

singam96/ShadeNet-5-35M: upload hf_draft

Browse files
Files changed (2) hide show
  1. inference/framing.py +48 -0
  2. inference/run_onnx.py +18 -20
inference/framing.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit a whole photo into the model's square input instead of cropping it.
2
+
3
+ The model takes 448x448. `letterbox` scales the photo so its LONG side is 448
4
+ and fills the rest of the square by mirroring the photo's own edge (the model
5
+ never saw flat-coloured bars, and the test-time rotation already feeds it
6
+ reflected borders). After the model runs, `crop_to_box` cuts the padding off
7
+ the maps again, so nothing of the photo is lost and nothing invented is shown.
8
+ """
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import Image
13
+
14
+
15
+ def letterbox(img: Image.Image, size: int):
16
+ """Return (square PIL image, (left, top, w, h) of the real photo in it)."""
17
+ img = img.convert("RGB")
18
+ w, h = img.size
19
+ scale = size / float(max(w, h))
20
+ nw, nh = max(1, int(round(w * scale))), max(1, int(round(h * scale)))
21
+ arr = np.asarray(img.resize((nw, nh), Image.BICUBIC))
22
+ left, top = (size - nw) // 2, (size - nh) // 2
23
+ pad = ((top, size - nh - top), (left, size - nw - left), (0, 0))
24
+ # 'symmetric' (edge pixel included) is safe for any pad width, even when
25
+ # the padding is longer than the photo itself (a very elongated panorama).
26
+ out = np.pad(arr, pad, mode="symmetric")
27
+ return Image.fromarray(out), (left, top, nw, nh)
28
+
29
+
30
+ def crop_to_box(maps: torch.Tensor, box) -> torch.Tensor:
31
+ """Cut [B, C, S, S] maps down to the photo's own pixels."""
32
+ left, top, w, h = box
33
+ return maps[:, :, top:top + h, left:left + w]
34
+
35
+
36
+ def resize_maps(maps: torch.Tensor, width: int, height: int) -> torch.Tensor:
37
+ """Resize 7-channel maps for display and keep the normals unit length."""
38
+ out = F.interpolate(maps.float(), size=(height, width), mode="bicubic",
39
+ align_corners=False).clamp(-1.0, 1.0)
40
+ n = out[:, 4:7]
41
+ out[:, 4:7] = n / n.norm(dim=1, keepdim=True).clamp_min(1e-6)
42
+ return out
43
+
44
+
45
+ def display_size(w: int, h: int, longest: int = 1024):
46
+ """Output size: the photo's own shape, long side at most `longest`."""
47
+ s = min(1.0, longest / float(max(w, h)))
48
+ return max(1, int(round(w * s))), max(1, int(round(h * s)))
inference/run_onnx.py CHANGED
@@ -3,8 +3,10 @@
3
  pip install onnxruntime numpy pillow torch huggingface_hub
4
  python run_onnx.py photos/ --enhanced --out out/
5
 
6
- Each photo becomes a panel image: input | albedo | depth | normal. The model
7
- downloads from the Hub unless you pass --onnx. torch is only used by the
 
 
8
  rotation resampling of --enhanced (mirror + rotations of +-4 degrees, six
9
  forward passes, unit-length normals); plain runs are one pass.
10
  """
@@ -15,10 +17,11 @@ import sys
15
  import numpy as np
16
  import onnxruntime as ort
17
  import torch
18
- from PIL import Image
19
 
20
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21
  from ensemble import tta_average, unit_normals # noqa: E402
 
22
 
23
  REPO = "singam96/ShadeNet-5-35M"
24
  ONNX_FILE = "onnx/shadenet5_mix_int4_int8.onnx"
@@ -26,17 +29,6 @@ SIZE = 448 # 448 or 896 (multiples of 448 only)
26
  ROT_DEG = 4.0
27
 
28
 
29
- def resize_pad(img: Image.Image, size: int) -> Image.Image:
30
- """Scale to cover and centre-crop to a square."""
31
- img = img.convert("RGB")
32
- w, h = img.size
33
- scale = max(size / float(w), size / float(h))
34
- nw, nh = max(1, int(round(w * scale))), max(1, int(round(h * scale)))
35
- img = img.resize((nw, nh), Image.BICUBIC)
36
- left, top = (nw - size) // 2, (nh - size) // 2
37
- return img.crop((left, top, left + size, top + size))
38
-
39
-
40
  def to_tensor(img: Image.Image) -> torch.Tensor:
41
  arr = np.asarray(img, dtype=np.float32) / 255.0
42
  return torch.from_numpy(arr.transpose(2, 0, 1)[None] * 2.0 - 1.0)
@@ -57,6 +49,8 @@ def main():
57
  ap.add_argument("--size", type=int, default=SIZE, choices=[448, 896])
58
  ap.add_argument("--enhanced", action="store_true",
59
  help="mirror + rotations of +-4 degrees, six passes")
 
 
60
  ap.add_argument("--threads", type=int, default=8,
61
  help="ONNX Runtime threads (more than your cores is slower)")
62
  args = ap.parse_args()
@@ -80,18 +74,22 @@ def main():
80
  files = [args.photos]
81
  os.makedirs(args.out, exist_ok=True)
82
  for fp in files:
83
- photo = resize_pad(Image.open(fp), args.size)
84
- x = to_tensor(photo)
 
85
  with torch.no_grad():
86
  if args.enhanced:
87
  maps = unit_normals(tta_average(refine, x, flip=True, rot_deg=ROT_DEG))
88
  else:
89
  maps = refine(x)
90
- tiles = [photo, to_img((maps[:, 0:3] + 1) / 2),
 
 
 
91
  to_img((maps[:, 3:4] + 1) / 2), to_img((maps[:, 4:7] + 1) / 2)]
92
- panel = Image.new("RGB", (args.size * 4, args.size))
93
- for i, t in enumerate(tiles):
94
- panel.paste(t, (i * args.size, 0))
95
  dst = os.path.join(args.out, os.path.splitext(os.path.basename(fp))[0] + ".png")
96
  panel.save(dst)
97
  print("saved", dst)
 
3
  pip install onnxruntime numpy pillow torch huggingface_hub
4
  python run_onnx.py photos/ --enhanced --out out/
5
 
6
+ Each photo becomes a panel image: input | albedo | depth | normal, at the photo's
7
+ own shape (the whole photo is kept: its long side is scaled to 448 and the rest of
8
+ the square is filled by mirroring its edge, then the padding is cut off the maps).
9
+ The model downloads from the Hub unless you pass --onnx. torch is only used by the
10
  rotation resampling of --enhanced (mirror + rotations of +-4 degrees, six
11
  forward passes, unit-length normals); plain runs are one pass.
12
  """
 
17
  import numpy as np
18
  import onnxruntime as ort
19
  import torch
20
+ from PIL import Image, ImageOps
21
 
22
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
23
  from ensemble import tta_average, unit_normals # noqa: E402
24
+ from framing import crop_to_box, display_size, letterbox, resize_maps # noqa: E402
25
 
26
  REPO = "singam96/ShadeNet-5-35M"
27
  ONNX_FILE = "onnx/shadenet5_mix_int4_int8.onnx"
 
29
  ROT_DEG = 4.0
30
 
31
 
 
 
 
 
 
 
 
 
 
 
 
32
  def to_tensor(img: Image.Image) -> torch.Tensor:
33
  arr = np.asarray(img, dtype=np.float32) / 255.0
34
  return torch.from_numpy(arr.transpose(2, 0, 1)[None] * 2.0 - 1.0)
 
49
  ap.add_argument("--size", type=int, default=SIZE, choices=[448, 896])
50
  ap.add_argument("--enhanced", action="store_true",
51
  help="mirror + rotations of +-4 degrees, six passes")
52
+ ap.add_argument("--max-side", type=int, default=1024,
53
+ help="long side of the output panel tiles, in pixels")
54
  ap.add_argument("--threads", type=int, default=8,
55
  help="ONNX Runtime threads (more than your cores is slower)")
56
  args = ap.parse_args()
 
74
  files = [args.photos]
75
  os.makedirs(args.out, exist_ok=True)
76
  for fp in files:
77
+ img = ImageOps.exif_transpose(Image.open(fp)).convert("RGB")
78
+ square, box = letterbox(img, args.size)
79
+ x = to_tensor(square)
80
  with torch.no_grad():
81
  if args.enhanced:
82
  maps = unit_normals(tta_average(refine, x, flip=True, rot_deg=ROT_DEG))
83
  else:
84
  maps = refine(x)
85
+ maps = crop_to_box(maps.float(), box)
86
+ ow, oh = display_size(*img.size, longest=args.max_side)
87
+ maps = resize_maps(maps, ow, oh)
88
+ tiles = [img.resize((ow, oh), Image.BICUBIC), to_img((maps[:, 0:3] + 1) / 2),
89
  to_img((maps[:, 3:4] + 1) / 2), to_img((maps[:, 4:7] + 1) / 2)]
90
+ panel = Image.new("RGB", (ow * 4, oh))
91
+ for i, tile in enumerate(tiles):
92
+ panel.paste(tile, (i * ow, 0))
93
  dst = os.path.join(args.out, os.path.splitext(os.path.basename(fp))[0] + ".png")
94
  panel.save(dst)
95
  print("saved", dst)