Skip to content

[ICCV 2023] Make-It-3D: High-Fidelity 3D Creation from A Single Image with Diffusion Prior

add refine stage

junshutang03dffd7d81e0
diff --git a/README.md b/README.md
index 525d999..37f1773 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,12 @@
<img src="demo/corgi-demo.png" height="170"><img src="demo/corgi.png" width="170"><img src="demo/corgi-rgb.gif" width="170"><img src="demo/corgi-normal.gif" width="170">
</div>
+## Todo
+- [x] Release coarse stage training code
+- [x] Release all training code (coarse + refine stage)
+- [ ] Release the test benchmark for all results in the paper
+- [ ] Release more applications
+
## Installation
Install with pip:
```
@@ -27,6 +33,7 @@ Install with pip:
pip install git+https://github.com/huggingface/diffusers.git
pip install git+https://github.com/huggingface/huggingface_hub.git
pip install git+https://github.com/facebookresearch/pytorch3d.git
+ pip install git+https://github.com/S-aiueo32/contextual_loss_pytorch.git
```
Other dependencies:
```
@@ -40,11 +47,11 @@ Training requirements
mkdir dpt_weights
```
Download the pretrained model [dpt_hybrid](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt), and put it in `dpt_weights`.
-- [BLIP2](https://arxiv.org/abs/2301.12597). We use BLIP2 to generate a caption. You can also modify the conditioned text using `--text "{TEXT}"`.
+- [BLIP2](https://arxiv.org/abs/2301.12597). We use BLIP2 to generate a caption. You can also modify the conditioned text using `--text "{TEXT}"` which will greatly reduce time.
- [Stable Diffusion](https://huggingface.co/models?other=stable-diffusion). We use diffusion prior from a pretrained 2D Stable Diffusion 2.0 model. To start with, you may need a huggingface [token](https://huggingface.co/settings/tokens) to access the model, or use `huggingface-cli login` command.
-## Coarse Stage Training
-We use progressive training strategy to generate a full 360° 3D geometry. Run the command and modify the workspace name `NAME` and the path of the reference image `IMGPATH`.
-We first optimize the scene under frontal camera views.
+## Training
+### Coarse stage
+We use progressive training strategy to generate a full 360° 3D geometry. Run the command and modify the workspace name `NAME` and the path of the reference image `IMGPATH`. We first optimize the scene under frontal camera views.
```
python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 135 225 --iters 2000
```
@@ -52,18 +59,24 @@ Then we spread the camera view samples to full 360°. If you need a prompt condi
```
python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 0 360 --albedo_iters 3000 --iters 5000 --final
```
-## Refine Stage Training
+### Refine stage
-Coming soon...
+After the coarse stage training, now you can easily use the command `--refine` for refine stage training. We optimize the scene under frontal camera views.
+```
+ python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 135 225 --refine
+```
+You can modify the value of training iterations using the command `--refine_iters`.
+```
+ python main.py --workspace ${NAME} --ref_path "${IMGPATH}" --phi_range 135 225 --refine_iters 3000 --refine
+```
+**Note:** We additionally use `contextual loss` on the refine stage, we find it helps to sharpen the texture. You may need to install [contextual_loss_pytorch](https://github.com/S-aiueo32/contextual_loss_pytorch) before training.
+```
+ pip install git+https://github.com/S-aiueo32/contextual_loss_pytorch.git
+```
## Important Note
Hallucinating 3D geometry and generating novel views from a single image of general genre is a challenging task. While our method demonstrates strong capability on creating 3D from most images with a centered single object, it may still encounter difficulties in reconstructing solid geometry on complex cases. **If you encounter any bugs, please feel free to contact us.**
-## Todo
-- [x] Release coarse stage training code
-- [ ] Release the test benchmark for all results in the paper
-- [ ] Release all training code
-- [ ] Release more applications
## Citation
diff --git a/__pycache__/activation.cpython-37.pyc b/__pycache__/activation.cpython-37.pyc
new file mode 100644
index 0000000..9f007ae
Binary files /dev/null and b/__pycache__/activation.cpython-37.pyc differ
diff --git a/__pycache__/encoding.cpython-37.pyc b/__pycache__/encoding.cpython-37.pyc
new file mode 100644
index 0000000..6ba72e5
Binary files /dev/null and b/__pycache__/encoding.cpython-37.pyc differ
diff --git a/__pycache__/optimizer.cpython-37.pyc b/__pycache__/optimizer.cpython-37.pyc
new file mode 100644
index 0000000..4bab172
Binary files /dev/null and b/__pycache__/optimizer.cpython-37.pyc differ
diff --git a/main.py b/main.py
index c953d78..35c5e0a 100644
--- a/main.py
+++ b/main.py
@@ -20,6 +20,7 @@ if __name__ == '__main__':
parser.add_argument('--negative', default='', type=str, help="negative text prompt")
parser.add_argument('--test', action='store_true', help="test mode")
parser.add_argument('--final', action='store_true', help="final train mode")
+ parser.add_argument('--refine', action='store_true', help="refine mode")
parser.add_argument('--save_mesh', action='store_true', help="export an obj mesh with texture")
parser.add_argument('--eval_interval', type=int, default=10, help="evaluate on the valid set every interval epochs")
parser.add_argument('--workspace', type=str, default='workspace')
@@ -34,6 +35,7 @@ if __name__ == '__main__':
### training options
parser.add_argument('--iters', type=int, default=10000, help="training iters")
+ parser.add_argument('--refine_iters', type=int, default=3000, help="training iters")
parser.add_argument('--lr', type=float, default=1e-3, help="max learning rate")
parser.add_argument('--min_lr', type=float, default=1e-4, help="minimal learning rate")
parser.add_argument('--ckpt', type=str, default='latest')
@@ -225,7 +227,7 @@ if __name__ == '__main__':
if opt.save_mesh:
trainer.save_mesh(resolution=256)
-
+
else:
train_loader = NeRFDataset(opt, device=device, type='train', H=opt.h, W=opt.w, size=100).dataloader()
@@ -236,7 +238,14 @@ if __name__ == '__main__':
# also test
if opt.final:
test_loader = NeRFDataset(opt, device=device, type='test', H=opt.H, W=opt.W, size=64).dataloader()
- trainer.test(test_loader, write_video=True)
+ trainer.test(test_loader, write_image=False, write_video=True)
if opt.save_mesh:
trainer.save_mesh(resolution=256)
+
+ if opt.refine:
+ mv_loader = NeRFDataset(opt, device=device, type='gen_mv', H=opt.H, W=opt.W, size=33).dataloader()
+ test_loader = NeRFDataset(opt, device=device, type='test', H=opt.H, W=opt.W, size=64).dataloader()
+ trainer.test(mv_loader, save_path=os.path.join(opt.workspace, 'mvimg'), write_image=True, write_video=False)
+ trainer.refine(os.path.join(opt.workspace, 'mvimg'), opt.refine_iters, test_loader)
+
\ No newline at end of file
diff --git a/nerf/__pycache__/network_tcnn.cpython-37.pyc b/nerf/__pycache__/network_tcnn.cpython-37.pyc
index eb4fa5c..ea60a24 100644
Binary files a/nerf/__pycache__/network_tcnn.cpython-37.pyc and b/nerf/__pycache__/network_tcnn.cpython-37.pyc differ
diff --git a/nerf/__pycache__/provider.cpython-37.pyc b/nerf/__pycache__/provider.cpython-37.pyc
index 9061b27..13c0056 100644
Binary files a/nerf/__pycache__/provider.cpython-37.pyc and b/nerf/__pycache__/provider.cpython-37.pyc differ
diff --git a/nerf/__pycache__/refine_utils.cpython-37.pyc b/nerf/__pycache__/refine_utils.cpython-37.pyc
new file mode 100644
index 0000000..b6c6639
Binary files /dev/null and b/nerf/__pycache__/refine_utils.cpython-37.pyc differ
diff --git a/nerf/__pycache__/renderer.cpython-37.pyc b/nerf/__pycache__/renderer.cpython-37.pyc
index f4fc944..a2efb72 100644
Binary files a/nerf/__pycache__/renderer.cpython-37.pyc and b/nerf/__pycache__/renderer.cpython-37.pyc differ
diff --git a/nerf/__pycache__/sd.cpython-37.pyc b/nerf/__pycache__/sd.cpython-37.pyc
index 5fb8400..b6ea4ff 100644
Binary files a/nerf/__pycache__/sd.cpython-37.pyc and b/nerf/__pycache__/sd.cpython-37.pyc differ
diff --git a/nerf/__pycache__/unet.cpython-37.pyc b/nerf/__pycache__/unet.cpython-37.pyc
index baed916..46a8b55 100644
Binary files a/nerf/__pycache__/unet.cpython-37.pyc and b/nerf/__pycache__/unet.cpython-37.pyc differ
diff --git a/nerf/__pycache__/utils.cpython-37.pyc b/nerf/__pycache__/utils.cpython-37.pyc
index 7bf1434..95e92c8 100644
Binary files a/nerf/__pycache__/utils.cpython-37.pyc and b/nerf/__pycache__/utils.cpython-37.pyc differ
diff --git a/nerf/provider.py b/nerf/provider.py
index ad7c459..cdcfa18 100644
--- a/nerf/provider.py
+++ b/nerf/provider.py
@@ -257,6 +257,7 @@ class NeRFDataset:
self.training = self.type in ['train', 'all']
self.testing = self.type in ['test']
+ self.gen_mv = self.type in ['gen_mv']
self.cx = self.H / 2
self.cy = self.W / 2
@@ -272,20 +273,17 @@ class NeRFDataset:
else:
fov = random.random() * (self.opt.fovy_range[1] - self.opt.fovy_range[0]) + self.opt.fovy_range[0]
- # elif self.testing:
- # theta = [80.0, 90.0, 100.0]
- # length = self.size // 3
- # i = int(index[0] // length)
- # if i % 2 == 0:
- # phi = ((index[0]%length)/(length -1)) * (self.opt.phi_range[1]-self.opt.phi_range[0]) + self.opt.phi_range[0]
- # else:
- # phi = ((index[0]%length)/(length -1)) * (self.opt.phi_range[0]-self.opt.phi_range[1]) + self.opt.phi_range[1]
- # theta = theta[i]
+ elif self.gen_mv:
+ theta = [80.0, 90.0, 100.0]
+ length = self.size // 3
+ i = int(index[0] // length)
+ phi = ((index[0]%length)/(length -1)) * (self.opt.phi_range[0]-self.opt.phi_range[1]) + self.opt.phi_range[1]
+ theta = theta[i]
- # thetas, phis, poses = circle_poses(self.device, radius=1.0, theta=theta, phi=phi)
- # is_front = False
- # is_large = False
- # fov = self.fov
+ thetas, phis, poses = circle_poses(self.device, radius=1.0, theta=theta, phi=phi)
+ is_front = False
+ is_large = False
+ fov = self.fov
else:
phi = (index[0] / self.size) * (self.opt.phi_range[1]-self.opt.phi_range[0]) + self.opt.phi_range[0]
thetas, phis, poses = circle_poses(self.device, radius=1.0, theta=90, phi=phi)
diff --git a/nerf/refine_utils.py b/nerf/refine_utils.py
new file mode 100644
index 0000000..45c4b33
--- /dev/null
+++ b/nerf/refine_utils.py
@@ -0,0 +1,410 @@
+import numpy as np
+import cv2
+import os
+import torch.nn.functional as F
+import imageio
+import torch
+import numpy as np
+from pytorch3d.structures import Pointclouds
+from pytorch3d.renderer import compositing
+from pytorch3d.renderer import AlphaCompositor
+from pytorch3d.renderer.points import rasterize_points
+import cv2
+import tqdm
+import random
+import warnings
+from copy import deepcopy
+
+warnings.filterwarnings('ignore')
+
+def load_depth(file_name):
+ import cv2
+ D = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)
+ if not D is None and len(D.shape) > 2:
+ D = D[:,:,0]
+ return D
+
+def save_obj(file_name, v, tri = []):
+ with open(file_name, 'w') as fid:
+ for i in range(len(v)):
+ fid.write('v %f %f %f\n' % (v[i][0],v[i][1],v[i][2]))
+ for i in range(len(tri)):
+ fid.write(('f'+' %d'*len(tri[i])*'\n') % tuple( \
+ [tri[i][j]+1 for j in range(len(tri[i]))]))
+ return os.path.exists(file_name)
+
+def multidepth2point(allD, alphamask, cam, c2w, npoint=1000000):
+
+ v_list = []
+ for i in range(allD.shape[0]):
+ D = allD[i]
+ x, y = np.meshgrid(np.arange(D.shape[0]), np.arange(D.shape[1]))
+ cam_xyz = np.vstack(( \
+ x.reshape(-1), \
+ y.reshape(-1), \
+ np.ones(len(D.reshape(-1)))))
+
+ v = np.linalg.inv(cam).dot(cam_xyz).T
+ v = v * np.tile(D.reshape((-1,1)), (1,3))
+ v = np.matmul(v,c2w[i, :3,:3].T)+c2w[i, :3, 3:].T
+ v = v[alphamask[i].reshape(-1)==1]
+ v_list.append(v)
+
+ v_list = np.concatenate(v_list)
+ np.random.shuffle(v_list)
+ v_list = v_list[:npoint]
+ # pcd = o3d.geometry.PointCloud()
+ # pcd.points = o3d.utility.Vector3dVector(v_list[:, :3])
+ # o3d.io.write_point_cloud('ori.ply', pcd)
+ return v_list
+
+def multidepth2point_mask(allD, alphamask, allimg, cam, c2w, cano_v, cano_c2w, cano_D, H, W, radius, ppp, outputdir, device, npoint=1000000):
+ image_size = [H, W]
+ K = cam
+ cano_v = torch.tensor(cano_v).to(device).float() # N x 3
+ cano_w2c = np.linalg.inv(cano_c2w)
+ cano_D = torch.Tensor(cano_D).unsqueeze(0).unsqueeze(0)
+ cano_color = torch.ones_like(cano_v)
+ K_tensor = torch.tensor(cam).to(device).float()
+ radius = float(radius) / float(image_size[0]) * 2.0
+ v_list = []
+ v_color_list = []
+ pbar = tqdm.tqdm(range(c2w.shape[0]))
+ for i in pbar:
+ if i > -1:
+ gt_rgb = torch.Tensor(allimg[i:i+1,...]).permute(0,3,1,2)
+ w2c = np.linalg.inv(c2w[i])
+ w2c_tensor = torch.tensor(w2c).to(device)
+ cano_mask = render_point(cano_v, cano_color, H, W, K_tensor, w2c_tensor, image_size, radius, ppp)
+ imageio.imwrite(outputdir+'/render_%s_mask.png'%(i),np.array(cano_mask[0].permute(1,2,0).detach().cpu().numpy() * 255,dtype=np.uint8))
+ mask = imageio.imread(outputdir+'/render_%s_mask.png'%(i)) / 255
+ os.remove(outputdir+'/render_%s_mask.png'%(i))
+ kernel = np.ones(((15, 15)), np.uint8) ##11
+ mask = cv2.erode(mask,kernel,iterations=1)
+ mask = np.logical_or(np.logical_or((mask[:,:, 0]>0.9),(mask[:,:, 1]>0.9)), (mask[:,:, 2]>0.9))
+ mask = np.logical_and(alphamask[i], ~mask)
+
+ D = allD[i]
+ x, y = np.meshgrid(np.arange(D.shape[0]), np.arange(D.shape[1]))
+ cam_xyz = np.vstack(( \
+ x.reshape(-1), \
+ y.reshape(-1), \
+ np.ones(len(D.reshape(-1)))))
+ v = np.linalg.inv(cam).dot(cam_xyz).T
+ v = v * np.tile(D.reshape((-1,1)), (1,3))
+ # imageio.imwrite(outputdir+'/render_%s_new_mask.png'%(i),np.array(mask * 255,dtype=np.uint8))
+
+ v = v[mask.reshape(-1)==1]
+
+ v = np.matmul(v,c2w[i, :3,:3].T)+c2w[i, :3, 3:].T
+ xy1, xyz = project(v, K, cano_w2c[:3, :4])
+ xy1 = np.round(xy1).astype(np.int32)
+ xy1 =torch.Tensor(xy1[None,None,...])/H*2.-1.
+ xy_d=F.grid_sample(cano_D, xy1)
+ xy_d = xy_d.squeeze(0).squeeze(0).permute(1,0).cpu().numpy()
+ xy_mask = np.logical_and((xyz-xy_d) <= (1 / H), (xyz-xy_d) >= -0.2)
+ # xy_mask = ((xyz-xy_d) >= -0.2)
+ v = v[~xy_mask[:, 0], :]
+
+ mask_cano = z_buffer(v, w2c, H, W, K)
+ v = v[mask_cano,:] #有color的点
+ xy,_ = project(v ,K, w2c[:3,:4])
+ xy =torch.Tensor(xy[None,None,...])/H*2.-1.
+ v_color=F.grid_sample(gt_rgb,xy)
+ v_color = v_color.squeeze().permute(1,0).cpu().numpy()
+
+ v_list.append(v)
+ v_color_list.append(v_color)
+
+ v_list = np.concatenate(v_list)
+ v_color_list = np.concatenate(v_color_list)
+ if len(v_list) < npoint:
+ return v_list, v_color_list
+ else:
+ arr = np.arange(len(v_list))
+ np.random.shuffle(arr)
+ arr = arr[:npoint]
+ return v_list[arr], v_color_list[arr]
+
+def depth2point(D, alphamask, c2w, gt_rgb, H, W, cam):
+ K = cam
+ x, y = np.meshgrid(np.arange(D.shape[1]), np.arange(D.shape[0]))
+ cam_xyz = np.vstack(( \
+ x.reshape(-1), \
+ y.reshape(-1), \
+ np.ones(len(D.reshape(-1)))))
+ v = np.linalg.inv(cam).dot(cam_xyz).T
+ v = v * np.tile(D.reshape((-1,1)), (1,3))
+ v = v[alphamask.reshape(-1)==1]
+ v = np.matmul(v,c2w[:3,:3].T)+c2w[:3, 3:].T
+ # save_mesh = trimesh.points.PointCloud(vertices = v)
+ # save_mesh.export(outputdir + '/teddy_depth_fix.obj')
+
+ w2c = np.linalg.inv(c2w)
+ mask_cano = z_buffer(v, w2c, H, W, K)
+ v = v[mask_cano,:] #有color的点
+
+ xy,_ = project(v ,K, w2c[:3,:4])
+ gt_rgb = torch.Tensor(gt_rgb[None,...]).permute(0,3,1,2)
+ xy =torch.Tensor(xy[None,None,...])/H*2.-1.
+ v_color=F.grid_sample(gt_rgb,xy)
+ v_color = v_color.squeeze().permute(1,0).cpu().numpy()
+ return v, v_color
+
+def project(xyz, K, RT):
+ xyz = np.dot(xyz, RT[:, :3].T) + RT[:, 3:].T
+ xyz = np.dot(xyz, K.T)
+ xy = xyz[:, :2] / xyz[:, 2:]
+ return xy,xyz[:,2:]
+
+def safe_normalize(x, eps=1e-20):
+ return x / np.sqrt(np.clip(np.sum(x * x, axis=-1), eps, 100000))
+
+def safe_normalize_tensor(x, eps=1e-20):
+ return x / torch.sqrt(torch.clamp(torch.sum(x * x, -1, keepdim=True), min=eps))
+
+# borrow from https://github.com/jiaxinxie97/HFGI3D/blob/main/multi_views/generate_multi_views.py
+def z_buffer(vertices, world2cam_pose_cano, H, W, K):
+ # world to camera
+ xy1,xyz = project(vertices, K, world2cam_pose_cano[:3,:4])
+ xy1 = np.round(xy1).astype(np.int32)
+ xy1_mask =np.logical_and(np.logical_and((xy1[:,0]>=0),(xy1[:,0]<=W-1)),np.logical_and((xy1[:,1]>=0),(xy1[:,1]<=H-1)))
+
+ # zbuffer, find visible point
+ img1 = np.zeros((H,W))
+ zbuff = np.zeros((H,W,2))
+ maskout =[]
+ colorout = []
+ for i in np.arange(xy1.shape[0]):
+ if xy1_mask[i]:
+ if img1[xy1[i, 1], xy1[i, 0]]==0:
+ img1[xy1[i, 1], xy1[i, 0]] = 1
+ zbuff[xy1[i,1], xy1[i,0],0] = xyz[i,0]
+ zbuff[xy1[i,1], xy1[i,0],1] = i
+ elif xyz[i,0]<zbuff[xy1[i,1],xy1[i,0,],0]:
+ zbuff[xy1[i,1],xy1[i,0],0] = xyz[i,0]
+ zbuff[xy1[i,1], xy1[i,0],1] = i
+ else:
+ continue
+
+ for i in np.arange(xy1.shape[0]):
+ if xy1_mask[i]:
+ if (xyz[i,0]-zbuff[xy1[i,1],xy1[i,0,],0])> (1./H):
+ # continue
+ maskout.append(vertices[int(i):int(i)+1,:])
+ colorout.append(np.array([0,0,0],dtype=np.float32).reshape((1,3)))
+ else:
+ maskout.append(vertices[int(i):int(i)+1,:])
+ colorout.append(np.array([1,1,1],dtype=np.float32).reshape((1,3)))
+ else:
+ maskout.append(vertices[int(i):int(i)+1,:])
+ colorout.append(np.array([0,0,0],dtype=np.float32).reshape((1,3)))
+ maskout = np.concatenate(maskout,axis=0)
+ colorout = np.concatenate(colorout,axis=0)
+ vertices = maskout
+ colors = colorout
+ mask =((colors[:,0]+colors[:,1]+colors[:,2])!=0)
+
+ return mask
+
+def rand_poses(index, device, radius_range=[1, 1.5], theta_range=[0, 100], phi_range=[0, 360]):
+
+ theta_range = np.deg2rad(theta_range)
+ phi_range = np.deg2rad(phi_range)
+ size = 1
+ if index % 4 == 0:
+ radius = torch.ones(size, device=device)
+ thetas = torch.ones(size, device=device) * (theta_range[1] - theta_range[0]) / 2 + theta_range[0]
+ phis = torch.ones(size, device=device) * (phi_range[1] - phi_range[0]) / 2 + phi_range[0]
+ is_front = True
+ else:
+ radius = torch.rand(size, device=device) * (radius_range[1] - radius_range[0]) + radius_range[0]
+ phis = torch.rand(size, device=device) * (phi_range[1] - phi_range[0]) + phi_range[0]
+ thetas = torch.rand(size, device=device) * (theta_range[1] - theta_range[0]) + theta_range[0]
+ is_front = False
+
+ centers = torch.stack([
+ radius * torch.sin(thetas) * torch.sin(phis),
+ radius * torch.cos(thetas),
+ radius * torch.sin(thetas) * torch.cos(phis),
+ ], dim=-1) # [B, 3]
+
+ targets = 0
+ # lookat
+ forward_vector = safe_normalize_tensor(targets - centers)
+ up_vector = torch.FloatTensor([0, -1, 0]).to(device).unsqueeze(0).repeat(size, 1)
+ right_vector = safe_normalize_tensor(torch.cross(forward_vector, up_vector, dim=-1))
+
+ poses = torch.eye(4, dtype=torch.float, device=device).unsqueeze(0).repeat(size, 1, 1)
+ poses[:, :3, :3] = torch.stack((right_vector, up_vector, forward_vector), dim=-1)
+ poses[:, :3, 3] = centers
+
+ return poses, is_front
+
+def fix_poses(index, device, radius_range=[1, 1.5], theta_range=[0, 100], phi_range=[0, 360]):
+
+ theta_range = np.deg2rad(theta_range)
+ phi_range = np.deg2rad(phi_range)
+ size = 1
+
+ if index % 4 == 0:
+ radius = torch.ones(size, device=device)
+ thetas = torch.ones(size, device=device) * (theta_range[1] - theta_range[0]) / 2 + theta_range[0]
+ phis = torch.ones(size, device=device) * (phi_range[1] - phi_range[0]) / 2 + phi_range[0]
+ # phis = torch.ones(size, device=device) * phi_range[0]
+ is_front = True
+ is_large = False
+
+ else:
+ radius = torch.rand(size, device=device) * (radius_range[1] - radius_range[0]) + radius_range[0]
+ if phi_range[1] <= np.deg2rad(240.0) and phi_range[0] >= np.deg2rad(120.0):
+ phis = torch.rand(size, device=device) * (phi_range[1] - phi_range[0]) + phi_range[0]
+ else:
+ rand = random.random()
+ if rand > 0.85:
+ phis = torch.rand(size, device=device) * (phi_range[1] - np.deg2rad(315.0)) + np.deg2rad(315.0)
+ elif rand > 0.7:
+ phis = torch.rand(size, device=device) * (np.deg2rad(45.0) - phi_range[0]) + phi_range[0]
+ elif rand > 0.5:
+ phis = torch.rand(size, device=device) * (np.deg2rad(315.0) - np.deg2rad(240.0)) + np.deg2rad(240.0)
+ elif rand > 0.3:
+ phis = torch.rand(size, device=device) * (np.deg2rad(120.0) - np.deg2rad(45.0)) + np.deg2rad(45.0)
+ else:
+ phis = torch.rand(size, device=device) * (np.deg2rad(240.0) - np.deg2rad(120.0)) + np.deg2rad(120.0)
+
+ is_front = False
+
+ rand_theta = torch.rand(size, device=device)
+ thetas = rand_theta * (theta_range[1] - theta_range[0]) + theta_range[0]
+
+ if (phis >= np.deg2rad(0) and phis <= np.deg2rad(45)) or (phis >= np.deg2rad(315) and phis <= np.deg2rad(360)):
+ is_large = True
+ else:
+ is_large = False
+
+ centers = torch.stack([
+ radius * torch.sin(thetas) * torch.sin(phis),
+ radius * torch.cos(thetas),
+ radius * torch.sin(thetas) * torch.cos(phis),
+ ], dim=-1) # [B, 3]
+
+ targets = 0
+ # lookat
+ forward_vector = safe_normalize_tensor(targets - centers)
+ up_vector = torch.FloatTensor([0, -1, 0]).to(device).unsqueeze(0).repeat(size, 1)
+ right_vector = safe_normalize_tensor(torch.cross(forward_vector, up_vector, dim=-1))
+
+ up_noise = 0
+ up_vector = safe_normalize_tensor(torch.cross(right_vector, forward_vector, dim=-1) + up_noise)
+
+ poses = torch.eye(4, dtype=torch.float, device=device).unsqueeze(0).repeat(size, 1, 1)
+ poses[:, :3, :3] = torch.stack((right_vector, up_vector, forward_vector), dim=-1)
+ poses[:, :3, 3] = centers
+
+ return poses, is_front, is_large
+
+def render_point(points_xyz_org, points_color, H, W, K, world2cam, image_size, radius, ppp, bg_feat=None, acc='alphacomposite'):
+ proj_xyz = torch.matmul(points_xyz_org, world2cam[:3, :3].T) + world2cam[:3, 3]
+
+ # Perspective projection
+ proj_xyz = torch.matmul(proj_xyz, K.T)
+ proj_xyz[:, 0:2] = proj_xyz[:, 0:2] / proj_xyz[:, 2:]
+ proj_xyz[:, 0] = proj_xyz[:, 0] / W * 2 - 1.0
+ proj_xyz[:, 1] = proj_xyz[:, 1] / H * 2 - 1.0
+ proj_xyz[:, 0] = proj_xyz[:, 0] * -1
+ proj_xyz[:, 1] = proj_xyz[:, 1] * -1
+
+ pts3D = Pointclouds(points=[proj_xyz], features=[points_color])
+ points_idx, z_buf, dist = rasterize_points(
+ pts3D, image_size, radius, ppp)
+ dist = 0.1*dist/ pow(radius, 2)
+ alphas = (
+ (1 - dist.clamp(max=1, min=1e-3).pow(0.5))
+ .pow(1)
+ .permute(0, 3, 1, 2)
+ )
+
+ transformed_src_alphas = compositing.alpha_composite(
+ points_idx.permute(0, 3, 1, 2).long(),
+ alphas,
+ pts3D.features_packed().permute(1,0),
+ )
+
+ return transformed_src_alphas
+
+def load_views(gt_rgb, rgb_files, depth_files, mask_files, cam2world_list, H, W, K, radius, ppp, outputdir, device):
+
+ # Load single-view depth
+ print("###### Loading single-view depth image ######")
+ ind = (len(cam2world_list)-1) // 2
+ depth_file_cano = depth_files[ind]
+ mask_file_cano = mask_files[ind]
+ cam2world_cano = cam2world_list[ind]
+ depth_cano = load_depth(depth_file_cano) / 1000.0
+
+ mask_cano = load_depth(mask_file_cano) / 255.0
+ depth_cano = cv2.resize(depth_cano,(W,H))
+ mask_cano = cv2.resize(mask_cano,(W,H))
+ kernel = np.ones(((11, 11)), np.uint8) ##11
+ mask_cano = cv2.erode(mask_cano,kernel,iterations=2)
+ mask_cano = (mask_cano==1)
+
+ depth_blur = depth_cano * mask_cano * 255.0
+ depth_blur = np.uint8(depth_blur)
+ sobel = cv2.Canny(depth_blur, 30, 30)
+ kernel = np.ones(((11, 11)), np.uint8)
+ edge_mask_cano = cv2.dilate(sobel, kernel,iterations=1)
+ # cv2.imwrite(os.path.join(outputdir, f'render_cano_sobel.png'), edge_mask_cano)
+
+ edge_mask_cano = (edge_mask_cano==255)
+ # mask_cano = np.logical_and(mask_cano, ~edge_mask_cano)
+ #### depth to point cloud
+ print("###### Depth to point cloud and mesh ######")
+ print("###### Single view point cloud colorization ######")
+ vertices_cano, vertices_color_cano = depth2point(depth_cano, mask_cano, cam2world_cano, gt_rgb, H, W, K)
+
+ # Load multi-view depth
+ print("###### Loading multi-view depth image ######")
+ all_depth=[]
+ all_mask=[]
+ all_cam = []
+ all_rgb = []
+ for i in range(len(depth_files)):
+ if i == ind:
+ continue
+ else:
+ depth = load_depth(depth_files[i]) / 1000.0
+ mask = load_depth(mask_files[i]) / 255.0
+ rgb = imageio.imread(rgb_files[i])/255.
+
+ depth = cv2.resize(depth,(W,H))
+ mask = cv2.resize(mask,(W,H))
+
+ kernel = np.ones(((11, 11)), np.uint8) ##11
+ mask = cv2.erode(mask,kernel,iterations=1)
+ mask = (mask==1)
+ depth_blur = depth * mask * 255.0
+ depth_blur = np.uint8(depth_blur)
+ sobel = cv2.Canny(depth_blur, 10, 10)
+ kernel = np.ones(((11, 11)), np.uint8)
+ edge_mask = cv2.dilate(sobel, kernel,iterations=1)
+ # cv2.imwrite(os.path.join(outputdir, f'render_{i}_sobel.png'),edge_mask)
+
+ edge_mask = (edge_mask==255)
+ rgb = cv2.resize(rgb[:,:,:3],(W,H))
+ mask = np.logical_and(mask, ~edge_mask)
+ c2w = cam2world_list[i]
+ all_depth.append(depth)
+ all_mask.append(mask)
+ all_cam.append(c2w)
+ all_rgb.append(rgb)
+
+ all_depth = np.stack(all_depth, axis=0)
+ all_mask = np.stack(all_mask, axis=0)
+ all_cam = np.stack(all_cam, axis=0)
+ all_rgb = np.stack(all_rgb, axis=0)
+ #### depth to point cloud
+ print("###### Multi depth to point cloud and mesh ######")
+ vertices_novel, vertices_color_novel = multidepth2point_mask(all_depth, all_mask, all_rgb, K, all_cam, vertices_cano, cam2world_cano, depth_cano*mask_cano, H, W, radius, ppp, outputdir, device)
+
+ return vertices_cano, vertices_color_cano, vertices_novel, vertices_color_novel
\ No newline at end of file
diff --git a/nerf/unet.py b/nerf/unet.py
new file mode 100644
index 0000000..52cfb09
--- /dev/null
+++ b/nerf/unet.py
@@ -0,0 +1,172 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+_assert_if_size_mismatch = True
+
+class Identity(nn.Module):
+ def __init__(self, *args, **kwargs):
+ super(Identity, self).__init__()
+
+ def forward(self, x):
+ return x
+
+class BasicBlock(nn.Module):
+ def __init__(self, in_channels, out_channels, kernel_size=3, normalization=nn.BatchNorm2d):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.conv1 = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size, padding=1),
+ normalization(out_channels),
+ nn.ReLU())
+
+ self.conv2 = nn.Sequential(nn.Conv2d(out_channels, out_channels, kernel_size, padding=1),
+ normalization(out_channels),
+ nn.ReLU())
+
+ def forward(self, inputs, **kwargs):
+ outputs = self.conv1(inputs)
+ outputs = self.conv2(outputs)
+ return outputs
+
+
+class GatedBlock(nn.Module):
+ def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, dilation=1, padding_mode='reflect', act_fun=nn.ELU, normalization=nn.BatchNorm2d):
+ super().__init__()
+ self.pad_mode = padding_mode
+ self.filter_size = kernel_size
+ self.stride = stride
+ self.dilation = dilation
+
+ n_pad_pxl = int(self.dilation * (self.filter_size - 1) / 2)
+
+ # this is for backward campatibility with older model checkpoints
+ self.block = nn.ModuleDict(
+ {
+ 'conv_f': nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, padding=n_pad_pxl),
+ 'act_f': act_fun(),
+ 'conv_m': nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, padding=n_pad_pxl),
+ 'act_m': nn.Sigmoid(),
+ 'norm': normalization(out_channels)
+ }
+ )
+
+ def forward(self, x, *args, **kwargs):
+ features = self.block.act_f(self.block.conv_f(x))
+ mask = self.block.act_m(self.block.conv_m(x))
+ output = features * mask
+ output = self.block.norm(output)
+
+ return output
+
+
+class DownsampleBlock(nn.Module):
+ def __init__(self, in_channels, out_channels, conv_block=BasicBlock):
+ super().__init__()
+
+ self.conv = conv_block(in_channels, out_channels)
+ self.down = nn.AvgPool2d(2, 2)
+
+ def forward(self, inputs, mask=None):
+ outputs = self.down(inputs)
+ outputs = self.conv(outputs, mask=mask)
+ return outputs
+
+
+class UpsampleBlock(nn.Module):
+ def __init__(self, out_channels, upsample_mode, same_num_filt=False, conv_block=BasicBlock):
+ super().__init__()
+ self.out_channels = out_channels
+
+ num_filt = out_channels if same_num_filt else out_channels * 2
+ if upsample_mode == 'deconv':
+ self.up = nn.ConvTranspose2d(num_filt, out_channels, 4, stride=2, padding=1)
+ self.conv = conv_block(out_channels * 2, out_channels, normalization=Identity)
+ elif upsample_mode=='bilinear' or upsample_mode=='nearest':
+ self.up = nn.Sequential(nn.Upsample(scale_factor=2, mode=upsample_mode),
+ # Before refactoring, it was a nn.Sequential with only one module.
+ # Need this for backward compatibility with model checkpoints.
+ nn.Sequential(
+ nn.Conv2d(num_filt, out_channels, 3, padding=1)
+ )
+ )
+ self.conv = conv_block(out_channels * 2, out_channels, normalization=Identity)
+ else:
+ assert False
+
+ def forward(self, inputs1, inputs2):
+ in1_up = self.up(inputs1)
+ if (inputs2.size(2) != in1_up.size(2)) or (inputs2.size(3) != in1_up.size(3)):
+ if _assert_if_size_mismatch:
+ raise ValueError(f'input2 size ({inputs2.shape[2:]}) does not match upscaled inputs1 size ({in1_up.shape[2:]}')
+ diff2 = (inputs2.size(2) - in1_up.size(2)) // 2
+ diff3 = (inputs2.size(3) - in1_up.size(3)) // 2
+ inputs2_ = inputs2[:, :, diff2 : diff2 + in1_up.size(2), diff3 : diff3 + in1_up.size(3)]
+ else:
+ inputs2_ = inputs2
+ output= self.conv(torch.cat([in1_up, inputs2_], 1))
+ return output
+
+
+class UNet(nn.Module):
+ r""" Rendering network with UNet architecture and multi-scale input."""
+ def __init__(
+ self,
+ num_input_channels=3,
+ num_output_channels=3,
+ feature_scale=4,
+ upsample_mode='bilinear',
+ last_act='sigmoid',
+ conv_block='gated'
+ ):
+ super().__init__()
+
+ self.feature_scale = feature_scale
+
+ self.num_input_channels = num_input_channels
+
+ if conv_block == 'basic':
+ self.conv_block = BasicBlock
+ elif conv_block == 'gated':
+ self.conv_block = GatedBlock
+ else:
+ raise ValueError('bad conv block {}'.format(conv_block))
+
+ filters = [64, 128, 256, 512, 1024]
+ filters = [x // self.feature_scale for x in filters]
+
+ # norm_layer = get_norm_layer(norm_layer)
+
+ self.start = self.conv_block(self.num_input_channels, filters[0])
+
+ self.down1 = DownsampleBlock(filters[0], filters[1] - self.num_input_channels, conv_block=self.conv_block)
+ self.down2 = DownsampleBlock(filters[1], filters[2] - self.num_input_channels, conv_block=self.conv_block)
+
+ self.up2 = UpsampleBlock(filters[1], upsample_mode, conv_block=self.conv_block)
+ self.up1 = UpsampleBlock(filters[0], upsample_mode, conv_block=self.conv_block)
+
+ # Before refactoring, it was a nn.Sequential with only one module.
+ # Need this for backward compatibility with model checkpoints.
+ self.final = nn.Sequential(
+ nn.Conv2d(filters[0], num_output_channels, 1)
+ )
+ if last_act == 'sigmoid':
+ self.final = nn.Sequential(self.final, nn.Sigmoid())
+ elif last_act == 'tanh':
+ self.final = nn.Sequential(self.final, nn.Tanh())
+
+ def forward(self, inputs, **kwargs):
+ masks = [None] * len(inputs)
+ in64 = self.start(inputs[0], mask=masks[0])
+ mask = masks[1]
+ down1 = self.down1(in64, mask)
+ down1 = torch.cat([down1, inputs[1]], 1)
+
+ mask = masks[2]
+ down2 = self.down2(down1, mask)
+ down2 = torch.cat([down2, inputs[2]], 1)
+
+ up_= down2
+ up_ = self.up2(up_, down1)
+ up1 = self.up1(up_, in64)
+ return self.final(up1)
diff --git a/nerf/utils.py b/nerf/utils.py
index 61ef22b..23338dc 100644
--- a/nerf/utils.py
+++ b/nerf/utils.py
@@ -23,7 +23,8 @@ import torch.nn.functional as F
import torch.distributed as dist
from torch.utils.data import Dataset, DataLoader
from torchvision.utils import save_image
-
+from nerf.refine_utils import *
+from nerf.unet import UNet
import trimesh
import mcubes
from rich.console import Console
@@ -32,8 +33,9 @@ from torch_ema import ExponentialMovingAverage
import clip
import torchvision.transforms as T
from torchmetrics import PearsonCorrCoef
-
+import contextual_loss as cl
from packaging import version as pver
+from copy import deepcopy
def custom_meshgrid(*args):
# ref: https://pytorch.org/docs/stable/generated/torch.meshgrid.html?highlight=meshgrid#torch.meshgrid
@@ -449,6 +451,11 @@ class Trainer(object):
text_z = text_z / text_z.norm(dim=-1, keepdim=True)
loss = - (image_z_1 * text_z).sum(-1).mean()
return loss
+
+ def img_cx_loss(self, cx_model, rgb1, rgb2):
+ loss = cx_model(rgb1, rgb2)
+ return loss
+
### ------------------------------
def train_step(self, data):
@@ -661,7 +668,7 @@ class Trainer(object):
self.evaluate_one_epoch(loader, name)
self.use_tensorboardX = use_tensorboardX
- def test(self, loader, save_path=None, name=None, write_video=True):
+ def test(self, loader, save_path=None, name=None, write_image=True, write_video=True):
if save_path is None:
save_path = os.path.join(self.workspace, 'result')
@@ -716,26 +723,227 @@ class Trainer(object):
pred_depth = preds_depth[0].detach().cpu().numpy()
pred_depth = (pred_depth * 1000.).astype(np.uint16)
- cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_rgb.png'), cv2.cvtColor(pred, cv2.COLOR_RGB2BGR))
- if preds_normal is not None:
- cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_normal.png'), cv2.cvtColor(preds_normal, cv2.COLOR_RGB2BGR))
- cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_depth.png'), pred_depth)
- cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_mask.png'), mask)
+ if write_image:
+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_rgb.png'), cv2.cvtColor(pred, cv2.COLOR_RGB2BGR))
+ if preds_normal is not None:
+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_normal.png'), cv2.cvtColor(preds_normal, cv2.COLOR_RGB2BGR))
+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_depth.png'), pred_depth)
+ cv2.imwrite(os.path.join(save_path, f'{name}_{i:04d}_mask.png'), mask)
+
pbar.update(loader.batch_size)
if write_video:
all_preds = np.stack(all_preds, axis=0)
all_preds_normal = np.stack(all_preds_normal, axis=0)
- all_preds_depth = np.stack(all_preds_depth, axis=0)
imageio.mimwrite(os.path.join(save_path, f'{name}_normal.mp4'), all_preds_normal, fps=25, quality=8, macro_block_size=1)
imageio.mimwrite(os.path.join(save_path, f'{name}_rgb.mp4'), all_preds, fps=25, quality=8, macro_block_size=1)
- imageio.mimwrite(os.path.join(save_path, f'{name}_depth.mp4'), all_preds_depth, fps=25, quality=8, macro_block_size=1)
all_poses = np.stack(all_poses, axis=0)
np.save(os.path.join(save_path, f'{name}_poses.npy'), all_poses)
self.log(f"==> Finished Test.")
+
+ def refine(self, load_dir, train_iters, test_loader):
+
+ load_data_folder = load_dir
+ outputdir = load_dir.replace("mvimg", "refine")
+ os.makedirs(outputdir,exist_ok=True)
+ text = self.opt.text
+ image_path = self.opt.ref_path
+ fov = self.opt.fov
+ H, W = self.opt.H, self.opt.W
+ device = torch.device('cuda')
+ # Camera intrincs and extrincs
+ focal = 1 / (2 * np.tan(np.deg2rad(fov) / 2))
+ K = np.array([[focal*W, 0, 0.5*W], [0, focal*H, 0.5*H], [0, 0, 1]])
+ cam_files = sorted(glob.glob(load_data_folder+'/*poses.npy'))
+ cam_file = cam_files[0]
+ cam2world_list = np.load(cam_file)
+ cam2world_cano = cam2world_list[(cam2world_list.shape[0]-1)//2]
+ image_size = [H, W]
+ radius = 2 #8 # points radius in pixel coordinate
+ ppp = 8 # points per pixels, for z_buffer
+
+ gt_rgb = imageio.imread(image_path)/255.
+ gt_rgb = cv2.resize(gt_rgb[:,:,:3],(H, W))
+
+ # load images
+ depth_files = sorted(glob.glob(load_data_folder+'/*depth.png'))
+ mask_files = sorted(glob.glob(load_data_folder+'/*mask.png'))
+ rgb_files = sorted(glob.glob(load_data_folder+'/*rgb.png'))
+
+ vertices_cano, vertices_color_cano, vertices_novel, vertices_color_novel = load_views(gt_rgb, rgb_files, depth_files, mask_files, cam2world_list, H, W, K, radius, ppp, outputdir, device)
+
+ #### colorize point cloud
+ # init zeros
+ all_v = np.concatenate((vertices_cano, vertices_novel), axis=0)
+ all_v_color = np.concatenate((vertices_color_cano, vertices_color_novel), axis=0)
+
+ # Save or load
+ print("###### Save point cloud ######")
+ np.save(outputdir + '/vertices_cano.npy', vertices_cano)
+ np.save(outputdir + '/vertices_color_cano.npy', vertices_color_cano)
+ np.save(outputdir + '/vertices_novel.npy', vertices_novel)
+ np.save(outputdir + '/vertices_color_novel.npy', vertices_color_novel)
+
+ # refine stage optimization with SDS loss
+ print("###### Optimization with SDS loss ######")
+ K = torch.tensor((K), device=device).float()
+ gt_rgb = imageio.imread(image_path)/255.
+ gt_mask = cv2.resize(gt_rgb[:,:,3:],(H, W))
+ gt_rgb = cv2.resize(gt_rgb[:,:,:3],(H, W))
+ gt_rgb = torch.Tensor(gt_rgb[None,...]).permute(0,3,1,2)
+ gt_rgb = gt_rgb.to(device)
+
+ kernel = np.ones(((5,5)), np.uint8) ##11
+ gt_mask = cv2.erode(gt_mask,kernel,iterations=1)
+ gt_mask = torch.Tensor(gt_mask).unsqueeze(0).unsqueeze(1)
+ gt_mask = gt_mask.to(device)
+
+ train_outputdir = outputdir+'/train/'
+ os.makedirs(train_outputdir,exist_ok=True)
+
+ radius = float(radius) / float(image_size[0]) * 2.0
+ unet = UNet(num_input_channels=3+16).to(device)
+ unet.train()
+ cx_model = cl.ContextualLoss(use_vgg=True, vgg_layer='relu5_4').to(device)
+
+ vertices_cano = torch.tensor((vertices_cano), requires_grad=False, device=device)
+ vertices_novel = torch.tensor((vertices_novel), requires_grad=False, device=device)
+ vertices_color_cano = torch.tensor((vertices_color_cano), requires_grad=False, device=device)
+
+ feat_cano = torch.nn.Parameter(torch.randn((vertices_color_cano.shape[0], 16), requires_grad=True, device=device))
+ vertices_color_cano = torch.nn.Parameter(torch.tensor((vertices_color_cano), requires_grad=True, device=device))
+ vertices_color_novel = torch.nn.Parameter(torch.tensor((vertices_color_novel), requires_grad=True, device=device))
+ feat_novel = torch.nn.Parameter(torch.randn((vertices_color_novel.shape[0], 16), requires_grad=True, device=device))
+ bg_feat = torch.nn.Parameter(torch.ones((1, 19, 1, 1), requires_grad=True, device=device))
+
+ vertices_color_novel_origin = deepcopy(vertices_color_novel).to(device)
+ vertices_color_novel_origin.requires_grad = False
+ vertices_color_cano_origin = deepcopy(vertices_color_cano).to(device)
+ vertices_color_cano_origin.requires_grad = False
+
+ params = [{'params': [vertices_color_novel], 'lr': 0.001}, \
+ {'params': [vertices_color_cano], 'lr': 0.001}, \
+ {'params': [feat_novel], 'lr': 0.001}, \
+ {'params': [feat_cano], 'lr': 0.001}, \
+ {'params': [bg_feat], 'lr': 0.001}, \
+ {'params': unet.parameters(), 'lr': 0.001}]
+
+ point_optimizer = torch.optim.Adam(params, betas=(0.9, 0.99), eps=1e-15)
+ point_scheduler = torch.optim.lr_scheduler.LambdaLR(point_optimizer, lambda iter: 0.1 ** min(iter / 1000, 1))
+ max_pool = torch.nn.MaxPool2d(kernel_size=5, stride=1, padding=2)
+
+ pbar = tqdm.tqdm(range(train_iters))
+ for i in pbar:
+ rand_c2w, is_front, is_large = fix_poses(i, device, radius_range=self.opt.radius_range, theta_range=self.opt.theta_range, phi_range=self.opt.phi_range)
+ text_z = self.text_z[0]
+ ref_text = self.text[0]
+
+ cam2world = rand_c2w[0,:,:]
+ world2cam = torch.linalg.inv(cam2world)
+ all_v = torch.cat((vertices_cano, vertices_novel),dim=0).float()
+ all_xy_cano = torch.cat((vertices_color_cano, feat_cano),dim=-1).float()
+ all_xy_novel = torch.cat((vertices_color_novel, feat_novel),dim=-1).float()
+ all_v_color = torch.cat((all_xy_cano, all_xy_novel),dim=0).float()
+
+ # Unet
+ scale = 1
+ pred_list = []
+ for j in range(3):
+ h = H // scale
+ w = W // scale
+ image_size = (h, w)
+ K_ = np.array([[focal*w, 0, 0.5*w], [0, focal*h, 0.5*h], [0, 0, 1]])
+ K_ = torch.tensor((K_), device=device).float()
+ pred_rgb = render_point(all_v, all_v_color, h, w, K_, world2cam, image_size, radius, ppp, bg_feat=bg_feat)
+ scale = scale * 2
+ pred_list.append(pred_rgb)
+ pred_rgb = unet(pred_list)
+
+ H, W = 800, 800
+ image_size = (H, W)
+ v_mask_color = torch.ones_like(all_v).float().to(device)
+ pred_mask = render_point(all_v, v_mask_color, H, W, K, world2cam, image_size, radius, ppp)
+ pred_mask_dilate = max_pool(pred_mask)
+
+ if i % 50 == 0:
+ save_image(pred_rgb, os.path.join(train_outputdir, f'{i}.png'))
+ # save_image(pred_mask_dilate, os.path.join(train_outputdir, f'{i}_mask.png'))
+
+ if is_front:
+ clip_loss = 1000 * self.img_loss(pred_rgb*gt_mask, gt_rgb*gt_mask)
+ bg_loss = 0
+ else:
+ clip_loss, de_imgs = self.guidance.train_step(text_z, pred_rgb, clip_model=self.clip_model,
+ ref_text=ref_text, islarge=False, ref_rgb=gt_rgb, guidance_scale=5)
+ clip_loss += 10 * self.img_clip_loss(pred_rgb, gt_rgb)
+ cx_loss = self.img_cx_loss(cx_model, pred_rgb, gt_rgb)
+ clip_loss += cx_loss
+
+ # background regularization
+ bg_loss = 1e-3 * (1 - pred_rgb * (1 - pred_mask_dilate)).sum()
+ reg_loss = torch.nn.MSELoss()(vertices_color_novel, vertices_color_novel_origin) * 1e3 + torch.nn.MSELoss()(vertices_color_cano, vertices_color_cano_origin) * 1e5
+ loss = clip_loss + reg_loss + bg_loss
+
+ pbar.set_description((f"loss: {loss.item():.4f}; reg_loss: {reg_loss.item():.4f}; bg_loss: {bg_loss.item():.4f}"))
+
+ point_optimizer.zero_grad()
+ loss.backward()
+ point_optimizer.step()
+
+ if i % 1000 == 0:
+ torch.save(all_v, outputdir + f'/{i}_v_unet.pt')
+ torch.save(all_v_color, outputdir + f'/{i}_v_color_unet.pt')
+ torch.save(bg_feat, outputdir + f'/{i}_bg_unet.pt')
+ torch.save({'model_state_dict': unet.state_dict(),
+ 'optimizer_state_dict': point_optimizer.state_dict(),
+ }, outputdir + f'/{i}_unet.pth')
+
+ torch.save(all_v, outputdir + f'/end_v_unet.pt')
+ torch.save(all_v_color, outputdir + f'/end_v_color_unet.pt')
+ torch.save(bg_feat, outputdir + f'/end_bg_unet.pt')
+ torch.save({'model_state_dict': unet.state_dict(),
+ 'optimizer_state_dict': point_optimizer.state_dict(),
+ }, outputdir + f'/end_unet.pth')
+
+ # unet.eval()
+ # evaluation
+ all_transformed_src_alpha = []
+ white_bg = torch.ones((1, 19, 1, 1)).to(device)
+ white_bg.requires_grad=False
+ img_outdir = os.path.join(outputdir, "results")
+ os.makedirs(img_outdir, exist_ok=True)
+
+ # test
+ print("###### Finel Refine Rendering ######")
+ pbar = tqdm.tqdm(total=len(test_loader) * test_loader.batch_size, bar_format='{percentage:3.0f}% {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]')
+ for i, data in enumerate(test_loader):
+ cam2world = data['poses'][0].detach().cpu().numpy()
+ world2cam = np.linalg.inv(cam2world)
+ world2cam = torch.Tensor(world2cam).to(device)
+ scale = 1
+ pred_list = []
+ for j in range(3):
+ h = H // scale
+ w = W // scale
+ image_size = (h, w)
+ K_ = np.array([[focal*w, 0, 0.5*w], [0, focal*h, 0.5*h], [0, 0, 1]])
+ K_ = torch.tensor((K_), device=device).float()
+ pred_rgb = render_point(all_v, all_v_color, h, w, K_, world2cam, image_size, radius, ppp, bg_feat=bg_feat)
+ scale = scale * 2
+ pred_list.append(pred_rgb)
+ pred_rgb = unet(pred_list)
+ transformed_src_alpha = np.array(pred_rgb[0].permute(1,2,0).detach().cpu().numpy() * 255,dtype=np.uint8)
+ save_image(pred_rgb, img_outdir+f'/render_unet_{i:04d}.png')
+ all_transformed_src_alpha.append(transformed_src_alpha)
+ pbar.update(test_loader.batch_size)
+
+ all_transformed_src_alpha = np.stack(all_transformed_src_alpha, axis=0)
+ imageio.mimwrite(img_outdir+'/render_unet_img_clip.mp4', all_transformed_src_alpha, fps=25, quality=8, macro_block_size=1)
+
+
def train_one_epoch(self, loader):
self.log(f"==> Start Training {self.workspace} Epoch {self.epoch}, lr={self.optimizer.param_groups[0]['lr']:.6f} ...")
diff --git a/raymarching/__pycache__/__init__.cpython-37.pyc b/raymarching/__pycache__/__init__.cpython-37.pyc
new file mode 100644
index 0000000..b268d7b
Binary files /dev/null and b/raymarching/__pycache__/__init__.cpython-37.pyc differ
diff --git a/raymarching/__pycache__/backend.cpython-37.pyc b/raymarching/__pycache__/backend.cpython-37.pyc
new file mode 100644
index 0000000..256c3eb
Binary files /dev/null and b/raymarching/__pycache__/backend.cpython-37.pyc differ
diff --git a/raymarching/__pycache__/raymarching.cpython-37.pyc b/raymarching/__pycache__/raymarching.cpython-37.pyc
new file mode 100644
index 0000000..6a6791b
Binary files /dev/null and b/raymarching/__pycache__/raymarching.cpython-37.pyc differ