NCJ commited on
Commit
57a1960
1 Parent(s): 234bf91

copy from dev

Browse files
.gitattributes CHANGED
@@ -33,3 +33,33 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ demo_examples/ filter=lfs diff=lfs merge=lfs -text
37
+ demo_examples/*.png filter=lfs diff=lfs merge=lfs -text
38
+ demo_examples/cup.jpg filter=lfs diff=lfs merge=lfs -text
39
+ demo_examples/teapot.png filter=lfs diff=lfs merge=lfs -text
40
+ demo_examples/cup.png filter=lfs diff=lfs merge=lfs -text
41
+ demo_examples/01.png filter=lfs diff=lfs merge=lfs -text
42
+ demo_examples/12.png filter=lfs diff=lfs merge=lfs -text
43
+ demo_examples/17.jpg filter=lfs diff=lfs merge=lfs -text
44
+ demo_examples/25.png filter=lfs diff=lfs merge=lfs -text
45
+ demo_examples/26.png filter=lfs diff=lfs merge=lfs -text
46
+ demo_examples/27.png filter=lfs diff=lfs merge=lfs -text
47
+ demo_examples/29.png filter=lfs diff=lfs merge=lfs -text
48
+ demo_examples/31.png filter=lfs diff=lfs merge=lfs -text
49
+ demo_examples/33.png filter=lfs diff=lfs merge=lfs -text
50
+ demo_examples/35.png filter=lfs diff=lfs merge=lfs -text
51
+ demo_examples/05.png filter=lfs diff=lfs merge=lfs -text
52
+ demo_examples/22.png filter=lfs diff=lfs merge=lfs -text
53
+ demo_examples/23.png filter=lfs diff=lfs merge=lfs -text
54
+ demo_examples/04.png filter=lfs diff=lfs merge=lfs -text
55
+ demo_examples/09.png filter=lfs diff=lfs merge=lfs -text
56
+ demo_examples/18.jpg filter=lfs diff=lfs merge=lfs -text
57
+ demo_examples/19.jpg filter=lfs diff=lfs merge=lfs -text
58
+ demo_examples/24.png filter=lfs diff=lfs merge=lfs -text
59
+ demo_examples/32.png filter=lfs diff=lfs merge=lfs -text
60
+ demo_examples/03.png filter=lfs diff=lfs merge=lfs -text
61
+ demo_examples/07.png filter=lfs diff=lfs merge=lfs -text
62
+ demo_examples/14.png filter=lfs diff=lfs merge=lfs -text
63
+ demo_examples/21.png filter=lfs diff=lfs merge=lfs -text
64
+ demo_examples/28.png filter=lfs diff=lfs merge=lfs -text
65
+ demo_examples/30.png filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ LABEL version="1.0.2"
4
+
5
+ ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
6
+ ENV TZ=America/Los_Angeles
7
+ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
8
+
9
+ RUN apt-get update && apt-get install -y --no-install-recommends \
10
+ curl \
11
+ libx11-6 \
12
+ libxrender1 \
13
+ libxxf86vm1 \
14
+ libxfixes3 \
15
+ libxi6 \
16
+ libxkbcommon0 \
17
+ libgomp1 \
18
+ libsm6 \
19
+ libgl1 \
20
+ git
21
+
22
+ RUN pip3 install --no-cache-dir \
23
+ numpy \
24
+ trimesh \
25
+ Pillow \
26
+ gradio==4.40.0 \
27
+ bpy \
28
+ opencv-python-headless
29
+
30
+ RUN pip3 install \
31
+ torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
32
+
33
+ RUN pip3 install git+https://github.com/facebookresearch/segment-anything.git
34
+
35
+ # Set up a new user named "user" with user ID 1000
36
+ RUN useradd -m -u 1000 user
37
+ # Switch to the "user" user
38
+ USER user
39
+ # Set home to the user's home directory
40
+ ENV HOME=/home/user \
41
+ PATH=/home/user/.local/bin:$PATH \
42
+ PYTHONPATH=$HOME/app \
43
+ PYTHONUNBUFFERED=1 \
44
+ SYSTEM=spaces
45
+ # Set the working directory to the user's home directory
46
+ WORKDIR $HOME/app
47
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
48
+ COPY --chown=user . $HOME/app
49
+
50
+ RUN pip3 install gradio_model3dcolor-0.0.1-py3-none-any.whl
51
+ RUN pip3 install gradio_model3dnormal-0.0.1-py3-none-any.whl
52
+
53
+ RUN mkdir ./checkpoints/ && curl https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth -o ./checkpoints/sam_vit_h_4b8939.pth
54
+
55
+ CMD ["python3", "gradio_demo.py"]
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
- title: MeshFormer
3
- emoji: 📈
4
  colorFrom: pink
5
  colorTo: gray
6
  sdk: docker
 
1
  ---
2
+ title: MeshFormer Dev
3
+ emoji: 🏢
4
  colorFrom: pink
5
  colorTo: gray
6
  sdk: docker
demo_examples/01.png ADDED

Git LFS Details

  • SHA256: 4e17b300fd9700fab365cab312f5c6383265fa96c423fe2920a17cbbce1ca5b2
  • Pointer size: 130 Bytes
  • Size of remote file: 73.7 kB
demo_examples/03.png ADDED

Git LFS Details

  • SHA256: 85568b0b61217649faa5f49009be26ede5fb25ac7a906fa1a9672ece35cb7ce9
  • Pointer size: 130 Bytes
  • Size of remote file: 81.4 kB
demo_examples/04.png ADDED

Git LFS Details

  • SHA256: 1a72c4dd1e9cc9a82b4a7a546f919f0f6ec4fc135103ba0e5d2ac33abd822b39
  • Pointer size: 130 Bytes
  • Size of remote file: 81.8 kB
demo_examples/05.png ADDED

Git LFS Details

  • SHA256: 2e57f6e4e76cc85fadbd6965aeca8e875217c204bf3f68043a6b362a8773450a
  • Pointer size: 130 Bytes
  • Size of remote file: 79.3 kB
demo_examples/07.png ADDED

Git LFS Details

  • SHA256: 9f383df1d66e40b51eb4dfcccfe69498677552c088d4827a7c64ef6dbca5f07f
  • Pointer size: 130 Bytes
  • Size of remote file: 43.6 kB
demo_examples/09.png ADDED

Git LFS Details

  • SHA256: 0fc0ce5e5614214458f038e7c822ec188188c32e4596c3bbb170d42331d2174d
  • Pointer size: 131 Bytes
  • Size of remote file: 196 kB
demo_examples/12.png ADDED

Git LFS Details

  • SHA256: 883cbadd6f01de6d1a4d3e667441b0bfa30fb91f754e5b2bebf42d2cc513d9d3
  • Pointer size: 130 Bytes
  • Size of remote file: 51.6 kB
demo_examples/14.png ADDED

Git LFS Details

  • SHA256: 65189f337ef48800a8c16589a81c78ba21a1b6c48a6549333e291a4b4ad25c12
  • Pointer size: 131 Bytes
  • Size of remote file: 106 kB
demo_examples/17.jpg ADDED

Git LFS Details

  • SHA256: 1be16df5ef2104c48b1780cffcb0ad1e3c84f02e7dfb62989c90b942e6119f0e
  • Pointer size: 130 Bytes
  • Size of remote file: 57.3 kB
demo_examples/18.jpg ADDED

Git LFS Details

  • SHA256: 9e24490a9d7374cca2c403266f4068238a0af26a923b62b8b7ea0669a1697cf5
  • Pointer size: 130 Bytes
  • Size of remote file: 58.1 kB
demo_examples/19.jpg ADDED

Git LFS Details

  • SHA256: 9a3ba96921dad9ff96676904f7d1514a8fbbea8fbaf147cb219bd92d9766f1ec
  • Pointer size: 130 Bytes
  • Size of remote file: 78.2 kB
demo_examples/21.png ADDED

Git LFS Details

  • SHA256: ef94c6494d6bd9244a4903c7bf18a3770eea57c66b2a53e5c6a1cbcb99ab11eb
  • Pointer size: 130 Bytes
  • Size of remote file: 35 kB
demo_examples/22.png ADDED

Git LFS Details

  • SHA256: b1f5488931814df7776ecc9ff676e3f95ea6270fe202572e8d7568344024bec5
  • Pointer size: 130 Bytes
  • Size of remote file: 47 kB
demo_examples/23.png ADDED

Git LFS Details

  • SHA256: 340592ce713f1b552a1424d4c3a871825b8d7ac4289eb1ed10644cecb9fba1f6
  • Pointer size: 130 Bytes
  • Size of remote file: 66.7 kB
demo_examples/24.png ADDED

Git LFS Details

  • SHA256: 4ccd19157bc794f27bfe69802c824cfa51999b0a6add3d23bc91cd608e0717f7
  • Pointer size: 131 Bytes
  • Size of remote file: 104 kB
demo_examples/25.png ADDED

Git LFS Details

  • SHA256: bff2100e7b26caa71e54c9251991ca388e006d978ce22e8ebcbcc301b01a3aac
  • Pointer size: 130 Bytes
  • Size of remote file: 51.8 kB
demo_examples/26.png ADDED

Git LFS Details

  • SHA256: 5b5031352b0891534bc09094cd04251de3c1767c70b6b622914c64bfcda80b4f
  • Pointer size: 130 Bytes
  • Size of remote file: 51 kB
demo_examples/27.png ADDED

Git LFS Details

  • SHA256: df923c2c8f20361df123f2afb25254d71d5825b18842a86e40ab5559617cb70a
  • Pointer size: 130 Bytes
  • Size of remote file: 77 kB
demo_examples/28.png ADDED

Git LFS Details

  • SHA256: 1d2d8af59b2f2b4ca0e6546435181b4869a24b0a8394bba52b51e2f1b5a73dc8
  • Pointer size: 130 Bytes
  • Size of remote file: 63 kB
demo_examples/29.png ADDED

Git LFS Details

  • SHA256: 1746dbdf3dff3bfd13e201d5ab5ea30f5404057000bc658222cba0fe1d12b946
  • Pointer size: 130 Bytes
  • Size of remote file: 49.3 kB
demo_examples/30.png ADDED

Git LFS Details

  • SHA256: 4920b94fe72bc494c3404df3c8617ea7b837f29cfddbde73e65d901f1abd80a3
  • Pointer size: 131 Bytes
  • Size of remote file: 349 kB
demo_examples/31.png ADDED

Git LFS Details

  • SHA256: a2c1cadc847ee50709c175b27fa716ccff645ca3f1844bfc3ddccd213cbefb56
  • Pointer size: 130 Bytes
  • Size of remote file: 48.3 kB
demo_examples/32.png ADDED

Git LFS Details

  • SHA256: a551e8bcfdc1542c92fae1236fa3428bea3998f7187e772368786cff8297aa29
  • Pointer size: 130 Bytes
  • Size of remote file: 75.2 kB
demo_examples/33.png ADDED

Git LFS Details

  • SHA256: 4cf620024f77d04115d5cff2793d5ba5de92d7491bc9b041cd4da3f25a597abb
  • Pointer size: 132 Bytes
  • Size of remote file: 2.15 MB
demo_examples/35.png ADDED

Git LFS Details

  • SHA256: 5b6812a04735cb977ff7ed20ceb265ec0a0046c7273e629830348af4b38df9ec
  • Pointer size: 132 Bytes
  • Size of remote file: 1.6 MB
demo_examples/cup.png ADDED

Git LFS Details

  • SHA256: be790add8ea7690abba3f464d18f103a459cdb1a0bd4346cf9040edb59e3c151
  • Pointer size: 131 Bytes
  • Size of remote file: 567 kB
demo_examples/teapot.png ADDED

Git LFS Details

  • SHA256: 46c51d39185186764b0374f3716c18dc67518e26a19fe01fb381c48f60102d60
  • Pointer size: 131 Bytes
  • Size of remote file: 349 kB
gradio_demo.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import os
4
+ import json
5
+ import subprocess
6
+ from PIL import Image
7
+ from functools import partial
8
+ from datetime import datetime
9
+ from sam_inference import get_sam_predictor, sam_seg
10
+ from utils import blend_seg, blend_seg_pure
11
+ import cv2
12
+ import uuid
13
+ import torch
14
+ import trimesh
15
+ from huggingface_hub import snapshot_download
16
+
17
+ from gradio_model3dcolor import Model3DColor
18
+ from gradio_model3dnormal import Model3DNormal
19
+
20
+ code_dir = snapshot_download("sudo-ai/MeshFormer-API", token=os.environ['HF_TOKEN'])
21
+
22
+ with open(f'{code_dir}/api.json', 'r') as file:
23
+ api_dict = json.load(file)
24
+ SEG_CMD = api_dict["SEG_CMD"]
25
+ MESH_CMD = api_dict["MESH_CMD"]
26
+
27
+ STYLE = """
28
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
29
+ """
30
+ # info (info-circle-fill), cursor (hand-index-thumb), wait (hourglass-split), done (check-circle)
31
+ ICONS = {
32
+ "info": """<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-info-circle-fill flex-shrink-0 me-2" viewBox="0 0 16 16">
33
+ <path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
34
+ </svg>""",
35
+ "cursor": """<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hand-index-thumb-fill flex-shrink-0 me-2" viewBox="0 0 16 16">
36
+ <path d="M8.5 1.75v2.716l.047-.002c.312-.012.742-.016 1.051.046.28.056.543.18.738.288.273.152.456.385.56.642l.132-.012c.312-.024.794-.038 1.158.108.37.148.689.487.88.716.075.09.141.175.195.248h.582a2 2 0 0 1 1.99 2.199l-.272 2.715a3.5 3.5 0 0 1-.444 1.389l-1.395 2.441A1.5 1.5 0 0 1 12.42 16H6.118a1.5 1.5 0 0 1-1.342-.83l-1.215-2.43L1.07 8.589a1.517 1.517 0 0 1 2.373-1.852L5 8.293V1.75a1.75 1.75 0 0 1 3.5 0z"/>
37
+ </svg>""",
38
+ "wait": """<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-hourglass-split flex-shrink-0 me-2" viewBox="0 0 16 16">
39
+ <path d="M2.5 15a.5.5 0 1 1 0-1h1v-1a4.5 4.5 0 0 1 2.557-4.06c.29-.139.443-.377.443-.59v-.7c0-.213-.154-.451-.443-.59A4.5 4.5 0 0 1 3.5 3V2h-1a.5.5 0 0 1 0-1h11a.5.5 0 0 1 0 1h-1v1a4.5 4.5 0 0 1-2.557 4.06c-.29.139-.443.377-.443.59v.7c0 .213.154.451.443.59A4.5 4.5 0 0 1 12.5 13v1h1a.5.5 0 0 1 0 1h-11zm2-13v1c0 .537.12 1.045.337 1.5h6.326c.216-.455.337-.963.337-1.5V2h-7zm3 6.35c0 .701-.478 1.236-1.011 1.492A3.5 3.5 0 0 0 4.5 13s.866-1.299 3-1.48V8.35zm1 0v3.17c2.134.181 3 1.48 3 1.48a3.5 3.5 0 0 0-1.989-3.158C8.978 9.586 8.5 9.052 8.5 8.351z"/>
40
+ </svg>""",
41
+ "done": """<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check-circle-fill flex-shrink-0 me-2" viewBox="0 0 16 16">
42
+ <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
43
+ </svg>""",
44
+ }
45
+ icons2alert = {
46
+ "info": "primary", # blue
47
+ "cursor": "info", # light blue
48
+ "wait": "secondary", # gray
49
+ "done": "success", # green
50
+ }
51
+
52
+
53
+ def message(text, icon_type="info"):
54
+ return f"""{STYLE} <div class="alert alert-{icons2alert[icon_type]} d-flex align-items-center" role="alert"> {ICONS[icon_type]}
55
+ <div>
56
+ {text}
57
+ </div>
58
+ </div>"""
59
+
60
+
61
+ def preprocess(tmp_dir, input_img, idx=None):
62
+ if idx is not None:
63
+ print("image idx:", int(idx))
64
+ input_img = Image.open(input_img[int(idx)]["name"])
65
+ input_img.save(f"{tmp_dir}/input.png")
66
+ # print(SEG_CMD.format(tmp_dir=tmp_dir))
67
+ os.system(SEG_CMD.format(tmp_dir=tmp_dir))
68
+ processed_img = Image.open(f"{tmp_dir}/seg.png")
69
+ return processed_img.resize((320, 320), Image.Resampling.LANCZOS)
70
+
71
+
72
+ def ply_to_glb(ply_path):
73
+ result = subprocess.run(
74
+ ["python", "ply2glb.py", "--", ply_path],
75
+ capture_output=True,
76
+ text=True,
77
+ )
78
+
79
+ print("Output of blender script:")
80
+ print(result.stdout)
81
+
82
+ glb_path = ply_path.replace(".ply", ".glb")
83
+ return glb_path
84
+
85
+
86
+ def mesh_gen(tmp_dir, simplify, num_inference_steps):
87
+ # print(MESH_CMD.format(tmp_dir=tmp_dir, num_inference_steps=num_inference_steps))
88
+ os.system(MESH_CMD.format(tmp_dir=tmp_dir, num_inference_steps=num_inference_steps))
89
+
90
+ mesh = trimesh.load_mesh(f"{tmp_dir}/mesh.ply")
91
+ vertex_normals = mesh.vertex_normals
92
+ colors = (-vertex_normals + 1) / 2.0
93
+ colors = (colors * 255).astype(np.uint8) # Convert to 8-bit color
94
+ mesh.visual.vertex_colors = colors[..., [2, 0, 1]] # RGB -> BRG
95
+ mesh.export(f"{tmp_dir}/mesh_normal.ply", file_type="ply")
96
+
97
+ color_path = ply_to_glb(f"{tmp_dir}/mesh.ply")
98
+ normal_path = ply_to_glb(f"{tmp_dir}/mesh_normal.ply")
99
+
100
+ return color_path, normal_path
101
+
102
+
103
+ def create_tmp_dir():
104
+ tmp_dir = (
105
+ "demo_exp/"
106
+ + datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
107
+ + "_"
108
+ + str(uuid.uuid4())[:4]
109
+ )
110
+ os.makedirs(tmp_dir, exist_ok=True)
111
+ print("create tmp_exp_dir", tmp_dir)
112
+ return tmp_dir
113
+
114
+
115
+ def vis_seg(checkbox):
116
+ if checkbox:
117
+ print("Show manual seg windows")
118
+ return (
119
+ [gr.Image(value=None, visible=True)] * 2
120
+ + [gr.Radio(visible=True)]
121
+ + [[], gr.Checkbox(visible=True)]
122
+ )
123
+ else:
124
+ print("Clear manual seg")
125
+ return (
126
+ [gr.Image(visible=False)] * 2
127
+ + [gr.Radio(visible=False)]
128
+ + [[], gr.Checkbox(visible=False)]
129
+ )
130
+
131
+
132
+ def calc_feat(checkbox, predictor, input_image, idx=None):
133
+ if checkbox:
134
+ if idx is not None:
135
+ print("image idx:", int(idx))
136
+ input_image = Image.open(input_image[int(idx)]["name"])
137
+ input_image.thumbnail([512, 512], Image.Resampling.LANCZOS)
138
+ w, h = input_image.size
139
+ print("image size:", w, h)
140
+ side_len = np.max((w, h))
141
+ seg_in = Image.new(input_image.mode, (side_len, side_len), (255, 255, 255))
142
+ seg_in.paste(
143
+ input_image, (np.max((0, (h - w) // 2)), np.max((0, (w - h) // 2)))
144
+ )
145
+ print("Calculating image SAM feature...")
146
+ predictor.set_image(np.array(seg_in.convert("RGB")))
147
+ torch.cuda.empty_cache()
148
+ return gr.Image(value=seg_in, visible=True)
149
+ else:
150
+ print("Quit manual seg")
151
+ raise ValueError("Quit manual seg")
152
+
153
+
154
+ def manual_seg(
155
+ predictor,
156
+ seg_in,
157
+ selected_points,
158
+ fg_bg_radio,
159
+ tmp_dir,
160
+ seg_mask_opt,
161
+ evt: gr.SelectData,
162
+ ):
163
+ print("Start segmentation")
164
+ selected_points.append(
165
+ {"coord": evt.index, "add_del": fg_bg_radio == "+ (add mask)"}
166
+ )
167
+ input_points = np.array([point["coord"] for point in selected_points])
168
+ input_labels = np.array([point["add_del"] for point in selected_points])
169
+ out_image = sam_seg(
170
+ predictor, np.array(seg_in.convert("RGB")), input_points, input_labels
171
+ )
172
+
173
+ # seg_in.save(f"{tmp_dir}/in.png")
174
+ # out_image.save(f"{tmp_dir}/out.png")
175
+ if seg_mask_opt:
176
+ segmentation = blend_seg_pure(
177
+ seg_in.convert("RGB"), out_image, input_points, input_labels
178
+ )
179
+ else:
180
+ segmentation = blend_seg(
181
+ seg_in.convert("RGB"), out_image, input_points, input_labels
182
+ )
183
+
184
+ # recenter and rescale
185
+ image_arr = np.array(out_image)
186
+ ret, mask = cv2.threshold(
187
+ np.array(out_image.split()[-1]), 0, 255, cv2.THRESH_BINARY
188
+ )
189
+ x, y, w, h = cv2.boundingRect(mask)
190
+ max_size = max(w, h)
191
+ ratio = 0.75
192
+ side_len = int(max_size / ratio)
193
+ padded_image = np.zeros((side_len, side_len, 4), dtype=np.uint8)
194
+ center = side_len // 2
195
+ padded_image[
196
+ center - h // 2 : center - h // 2 + h, center - w // 2 : center - w // 2 + w
197
+ ] = image_arr[y : y + h, x : x + w]
198
+ rgba = Image.fromarray(padded_image)
199
+ rgba.save(f"{tmp_dir}/seg.png")
200
+ torch.cuda.empty_cache()
201
+
202
+ return segmentation.resize((380, 380), Image.Resampling.LANCZOS), rgba.resize(
203
+ (320, 320), Image.Resampling.LANCZOS
204
+ )
205
+
206
+
207
+ custom_theme = gr.themes.Soft(primary_hue="blue").set(
208
+ button_secondary_background_fill="*neutral_100",
209
+ button_secondary_background_fill_hover="*neutral_200",
210
+ )
211
+
212
+ with gr.Blocks(title="MeshFormer Demo", css="style.css", theme=custom_theme) as demo:
213
+ with gr.Row():
214
+ gr.Markdown(
215
+ "# MeshFormer: High-Quality Mesh Generation with 3D-Guided Reconstruction Model"
216
+ )
217
+ with gr.Row():
218
+ gr.Markdown(
219
+ "[Project Page](https://meshformer3d.github.io/) | [arXiv](https://arxiv.org/abs/TBD)"
220
+ )
221
+ with gr.Row():
222
+ gr.Markdown(
223
+ """
224
+ <div>
225
+ <b><em>Check out <a href="https://www.sudo.ai/3dgen">Hillbot (sudoAI)</a> for more details and advanced features.</em></b>
226
+ </div>
227
+ """
228
+ )
229
+ with gr.Row():
230
+ guide_text_i2m = gr.HTML(message("Please input an image!"), visible=True)
231
+
232
+ tmp_dir_img = gr.State("./demo_exp/placeholder")
233
+ tmp_dir_txt = gr.State("./demo_exp/placeholder")
234
+ tmp_dir_3t3 = gr.State("./demo_exp/placeholder")
235
+
236
+ example_folder = os.path.join(os.path.dirname(__file__), "demo_examples")
237
+ example_fns = os.listdir(example_folder)
238
+ example_fns.sort()
239
+ img_examples = [
240
+ os.path.join(example_folder, x) for x in example_fns
241
+ ] # if x.endswith('.png') or x.endswith('.')
242
+
243
+ with gr.Row(variant="panel"):
244
+ with gr.Row():
245
+ with gr.Column(scale=8):
246
+ input_image = gr.Image(
247
+ type="pil",
248
+ image_mode="RGBA",
249
+ height=320,
250
+ label="Input Image",
251
+ interactive=True,
252
+ )
253
+ gr.Examples(
254
+ examples=img_examples,
255
+ inputs=[input_image],
256
+ outputs=[input_image],
257
+ cache_examples=False,
258
+ label="Image Examples (Click one of the images below to start)",
259
+ examples_per_page=27,
260
+ )
261
+ with gr.Accordion("Options", open=False):
262
+ img_simplify = gr.Checkbox(
263
+ False, label="simplify the generated mesh", visible=False
264
+ )
265
+ n_steps_img = gr.Slider(
266
+ value=28,
267
+ minimum=15,
268
+ maximum=100,
269
+ step=1,
270
+ label="number of inference steps",
271
+ )
272
+ # manual segmentation
273
+ checkbox_manual_seg = gr.Checkbox(False, label="manual segmentation")
274
+ with gr.Row():
275
+ with gr.Column(scale=1):
276
+ seg_in = gr.Image(
277
+ type="pil",
278
+ image_mode="RGBA",
279
+ label="Click to segment",
280
+ visible=False,
281
+ show_download_button=False,
282
+ height=380,
283
+ )
284
+ with gr.Column(scale=1):
285
+ seg_out = gr.Image(
286
+ type="pil",
287
+ image_mode="RGBA",
288
+ label="Segmentation",
289
+ interactive=False,
290
+ visible=False,
291
+ show_download_button=False,
292
+ height=380,
293
+ elem_id="disp_image",
294
+ )
295
+ fg_bg_radio = gr.Radio(
296
+ ["+ (add mask)", "- (remove area)"],
297
+ value="+ (add mask)",
298
+ info="Select foreground (+) or background (-) point",
299
+ label="Point label",
300
+ visible=False,
301
+ interactive=True,
302
+ )
303
+ seg_mask_opt = gr.Checkbox(
304
+ True,
305
+ label="show foreground mask in manual segmentation",
306
+ visible=False,
307
+ )
308
+ # run
309
+ img_run_btn = gr.Button(
310
+ "Generate", variant="primary", interactive=False
311
+ )
312
+ with gr.Column(scale=6):
313
+ processed_image = gr.Image(
314
+ type="pil",
315
+ label="Processed Image",
316
+ interactive=False,
317
+ height=320,
318
+ image_mode="RGBA",
319
+ elem_id="disp_image",
320
+ )
321
+ # with gr.Row():
322
+ # mesh_output = gr.Model3D(label="Generated Mesh", elem_id="model-3d-out")
323
+ mesh_output_normal = Model3DNormal(
324
+ label="Generated Mesh (normal)",
325
+ elem_id="mesh-normal-out",
326
+ height=400,
327
+ )
328
+ mesh_output = Model3DColor(
329
+ label="Generated Mesh (color)",
330
+ elem_id="mesh-out",
331
+ height=400,
332
+ )
333
+
334
+ predictor = gr.State(value=get_sam_predictor())
335
+ selected_points = gr.State(value=[])
336
+ selected_points_t2i = gr.State(value=[])
337
+
338
+ disable_checkbox = lambda: gr.Checkbox(value=False)
339
+ disable_button = lambda: gr.Button(interactive=False)
340
+ enable_button = lambda: gr.Button(interactive=True)
341
+ update_guide = lambda GUIDE_TEXT, icon_type="info": gr.HTML(
342
+ value=message(GUIDE_TEXT, icon_type)
343
+ )
344
+ update_md = lambda GUIDE_TEXT: gr.Markdown(value=GUIDE_TEXT)
345
+
346
+ def is_img_clear(input_image):
347
+ if not input_image:
348
+ raise ValueError("Input image cleared.")
349
+
350
+ checkbox_manual_seg.change(
351
+ vis_seg,
352
+ inputs=[checkbox_manual_seg],
353
+ outputs=[seg_in, seg_out, fg_bg_radio, selected_points, seg_mask_opt],
354
+ queue=False,
355
+ ).success(
356
+ calc_feat,
357
+ inputs=[checkbox_manual_seg, predictor, input_image],
358
+ outputs=[seg_in],
359
+ ).success(
360
+ fn=create_tmp_dir, outputs=[tmp_dir_img], queue=False
361
+ )
362
+
363
+ seg_in.select(
364
+ manual_seg,
365
+ [predictor, seg_in, selected_points, fg_bg_radio, tmp_dir_img, seg_mask_opt],
366
+ [seg_out, processed_image],
367
+ )
368
+
369
+ input_image.change(disable_button, outputs=img_run_btn, queue=False).success(
370
+ disable_checkbox, outputs=checkbox_manual_seg, queue=False
371
+ ).success(fn=is_img_clear, inputs=input_image, queue=False).success(
372
+ fn=create_tmp_dir, outputs=tmp_dir_img, queue=False
373
+ ).success(
374
+ fn=partial(update_guide, "Preprocessing the image!", "wait"),
375
+ outputs=[guide_text_i2m],
376
+ queue=False,
377
+ ).success(
378
+ fn=preprocess,
379
+ inputs=[tmp_dir_img, input_image],
380
+ outputs=[processed_image],
381
+ queue=True,
382
+ ).success(
383
+ fn=partial(
384
+ update_guide,
385
+ "Click <b>Generate</b> to generate mesh! If the input image was not segmented accurately, please adjust it using <b>manual segmentation</b>.",
386
+ "cursor",
387
+ ),
388
+ outputs=[guide_text_i2m],
389
+ queue=False,
390
+ ).success(
391
+ enable_button, outputs=img_run_btn, queue=False
392
+ )
393
+
394
+ img_run_btn.click(
395
+ fn=partial(update_guide, "Generating the mesh!", "wait"),
396
+ outputs=[guide_text_i2m],
397
+ queue=False,
398
+ ).success(
399
+ fn=mesh_gen,
400
+ inputs=[tmp_dir_img, img_simplify, n_steps_img],
401
+ outputs=[mesh_output, mesh_output_normal],
402
+ queue=True,
403
+ ).success(
404
+ fn=partial(
405
+ update_guide,
406
+ "Successfully generated the mesh. (It might take a few seconds to load the mesh)",
407
+ "done",
408
+ ),
409
+ outputs=[guide_text_i2m],
410
+ queue=False,
411
+ )
412
+
413
+ demo.queue().launch(
414
+ debug=True, share=False, inline=False, show_api=False, server_name="0.0.0.0"
415
+ )
gradio_model3dcolor-0.0.1-py3-none-any.whl ADDED
Binary file (995 kB). View file
 
gradio_model3dnormal-0.0.1-py3-none-any.whl ADDED
Binary file (995 kB). View file
 
ply2glb.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import bpy
2
+ import sys
3
+
4
+
5
+ # Clear the scene
6
+ bpy.ops.object.select_all(action="SELECT")
7
+ bpy.ops.object.delete(use_global=False)
8
+
9
+ # Load mesh.ply
10
+ ply_path = sys.argv[-1]
11
+ bpy.ops.wm.ply_import(filepath=ply_path)
12
+
13
+ # Create a new material
14
+ material = bpy.data.materials.new(name="New_Material")
15
+ material.use_nodes = True
16
+
17
+ # Assign the material to the object
18
+ obj = bpy.context.selected_objects[0]
19
+ if obj.data.materials:
20
+ obj.data.materials[0] = material
21
+ else:
22
+ obj.data.materials.append(material)
23
+
24
+ # Add a Vertex Color node and link it
25
+ nodes = material.node_tree.nodes
26
+ links = material.node_tree.links
27
+
28
+ # Clear default nodes
29
+ for node in nodes:
30
+ nodes.remove(node)
31
+
32
+ # Create nodes
33
+ output_node = nodes.new(type="ShaderNodeOutputMaterial")
34
+ vertex_color_node = nodes.new(type="ShaderNodeVertexColor")
35
+ principled_bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
36
+
37
+ # Set the vertex color layer name
38
+ vertex_color_node.layer_name = "Col"
39
+
40
+ # Arrange nodes
41
+ vertex_color_node.location = (-300, 0)
42
+ principled_bsdf.location = (0, 0)
43
+ output_node.location = (300, 0)
44
+
45
+ # Link nodes
46
+ links.new(vertex_color_node.outputs["Color"], principled_bsdf.inputs["Base Color"])
47
+ links.new(principled_bsdf.outputs["BSDF"], output_node.inputs["Surface"])
48
+
49
+ # Rotate the object
50
+ bpy.context.object.rotation_euler[2] = 1.57079
51
+
52
+ # Export the scene to a glTF file
53
+ glb_path = ply_path.replace(".ply", ".glb")
54
+ bpy.ops.export_scene.gltf(filepath=glb_path, export_format="GLB")
55
+
56
+ # Free up memory
57
+ bpy.ops.wm.read_factory_settings(use_empty=True)
sam_inference.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from segment_anything import SamPredictor, sam_model_registry
4
+ from PIL import Image
5
+
6
+ models = {
7
+ 'vit_b': './checkpoints/sam_vit_b_01ec64.pth',
8
+ 'vit_l': './checkpoints/sam_vit_l_0b3195.pth',
9
+ 'vit_h': './checkpoints/sam_vit_h_4b8939.pth'
10
+ }
11
+
12
+
13
+ def get_sam_predictor(model_type='vit_h', device=None, image=None):
14
+ if device is None and torch.cuda.is_available():
15
+ device = 'cuda'
16
+ elif device is None:
17
+ device = 'cpu'
18
+ # sam model
19
+ sam = sam_model_registry[model_type](checkpoint=models[model_type])
20
+ sam = sam.to(device)
21
+
22
+ predictor = SamPredictor(sam)
23
+ if image is not None:
24
+ predictor.set_image(image)
25
+ return predictor
26
+
27
+ def sam_seg(predictor, input_img, input_points, input_labels):
28
+ masks, scores, logits = predictor.predict(
29
+ point_coords=input_points,
30
+ point_labels=input_labels,
31
+ multimask_output=True,
32
+ )
33
+
34
+ opt_idx = np.argmax(scores)
35
+ mask = masks[opt_idx]
36
+ out_image = np.zeros((input_img.shape[0], input_img.shape[1], 4), dtype=np.uint8)
37
+ out_image[:, :, :3] = input_img
38
+ out_image[:, :, 3] = mask.astype(np.uint8) * 255
39
+ torch.cuda.empty_cache()
40
+ return Image.fromarray(out_image, mode='RGBA')
style.css ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #model-3d-out {
2
+ height: 400px;
3
+ }
4
+ #disp_image {
5
+ text-align: center; /* Horizontally center the content */
6
+ }
7
+
8
+ .centered {
9
+ text-align: center; /* Horizontally center the content */
10
+ }
11
+ .centered img {
12
+ display: block; /* Make the image a block element */
13
+ margin: 0 auto; /* Center the block element (the image) horizontally */
14
+ height: 100px;
15
+ }
16
+
17
+ #prompt-container{
18
+ gap: 0;
19
+ }
20
+ #prompt-container .form{
21
+ border-top-right-radius: 0;
22
+ border-bottom-right-radius: 0;
23
+ }
24
+
25
+ #gen-button{
26
+ border-top-left-radius:0;
27
+ border-bottom-left-radius:0;
28
+ }
29
+
30
+ .tab_at_top button.selected{
31
+ font-size: 24px !important;
32
+ }
utils.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+
5
+ # marker choices
6
+ COLORS = [(246, 195, 203), (112, 221, 208)]
7
+ MARKERS = [1, 5]
8
+
9
+ def blend_seg(input_image, segmented_image, dot_locations, dot_labels, contour_color=(63, 126, 174)):
10
+ input_image = np.array(input_image)
11
+ segmented_image = np.array(segmented_image)
12
+
13
+ # Create a mask for the foreground (non-transparent) pixels
14
+ foreground_mask = segmented_image[:, :, 3] > 0
15
+
16
+ # Create a mask for the background (transparent) pixels
17
+ background_mask = ~foreground_mask
18
+
19
+ # Darken the background pixels
20
+ darkened_background = input_image.copy()
21
+ darkened_background[background_mask] = darkened_background[background_mask] * 0.52 # Adjust the multiplier as needed to control darkness
22
+
23
+ # Create an empty mask for the boundary
24
+ boundary_mask = np.zeros_like(segmented_image[:, :, 3], dtype=np.uint8)
25
+ solid_boundary_mask = np.zeros_like(segmented_image[:, :, 3], dtype=np.uint8)
26
+
27
+ # Find the contour of the segmented region
28
+ contours, _ = cv2.findContours(
29
+ segmented_image[:, :, 3], cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE
30
+ )
31
+
32
+ # Draw the boundary on the boundary mask
33
+ cv2.drawContours(boundary_mask, contours, -1, (255), thickness=6)
34
+ cv2.drawContours(solid_boundary_mask, contours, -1, (255), thickness=2)
35
+
36
+ blur_mask = cv2.GaussianBlur(boundary_mask, (0, 0), sigmaX=4)
37
+
38
+ # Create a mask for the contour region
39
+ contour_region_mask = (blur_mask > 0)
40
+
41
+ # Blend the contour color with the existing pixel colors
42
+ result_image = darkened_background.copy()
43
+ mask_weight = 0.9 * blur_mask[contour_region_mask, None]/255
44
+ result_image[contour_region_mask] = (
45
+ darkened_background[contour_region_mask] * (1-mask_weight) + np.array(contour_color) * mask_weight
46
+ ).astype(np.uint8)
47
+
48
+ # Overlay the contour on the result image without blending
49
+ result_image[solid_boundary_mask > 0] = contour_color # Set contour pixels to blue
50
+
51
+ # Draw dots at the specified locations
52
+ dot_radius = 6
53
+ for location, label in zip(dot_locations, dot_labels):
54
+ if label:
55
+ cv2.circle(result_image, location, dot_radius, COLORS[label], -1)
56
+ else:
57
+ cv2.drawMarker(result_image, location, COLORS[label], markerType=MARKERS[label],
58
+ markerSize=6, thickness=3)
59
+
60
+ return Image.fromarray(result_image)
61
+
62
+
63
+ def blend_seg_pure(input_image, segmented_image, dot_locations, dot_labels):
64
+ input_image = np.array(input_image)
65
+ segmented_image = np.array(segmented_image)
66
+
67
+ # Create a mask for the foreground (non-transparent) pixels
68
+ foreground_mask = segmented_image[:, :, 3] > 0
69
+
70
+ # Blend the foreground
71
+ red_foreground = input_image.copy()
72
+ blend_weight = 0.8
73
+ red_foreground[foreground_mask] = red_foreground[foreground_mask] *(1-blend_weight) + np.array((255,0,0)) * blend_weight
74
+
75
+ result_image = red_foreground
76
+
77
+ # Draw dots at the specified locations
78
+ dot_radius = 6
79
+ for location, label in zip(dot_locations, dot_labels):
80
+ if label:
81
+ cv2.circle(result_image, location, dot_radius, COLORS[label], -1)
82
+ else:
83
+ cv2.drawMarker(result_image, location, COLORS[label], markerType=MARKERS[label],
84
+ markerSize=6, thickness=3)
85
+
86
+ return Image.fromarray(result_image)