File size: 60,209 Bytes
89a7ccb |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 |
from typing import Dict
import numpy as np
from omegaconf import DictConfig, ListConfig
import torch
from torch.utils.data import Dataset
from pathlib import Path
import json
from PIL import Image
from torchvision import transforms
from einops import rearrange
from typing import Literal, Tuple, Optional, Any
import cv2
import random
import json
import os, sys
import math
import PIL.Image
from .normal_utils import trans_normal, normal2img, img2normal
import pdb
from .depth_utils import scale_depth_to_model
import traceback
class ObjaverseDataset(Dataset):
def __init__(self,
root_dir_ortho: str,
root_dir_persp: str,
pred_ortho: bool,
pred_persp: bool,
num_views: int,
bg_color: Any,
img_wh: Tuple[int, int],
object_list: str,
groups_num: int=1,
validation: bool = False,
data_view_num: int = 6,
num_validation_samples: int = 64,
num_samples: Optional[int] = None,
invalid_list: Optional[str] = None,
trans_norm_system: bool = True, # if True, transform all normals map into the cam system of front view
augment_data: bool = False,
read_normal: bool = True,
read_color: bool = False,
read_depth: bool = False,
read_mask: bool = False,
pred_type: str = 'color',
suffix: str = 'png',
subscene_tag: int = 2,
load_cam_type: bool = False,
backup_scene: str = "0306b42594fb447ca574f597352d4b56",
ortho_crop_size: int = 360,
persp_crop_size: int = 440,
load_switcher: bool = True
) -> None:
"""Create a dataset from a folder of images.
If you pass in a root directory it will be searched for images
ending in ext (ext can be a list)
"""
self.load_cam_type = load_cam_type
self.root_dir_ortho = Path(root_dir_ortho)
self.root_dir_persp = Path(root_dir_persp)
self.pred_ortho = pred_ortho
self.pred_persp = pred_persp
self.num_views = num_views
self.bg_color = bg_color
self.validation = validation
self.num_samples = num_samples
self.trans_norm_system = trans_norm_system
self.augment_data = augment_data
self.invalid_list = invalid_list
self.groups_num = groups_num
print("augment data: ", self.augment_data)
self.img_wh = img_wh
self.read_normal = read_normal
self.read_color = read_color
self.read_depth = read_depth
self.read_mask = read_mask
self.pred_type = pred_type # load type
self.suffix = suffix
self.subscene_tag = subscene_tag
self.view_types = ['front', 'front_right', 'right', 'back', 'left', 'front_left']
self.fix_cam_pose_dir = "./mvdiffusion/data/fixed_poses/nine_views"
self.fix_cam_poses = self.load_fixed_poses() # world2cam matrix
self.ortho_crop_size = ortho_crop_size
self.persp_crop_size = persp_crop_size
self.load_switcher = load_switcher
if object_list is not None:
with open(object_list) as f:
self.objects = json.load(f)
self.objects = [os.path.basename(o).replace(".glb", "") for o in self.objects]
else:
self.objects = os.listdir(self.root_dir)
self.objects = sorted(self.objects)
if self.invalid_list is not None:
with open(self.invalid_list) as f:
self.invalid_objects = json.load(f)
self.invalid_objects = [os.path.basename(o).replace(".glb", "") for o in self.invalid_objects]
else:
self.invalid_objects = []
self.all_objects = set(self.objects) - (set(self.invalid_objects) & set(self.objects))
self.all_objects = list(self.all_objects)
if not validation:
self.all_objects = self.all_objects[:-num_validation_samples]
else:
self.all_objects = self.all_objects[-num_validation_samples:]
if num_samples is not None:
self.all_objects = self.all_objects[:num_samples]
print("loading ", len(self.all_objects), " objects in the dataset")
if self.pred_type == 'color':
self.backup_data = self.__getitem_color__(0, backup_scene)
elif self.pred_type == 'normal_depth':
self.backup_data = self.__getitem_normal_depth__(0, backup_scene)
elif self.pred_type == 'mixed_rgb_normal_depth':
self.backup_data = self.__getitem_mixed__(0, backup_scene)
elif self.pred_type == 'mixed_color_normal':
self.backup_data = self.__getitem_image_normal_mixed__(0, backup_scene)
elif self.pred_type == 'mixed_rgb_noraml_mask':
self.backup_data = self.__getitem_mixed_rgb_noraml_mask__(0, backup_scene)
elif self.pred_type == 'joint_color_normal':
self.backup_data = self.__getitem_joint_rgb_noraml__(0, backup_scene)
def __len__(self):
return len(self.objects)*self.total_view
def load_fixed_poses(self):
poses = {}
for face in self.view_types:
RT = np.loadtxt(os.path.join(self.fix_cam_pose_dir,'%03d_%s_RT.txt'%(0, face)))
poses[face] = RT
return poses
def cartesian_to_spherical(self, xyz):
ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
xy = xyz[:,0]**2 + xyz[:,1]**2
z = np.sqrt(xy + xyz[:,2]**2)
theta = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
#ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
azimuth = np.arctan2(xyz[:,1], xyz[:,0])
return np.array([theta, azimuth, z])
def get_T(self, target_RT, cond_RT):
R, T = target_RT[:3, :3], target_RT[:, -1]
T_target = -R.T @ T # change to cam2world
R, T = cond_RT[:3, :3], cond_RT[:, -1]
T_cond = -R.T @ T
theta_cond, azimuth_cond, z_cond = self.cartesian_to_spherical(T_cond[None, :])
theta_target, azimuth_target, z_target = self.cartesian_to_spherical(T_target[None, :])
d_theta = theta_target - theta_cond
d_azimuth = (azimuth_target - azimuth_cond) % (2 * math.pi)
d_z = z_target - z_cond
# d_T = torch.tensor([d_theta.item(), math.sin(d_azimuth.item()), math.cos(d_azimuth.item()), d_z.item()])
return d_theta, d_azimuth
def get_bg_color(self):
if self.bg_color == 'white':
bg_color = np.array([1., 1., 1.], dtype=np.float32)
elif self.bg_color == 'black':
bg_color = np.array([0., 0., 0.], dtype=np.float32)
elif self.bg_color == 'gray':
bg_color = np.array([0.5, 0.5, 0.5], dtype=np.float32)
elif self.bg_color == 'random':
bg_color = np.random.rand(3)
elif self.bg_color == 'three_choices':
white = np.array([1., 1., 1.], dtype=np.float32)
black = np.array([0., 0., 0.], dtype=np.float32)
gray = np.array([0.5, 0.5, 0.5], dtype=np.float32)
bg_color = random.choice([white, black, gray])
elif isinstance(self.bg_color, float):
bg_color = np.array([self.bg_color] * 3, dtype=np.float32)
else:
raise NotImplementedError
return bg_color
def load_mask(self, img_path, return_type='np'):
# not using cv2 as may load in uint16 format
# img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255]
# img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC)
# pil always returns uint8
img = np.array(Image.open(img_path).resize(self.img_wh))
img = np.float32(img > 0)
assert len(np.shape(img)) == 2
if return_type == "np":
pass
elif return_type == "pt":
img = torch.from_numpy(img)
else:
raise NotImplementedError
return img
def load_mask_from_rgba(self, img_path, camera_type):
img = Image.open(img_path)
if camera_type == 'ortho':
left = (img.width - self.ortho_crop_size) // 2
right = (img.width + self.ortho_crop_size) // 2
top = (img.height - self.ortho_crop_size) // 2
bottom = (img.height + self.ortho_crop_size) // 2
img = img.crop((left, top, right, bottom))
if camera_type == 'persp':
left = (img.width - self.persp_crop_size) // 2
right = (img.width + self.persp_crop_size) // 2
top = (img.height - self.persp_crop_size) // 2
bottom = (img.height + self.persp_crop_size) // 2
img = img.crop((left, top, right, bottom))
img = img.resize(self.img_wh)
img = np.array(img).astype(np.float32) / 255. # [0, 1]
assert img.shape[-1] == 4 # must RGBA
alpha = img[:, :, 3:]
if alpha.shape[-1] != 1:
alpha = alpha[:, :, None]
return alpha
def load_image(self, img_path, bg_color, alpha, return_type='np', camera_type=None, read_depth=False, center_crop_size=None):
# not using cv2 as may load in uint16 format
# img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255]
# img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC)
# pil always returns uint8
img = Image.open(img_path)
if center_crop_size == None:
if camera_type == 'ortho':
left = (img.width - self.ortho_crop_size) // 2
right = (img.width + self.ortho_crop_size) // 2
top = (img.height - self.ortho_crop_size) // 2
bottom = (img.height + self.ortho_crop_size) // 2
img = img.crop((left, top, right, bottom))
if camera_type == 'persp':
left = (img.width - self.persp_crop_size) // 2
right = (img.width + self.persp_crop_size) // 2
top = (img.height - self.persp_crop_size) // 2
bottom = (img.height + self.persp_crop_size) // 2
img = img.crop((left, top, right, bottom))
else:
center_crop_size = min(center_crop_size, 512)
left = (img.width - center_crop_size) // 2
right = (img.width + center_crop_size) // 2
top = (img.height - center_crop_size) // 2
bottom = (img.height + center_crop_size) // 2
img = img.crop((left, top, right, bottom))
img = img.resize(self.img_wh)
img = np.array(img).astype(np.float32) / 255. # [0, 1]
assert img.shape[-1] == 3 or img.shape[-1] == 4 # RGB or RGBA
if alpha is None and img.shape[-1] == 4:
alpha = img[:, :, 3:]
img = img[:, :, :3]
if alpha.shape[-1] != 1:
alpha = alpha[:, :, None]
if read_depth:
bg_color = np.array([1., 1., 1.], dtype=np.float32)
img = img[...,:3] * alpha + bg_color * (1 - alpha)
if return_type == "np":
pass
elif return_type == "pt":
img = torch.from_numpy(img)
else:
raise NotImplementedError
return img
def load_depth(self, img_path, bg_color, alpha, return_type='np', camera_type=None):
# not using cv2 as may load in uint16 format
# img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255]
# img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC)
# pil always returns uint8
depth_bg_color = np.array([1., 1., 1.], dtype=np.float32) # white for depth
depth_map = Image.open(img_path)
if camera_type == 'ortho':
left = (depth_map.width - self.ortho_crop_size) // 2
right = (depth_map.width + self.ortho_crop_size) // 2
top = (depth_map.height - self.ortho_crop_size) // 2
bottom = (depth_map.height + self.ortho_crop_size) // 2
depth_map = depth_map.crop((left, top, right, bottom))
if camera_type == 'persp':
left = (depth_map.width - self.persp_crop_size) // 2
right = (depth_map.width + self.persp_crop_size) // 2
top = (depth_map.height - self.persp_crop_size) // 2
bottom = (depth_map.height + self.persp_crop_size) // 2
depth_map = depth_map.crop((left, top, right, bottom))
depth_map = depth_map.resize(self.img_wh)
depth_map = np.array(depth_map)
# scale the depth map:
depth_map = scale_depth_to_model(depth_map.astype(np.float32))
# depth_map = depth_map / 65535. # [0, 1]
# depth_map[depth_map > 0.4] = 0
# depth_map = depth_map / 0.4
assert depth_map.ndim == 2 # depth
img = np.stack([depth_map]*3, axis=-1)
if alpha.shape[-1] != 1:
alpha = alpha[:, :, None]
# print(np.max(img[:, :, 0]))
# print(np.min(img[...,:3]), np.max(img[...,:3]))
img = img[...,:3] * alpha + depth_bg_color * (1 - alpha)
if return_type == "np":
pass
elif return_type == "pt":
img = torch.from_numpy(img)
else:
raise NotImplementedError
return img
def transform_mask_as_input(self, mask, return_type='np'):
# mask = mask * 255
# print(np.max(mask))
# mask = mask.resize(self.img_wh)
mask = np.squeeze(mask, axis=-1)
assert mask.ndim == 2 #
mask = np.stack([mask]*3, axis=-1)
if return_type == "np":
pass
elif return_type == "pt":
mask = torch.from_numpy(mask)
else:
raise NotImplementedError
return mask
def load_normal(self, img_path, bg_color, alpha, RT_w2c=None, RT_w2c_cond=None, return_type='np', camera_type=None, center_crop_size=None):
# not using cv2 as may load in uint16 format
# img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED) # [0, 255]
# img = cv2.resize(img, self.img_wh, interpolation=cv2.INTER_CUBIC)
# pil always returns uint8
# normal = Image.open(img_path)
img = Image.open(img_path)
if center_crop_size == None:
if camera_type == 'ortho':
left = (img.width - self.ortho_crop_size) // 2
right = (img.width + self.ortho_crop_size) // 2
top = (img.height - self.ortho_crop_size) // 2
bottom = (img.height + self.ortho_crop_size) // 2
img = img.crop((left, top, right, bottom))
if camera_type == 'persp':
left = (img.width - self.persp_crop_size) // 2
right = (img.width + self.persp_crop_size) // 2
top = (img.height - self.persp_crop_size) // 2
bottom = (img.height + self.persp_crop_size) // 2
img = img.crop((left, top, right, bottom))
else:
center_crop_size = min(center_crop_size, 512)
left = (img.width - center_crop_size) // 2
right = (img.width + center_crop_size) // 2
top = (img.height - center_crop_size) // 2
bottom = (img.height + center_crop_size) // 2
img = img.crop((left, top, right, bottom))
normal = np.array(img.resize(self.img_wh))
assert normal.shape[-1] == 3 or normal.shape[-1] == 4 # RGB or RGBA
if alpha is None and normal.shape[-1] == 4:
alpha = normal[:, :, 3:] / 255.
normal = normal[:, :, :3]
normal = trans_normal(img2normal(normal), RT_w2c, RT_w2c_cond)
img = (normal*0.5 + 0.5).astype(np.float32) # [0, 1]
if alpha.shape[-1] != 1:
alpha = alpha[:, :, None]
img = img[...,:3] * alpha + bg_color * (1 - alpha)
if return_type == "np":
pass
elif return_type == "pt":
img = torch.from_numpy(img)
else:
raise NotImplementedError
return img
def __len__(self):
return len(self.all_objects)
def __getitem_color__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index % len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
# ! if you would like predict depth; modify here
read_color, read_normal, read_depth = True, False, False
assert (read_color and (read_normal or read_depth)) is False
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
return_type='np')
else:
cond_alpha = None
img_tensors_in = [
self.load_image(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
bg_color, cond_alpha, return_type='pt', camera_type=load_cam_type).permute(2, 0, 1)
] * self.num_views
img_tensors_out = []
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"mask_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"normals_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if read_normal:
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c,
return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
img_tensors_out.append(normal_tensor)
if read_depth:
depth_tensor = self.load_depth(depth_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
img_tensors_out.append(depth_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
# if self.pred_ortho and self.pred_persp:
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class] * self.num_views, dim=0) # (Nv, 2)
color_class = torch.tensor([0, 1]).float()
color_task_embeddings = torch.stack([color_class] * self.num_views, dim=0) # (Nv, 2)
if read_normal or read_depth:
task_embeddings = normal_task_embeddings
if read_color:
task_embeddings = color_task_embeddings
# print(elevations)
# print(azimuths)
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'camera_embeddings': camera_embeddings,
'task_embeddings': task_embeddings
}
def __getitem_normal_depth__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index%len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), return_type='np')
else:
cond_alpha = None
# img_tensors_in = [
# self.load_image(os.path.join(self.root_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), bg_color, cond_alpha, return_type='pt').permute(2, 0, 1)
# ] * self.num_views
img_tensors_out = []
normal_tensors_out = []
depth_tensors_out = []
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if self.read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if self.read_normal:
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "normals_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
normal_tensors_out.append(normal_tensor)
if self.read_depth:
if alpha is None:
alpha = self.load_mask_from_rgba(img_path, camera_type=load_cam_type)
depth_tensor = self.load_depth(depth_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
depth_tensors_out.append(depth_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
img_tensors_in = img_tensors_out
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
if self.read_color:
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
if self.read_normal:
normal_tensors_out = torch.stack(normal_tensors_out, dim=0).float() # (Nv, 3, H, W)
if self.read_depth:
depth_tensors_out = torch.stack(depth_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
# if self.pred_ortho and self.pred_persp:
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class]*self.num_views, dim=0) # (Nv, 2)
color_class = torch.tensor([0, 1]).float()
depth_task_embeddings = torch.stack([color_class]*self.num_views, dim=0) # (Nv, 2)
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'normals_out': normal_tensors_out,
'depth_out': depth_tensors_out,
'camera_embeddings': camera_embeddings,
'normal_task_embeddings': normal_task_embeddings,
'depth_task_embeddings': depth_task_embeddings
}
def __getitem_mixed_rgb_noraml_mask__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index%len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), return_type='np')
else:
cond_alpha = None
img_tensors_out = []
normal_tensors_out = []
depth_tensors_out = []
random_select = random.random()
read_color, read_normal, read_mask = [random_select < 1 / 3, 1 / 3 <= random_select <= 2 / 3,
random_select > 2 / 3]
# print(read_color, read_normal, read_depth)
assert sum([read_color, read_normal, read_mask]) == 1, "Only one variable should be True"
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type, read_depth=False)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if read_normal:
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "normals_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
img_tensors_out.append(normal_tensor)
if read_mask:
if alpha is None:
alpha = self.load_mask_from_rgba(img_path, camera_type=load_cam_type)
mask_tensor = self.transform_mask_as_input(alpha, return_type='pt').permute(2, 0, 1)
img_tensors_out.append(mask_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
if self.load_switcher: # rgb input, use domain switcher to control the output type
img_tensors_in = [
self.load_image(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"normals_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
bg_color, cond_alpha, RT_w2c=cond_w2c, RT_w2c_cond=cond_w2c, return_type='pt', camera_type=load_cam_type).permute(
2, 0, 1)
] * self.num_views
color_class = torch.tensor([0, 1]).float()
color_task_embeddings = torch.stack([color_class] * self.num_views, dim=0) # (Nv, 2)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class] * self.num_views, dim=0) # (Nv, 2)
mask_class = torch.tensor([1, 1]).float()
mask_task_embeddings = torch.stack([mask_class] * self.num_views, dim=0)
if read_color:
task_embeddings = color_task_embeddings
# img_tensors_out = depth_tensors_out
elif read_normal:
task_embeddings = normal_task_embeddings
# img_tensors_out = normal_tensors_out
elif read_mask:
task_embeddings = mask_task_embeddings
# img_tensors_out = depth_tensors_out
else: # for stage 1 training, the input and the output are in the same domain
img_tensors_in = [img_tensors_out[0]] * self.num_views
empty_class = torch.tensor([0, 0]).float() # empty task
empty_task_embeddings = torch.stack([empty_class] * self.num_views, dim=0)
task_embeddings = empty_task_embeddings
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'normals_out': normal_tensors_out,
'depth_out': depth_tensors_out,
'camera_embeddings': camera_embeddings,
'task_embeddings': task_embeddings,
}
def __getitem_mixed__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index%len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), return_type='np')
else:
cond_alpha = None
# img_tensors_in = [
# self.load_image(os.path.join(self.root_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), bg_color, cond_alpha, return_type='pt').permute(2, 0, 1)
# ] * self.num_views
img_tensors_out = []
normal_tensors_out = []
depth_tensors_out = []
random_select = random.random()
read_color, read_normal, read_depth = [random_select < 1 / 3, 1 / 3 <= random_select <= 2 / 3,
random_select > 2 / 3]
# print(read_color, read_normal, read_depth)
assert sum([read_color, read_normal, read_depth]) == 1, "Only one variable should be True"
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type, read_depth=read_depth)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if read_normal:
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "normals_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
img_tensors_out.append(normal_tensor)
if read_depth:
if alpha is None:
alpha = self.load_mask_from_rgba(img_path, camera_type=load_cam_type)
depth_tensor = self.load_depth(depth_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
img_tensors_out.append(depth_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
img_tensors_in = [
self.load_image(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
bg_color, cond_alpha, return_type='pt', camera_type=load_cam_type, read_depth=read_depth).permute(
2, 0, 1)
] * self.num_views
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
# if self.read_color:
# img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
# if self.read_normal:
# normal_tensors_out = torch.stack(normal_tensors_out, dim=0).float() # (Nv, 3, H, W)
# if self.read_depth:
# depth_tensors_out = torch.stack(depth_tensors_out, dim=0).float() # (Nv, 3, H, W)
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
# if self.pred_ortho and self.pred_persp:
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
color_class = torch.tensor([0, 1]).float()
color_task_embeddings = torch.stack([color_class]*self.num_views, dim=0) # (Nv, 2)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class]*self.num_views, dim=0) # (Nv, 2)
depth_class = torch.tensor([1, 1]).float()
depth_task_embeddings = torch.stack([depth_class]*self.num_views, dim=0)
if read_color:
task_embeddings = color_task_embeddings
# img_tensors_out = depth_tensors_out
elif read_normal:
task_embeddings = normal_task_embeddings
# img_tensors_out = normal_tensors_out
elif read_depth:
task_embeddings = depth_task_embeddings
# img_tensors_out = depth_tensors_out
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'normals_out': normal_tensors_out,
'depth_out': depth_tensors_out,
'camera_embeddings': camera_embeddings,
'task_embeddings': task_embeddings,
}
def __getitem_image_normal_mixed__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index%len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
# get crop size for each mv instance:
center_crop_size = 0
for view in view_types:
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
img = Image.open(img_path)
img = img.resize([512,512])
img = np.array(img).astype(np.float32) / 255. # [0, 1]
max_w_h = self.cal_single_view_crop(img)
center_crop_size = max(center_crop_size, max_w_h)
center_crop_size = center_crop_size * 4. / 3.
center_crop_size = center_crop_size + (random.random()-0.5) * 10.
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), return_type='np')
else:
cond_alpha = None
# img_tensors_in = [
# self.load_image(os.path.join(self.root_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), bg_color, cond_alpha, return_type='pt').permute(2, 0, 1)
# ] * self.num_views
img_tensors_out = []
normal_tensors_out = []
depth_tensors_out = []
random_select = random.random()
read_color, read_normal = [random_select < 1 / 2, 1 / 2 <= random_select <= 1]
# print(read_color, read_normal, read_depth)
assert sum([read_color, read_normal]) == 1, "Only one variable should be True"
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type, read_depth=False, center_crop_size=center_crop_size)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if read_normal:
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "normals_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c, return_type="pt", camera_type=load_cam_type, center_crop_size=center_crop_size).permute(2, 0, 1)
img_tensors_out.append(normal_tensor)
# if read_depth:
# if alpha is None:
# alpha = self.load_mask_from_rgba(img_path, camera_type=load_cam_type)
# depth_tensor = self.load_depth(depth_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type).permute(2, 0, 1)
# img_tensors_out.append(depth_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
img_tensors_in = [
self.load_image(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
bg_color, cond_alpha, return_type='pt', camera_type=load_cam_type, read_depth=False, center_crop_size=center_crop_size).permute(
2, 0, 1)
] * self.num_views
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
# if self.read_color:
# img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
# if self.read_normal:
# normal_tensors_out = torch.stack(normal_tensors_out, dim=0).float() # (Nv, 3, H, W)
# if self.read_depth:
# depth_tensors_out = torch.stack(depth_tensors_out, dim=0).float() # (Nv, 3, H, W)
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
# if self.pred_ortho and self.pred_persp:
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
color_class = torch.tensor([0, 1]).float()
color_task_embeddings = torch.stack([color_class]*self.num_views, dim=0) # (Nv, 2)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class]*self.num_views, dim=0) # (Nv, 2)
# depth_class = torch.tensor([1, 1]).float()
# depth_task_embeddings = torch.stack([depth_class]*self.num_views, dim=0)
if read_color:
task_embeddings = color_task_embeddings
# img_tensors_out = depth_tensors_out
elif read_normal:
task_embeddings = normal_task_embeddings
# img_tensors_out = normal_tensors_out
# elif read_depth:
# task_embeddings = depth_task_embeddings
# img_tensors_out = depth_tensors_out
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'normals_out': normal_tensors_out,
'depth_out': depth_tensors_out,
'camera_embeddings': camera_embeddings,
'task_embeddings': task_embeddings,
}
def cal_single_view_crop(self, image):
assert np.shape(image)[-1] == 4 # RGBA
# Extract the alpha channel (transparency) and the object (RGB channels)
alpha_channel = image[:, :, 3]
# Find the bounding box coordinates of the object
coords = cv2.findNonZero(alpha_channel)
x, y, width, height = cv2.boundingRect(coords)
return max(width, height)
def __getitem_joint_rgb_noraml__(self, index, debug_object=None):
if debug_object is not None:
object_name = debug_object #
set_idx = random.sample(range(0, self.groups_num), 1)[0] # without replacement
else:
object_name = self.all_objects[index%len(self.all_objects)]
set_idx = 0
if self.augment_data:
cond_view = random.sample(self.view_types, k=1)[0]
else:
cond_view = 'front'
assert self.pred_ortho or self.pred_persp
if self.pred_ortho and self.pred_persp:
if random.random() < 0.5:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
else:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
elif self.pred_ortho and not self.pred_persp:
load_dir = self.root_dir_ortho
load_cam_type = 'ortho'
elif self.pred_persp and not self.pred_ortho:
load_dir = self.root_dir_persp
load_cam_type = 'persp'
view_types = self.view_types
cond_w2c = self.fix_cam_poses[cond_view]
tgt_w2cs = [self.fix_cam_poses[view] for view in view_types]
elevations = []
azimuths = []
# get the bg color
bg_color = self.get_bg_color()
if self.read_mask:
cond_alpha = self.load_mask(os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, cond_view, self.suffix)), return_type='np')
else:
cond_alpha = None
img_tensors_out = []
normal_tensors_out = []
read_color, read_normal = True, True
# print(read_color, read_normal, read_depth)
# get crop size for each mv instance:
center_crop_size = 0
for view in view_types:
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
img = Image.open(img_path)
img = img.resize([512,512])
img = np.array(img).astype(np.float32) / 255. # [0, 1]
max_w_h = self.cal_single_view_crop(img)
center_crop_size = max(center_crop_size, max_w_h)
center_crop_size = center_crop_size * 4. / 3.
center_crop_size = center_crop_size + (random.random()-0.5) * 10.
for view, tgt_w2c in zip(view_types, tgt_w2cs):
img_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "rgb_%03d_%s.%s" % (set_idx, view, self.suffix))
mask_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "mask_%03d_%s.%s" % (set_idx, view, self.suffix))
depth_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "depth_%03d_%s.%s" % (set_idx, view, self.suffix))
if self.read_mask:
alpha = self.load_mask(mask_path, return_type='np')
else:
alpha = None
if read_color:
img_tensor = self.load_image(img_path, bg_color, alpha, return_type="pt", camera_type=load_cam_type, read_depth=False, center_crop_size=center_crop_size)
img_tensor = img_tensor.permute(2, 0, 1)
img_tensors_out.append(img_tensor)
if read_normal:
normal_path = os.path.join(load_dir, object_name[:self.subscene_tag], object_name, "normals_%03d_%s.%s" % (set_idx, view, self.suffix))
normal_tensor = self.load_normal(normal_path, bg_color, alpha, RT_w2c=tgt_w2c, RT_w2c_cond=cond_w2c, return_type="pt", camera_type=load_cam_type, center_crop_size=center_crop_size).permute(2, 0, 1)
normal_tensors_out.append(normal_tensor)
# evelations, azimuths
elevation, azimuth = self.get_T(tgt_w2c, cond_w2c)
elevations.append(elevation)
azimuths.append(azimuth)
if self.load_switcher: # rgb input, use domain switcher to control the output type
img_tensors_in = [
self.load_image(os.path.join(load_dir, object_name[:self.subscene_tag], object_name,
"rgb_%03d_%s.%s" % (set_idx, cond_view, self.suffix)),
bg_color, cond_alpha, return_type='pt', camera_type=load_cam_type,
read_depth=False, center_crop_size=center_crop_size).permute(
2, 0, 1)
] * self.num_views
color_class = torch.tensor([0, 1]).float()
color_task_embeddings = torch.stack([color_class] * self.num_views, dim=0) # (Nv, 2)
normal_class = torch.tensor([1, 0]).float()
normal_task_embeddings = torch.stack([normal_class] * self.num_views, dim=0) # (Nv, 2)
if read_color:
task_embeddings = color_task_embeddings
# img_tensors_out = depth_tensors_out
elif read_normal:
task_embeddings = normal_task_embeddings
# img_tensors_out = normal_tensors_out
else: # for stage 1 training, the input and the output are in the same domain
img_tensors_in = [img_tensors_out[0]] * self.num_views
empty_class = torch.tensor([0, 0]).float() # empty task
empty_task_embeddings = torch.stack([empty_class] * self.num_views, dim=0)
task_embeddings = empty_task_embeddings
img_tensors_in = torch.stack(img_tensors_in, dim=0).float() # (Nv, 3, H, W)
img_tensors_out = torch.stack(img_tensors_out, dim=0).float() # (Nv, 3, H, W)
normal_tensors_out = torch.stack(normal_tensors_out, dim=0).float() # (Nv, 3, H, W)
elevations = torch.as_tensor(elevations).float().squeeze(1)
azimuths = torch.as_tensor(azimuths).float().squeeze(1)
elevations_cond = torch.as_tensor([0] * self.num_views).float() # fixed only use 4 views to train
if load_cam_type == 'ortho':
cam_type_emb = torch.tensor([0, 1]).expand(self.num_views, -1)
else:
cam_type_emb = torch.tensor([1, 0]).expand(self.num_views, -1)
camera_embeddings = torch.stack([elevations_cond, elevations, azimuths], dim=-1)
if self.load_cam_type:
camera_embeddings = torch.cat((camera_embeddings, cam_type_emb), dim=-1) # (Nv, 5)
return {
'elevations_cond': elevations_cond,
'elevations_cond_deg': torch.rad2deg(elevations_cond),
'elevations': elevations,
'azimuths': azimuths,
'elevations_deg': torch.rad2deg(elevations),
'azimuths_deg': torch.rad2deg(azimuths),
'imgs_in': img_tensors_in,
'imgs_out': img_tensors_out,
'normals_out': normal_tensors_out,
'camera_embeddings': camera_embeddings,
'color_task_embeddings': color_task_embeddings,
'normal_task_embeddings': normal_task_embeddings
}
def __getitem__(self, index):
try:
if self.pred_type == 'color':
data = self.backup_data = self.__getitem_color__(index)
elif self.pred_type == 'normal_depth':
data = self.backup_data = self.__getitem_normal_depth__(index)
elif self.pred_type == 'mixed_rgb_normal_depth':
data = self.backup_data = self.__getitem_mixed__(index)
elif self.pred_type == 'mixed_color_normal':
data = self.backup_data = self.__getitem_image_normal_mixed__(index)
elif self.pred_type == 'mixed_rgb_noraml_mask':
data = self.backup_data = self.__getitem_mixed_rgb_noraml_mask__(index)
elif self.pred_type == 'joint_color_normal':
data = self.backup_data = self.__getitem_joint_rgb_noraml__(index)
return data
except:
print("load error ", self.all_objects[index%len(self.all_objects)])
return self.backup_data
class ConcatDataset(torch.utils.data.Dataset):
def __init__(self, datasets, weights):
self.datasets = datasets
self.weights = weights
self.num_datasets = len(datasets)
def __getitem__(self, i):
chosen = random.choices(self.datasets, self.weights, k=1)[0]
return chosen[i]
def __len__(self):
return max(len(d) for d in self.datasets)
if __name__ == "__main__":
train_dataset = ObjaverseDataset(
root_dir="/ghome/l5/xxlong/.objaverse/hf-objaverse-v1/renderings",
size=(128, 128),
ext="hdf5",
default_trans=torch.zeros(3),
return_paths=False,
total_view=8,
validation=False,
object_list=None,
views_mode='fourviews'
)
data0 = train_dataset[0]
data1 = train_dataset[50]
# print(data)
|