text
stringlengths
1
93.6k
s.close()
# Run
main()
# <FILESEP>
import numpy as np
import os
import argparse
import pickle
import torch
import copy
import cc3d
import cv2
from skimage.morphology import skeletonize, remove_small_holes
def read_pickle(pkl_path):
with open(pkl_path, 'rb') as f:
return pickle.load(f)
# borrowed from SAM3D
def num_to_natural(group_ids):
'''
Change the group number to natural number arrangement
'''
if np.all(group_ids == -1):
return group_ids
array = copy.deepcopy(group_ids)
unique_values = np.unique(array[array != -1])
mapping = np.full(np.max(unique_values) + 2, -1)
mapping[unique_values + 1] = np.arange(len(unique_values))
array = mapping[array + 1]
return array
def remove_small_group(group_ids, th):
fg_areas = np.sum(group_ids > -1)
unique_elements, counts = np.unique(group_ids, return_counts=True)
result = group_ids.copy()
for i, count in enumerate(counts):
# if count <= th:
if count / fg_areas <= th:
result[group_ids == unique_elements[i]] = -1
return result
def get_3d_points(K_, pose, pixs, deps):
# partly borrowed from Syncdreamer
# 1,h*w,3 @ 1,3,3 => 1,h*w,3
points = pixs @ torch.inverse(K_).permute(0, 2, 1)
# 1,h*w,3 @ 1,hw,1 => 1,h*w,3
points = points * deps
hw = points.shape[1]
points = torch.cat([points, torch.ones(1, hw, 1, dtype=torch.float32)], 2) # 1,h*w,4
# 1,h*w,4 @ 1,4,4 => 1,h*w,4
pose_ = pose.unsqueeze(0).permute(0, 2, 1)
points = points @ pose_
return points[...,:3]
def get_2d_pixels(K_, pose, pts):
# 1,h*w,4 @ 1,4,4 => 1,h*w,4
pose_ = torch.inverse(pose).unsqueeze(0).permute(0, 2, 1)
hw = pts.shape[1]
pts_ = torch.cat([pts, torch.ones(1, hw, 1, dtype=torch.float32)], 2)
points = pts_ @ pose_
# 1,h*w,3 @ 1,3,3 => 1,h*w,3
pixs = points[...,:3] @ K_.permute(0, 2, 1)
depth_ = pixs[0, :, 2]
pixs[..., :2] = pixs[..., :2] / pixs[..., 2:]
return pixs[..., :2], depth_ # 1,h*w,2, h*w,
def sam_mask_preprocess(sam_, alpha_map, th):
sam_ = num_to_natural(sam_) # remove index with no exact pixels, caused by sam mask overlapping
# detect disconnected parts to remove noisy small pixel groups
labs_connected = cc3d.connected_components(sam_ + 1)
sam_new = -1 * np.ones_like(sam_)
extra_ind = np.max(sam_)+1
for idp in range(np.min(sam_), np.max(sam_)+1):
cur_map = labs_connected[sam_==idp]
unique_values = np.unique(cur_map)
unique_nums = np.bincount(cur_map)
if len(unique_values) == 1:
sam_new[sam_==idp] = idp
elif len(unique_values) > 1 and np.max(unique_nums) > 19:
for ide in range(len(unique_values)):
if unique_nums[unique_values[ide]] > 19:
sam_new[labs_connected==unique_values[ide]] = extra_ind
extra_ind += 1
bg_maskid = np.unique(sam_new[alpha_map < 0.95])
for idm in range(bg_maskid.shape[0]):
if 0.9*np.sum(sam_new==bg_maskid[idm]) < np.sum(sam_new[alpha_map < 0.95]==bg_maskid[idm]):
sam_new[sam_new==bg_maskid[idm]] = -1
sam_new[alpha_map < 0.95] = -1 # set background as invalid mask
sam_new = remove_small_group(sam_new, th)
sam_new = num_to_natural(sam_new)
return sam_new