Spaces:
Sleeping
Sleeping
File size: 12,016 Bytes
5b557cf | 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 | import numpy as np
import torch
from torch_geometric.nn import knn
from torch_geometric.data import Data
from torch_geometric.nn import radius_graph, knn_graph
import graph_helpers as gh
import sphere_helpers as sh
import mesh_helpers as mh
import clusters as cl
import utils
from torch_scatter import scatter
import math
from math import pi, sqrt
from warnings import warn
def image2Graph(data, gt = None, mask = None, depth = 1, x_only = False, device = 'cpu'):
_,ch,rows,cols = data.shape
x = torch.reshape(data,(ch,rows*cols)).permute((1,0)).to(device)
if mask is not None:
# Mask out nodes
node_mask = torch.where(mask.flatten())
x = x[node_mask]
if gt is not None:
y = gt.flatten().to(device)
if mask is not None:
y = y[node_mask]
if x_only:
if gt is not None:
return x,y
else:
return x
im_pos = gh.getImPos(rows,cols)
if mask is not None:
im_pos = im_pos[node_mask]
# Make "point cloud" for clustering
pos2D = gh.convertImPos(im_pos,flip_y=False)
# Generate initial graph
edge_index = gh.grid2Edges(pos2D)
directions = pos2D[edge_index[1]] - pos2D[edge_index[0]]
selections = gh.edges2Selections(edge_index,directions,interpolated=False,y_down=True)
# Generate info for downsampled versions of the graph
clusters, edge_indexes, selections_list = cl.makeImageClusters(pos2D,cols,rows,edge_index,selections,depth=depth,device=device)
# Make final graph and metadata needed for mapping the result after going through the network
graph = Data(x=x,clusters=clusters,edge_indexes=edge_indexes,selections_list=selections_list,interps_list=None)
metadata = Data(original=data,im_pos=im_pos.long(),rows=rows,cols=cols,ch=ch)
if gt is not None:
graph.y = y
return graph,metadata
def graph2Image(result,metadata,canvas=None):
x = utils.toNumpy(result,permute=False)
im_pos = utils.toNumpy(metadata.im_pos,permute=False)
if canvas is None:
canvas = utils.makeCanvas(x,metadata.original)
# Paint over the original image (neccesary for masked images)
canvas[im_pos[:,0],im_pos[:,1]] = x
return canvas
### Begin Interpolated Methods ###
def sphere2Graph(data, structure="layering", cluster_method="layering", scale=1.0, stride=2, interpolation_mode = "angle", gt = None, mask = None, depth = 1, x_only = False, device = 'cpu'):
_,ch,rows,cols = data.shape
if structure == "equirec":
# Use the original data to start with
cartesian, spherical = sh.sampleSphere_Equirec(scale*rows,scale*cols)
elif structure == "layering":
cartesian, spherical = sh.sampleSphere_Layering(scale*rows)
elif structure == "spiral":
cartesian, spherical = sh.sampleSphere_Spiral(scale*rows,scale*cols)
elif structure == "icosphere":
cartesian, spherical = sh.sampleSphere_Icosphere(scale*rows)
elif structure == "random":
cartesian, spherical = sh.sampleSphere_Random(scale*rows,scale*cols)
else:
raise ValueError("Sphere structure unknown")
if interpolation_mode == "bary":
bary_d = pi/(scale*rows)
else:
bary_d = None
# Get the landing point for each node
sample_x, sample_y = sh.spherical2equirec(spherical[:,0],spherical[:,1],rows,cols)
if mask is not None:
node_mask = gh.maskPoints(mask,sample_x,sample_y)
sample_x = sample_x[node_mask]
sample_y = sample_y[node_mask]
spherical = spherical[node_mask]
cartesian = cartesian[node_mask]
features = utils.bilinear_interpolate(data, sample_x, sample_y).to(device)
if gt is not None:
features_y = utils.bilinear_interpolate(gt.unsqueeze(0), sample_x, sample_y).to(device)
if x_only:
if gt is not None:
return features,features_y
else:
return features
# Build initial graph
edge_index,directions = gh.surface2Edges(cartesian,cartesian)
edge_index,selections,interps = gh.edges2Selections(edge_index,directions,interpolated=True,bary_d=bary_d)
# Generate info for downsampled versions of the graph
clusters, edge_indexes, selections_list, interps_list = cl.makeSphereClusters(cartesian,edge_index,selections,interps,rows*scale,cols*scale,cluster_method,stride=stride,bary_d=bary_d,depth=depth,device=device)
# Make final graph and metadata needed for mapping the result after going through the network
graph = Data(x=features,clusters=clusters,edge_indexes=edge_indexes,selections_list=selections_list,interps_list=interps_list)
metadata = Data(original=data,pos3D=cartesian,mask=mask,rows=rows,cols=cols,ch=ch)
if gt is not None:
graph.y = features_y
return graph, metadata
def graph2Sphere(features,metadata):
# Generate equirectangular points and their 3D locations
theta, phi = sh.equirec2spherical(metadata.rows, metadata.cols)
x,y,z = sh.spherical2xyz(theta,phi)
v = torch.stack((x,y,z),dim=1)
# Find closest 3D point to each equirectangular point
nearest = torch.reshape(knn(metadata.pos3D,v,3)[1],(len(v),3))
#Interpolate based on proximty to each node
w0 = 1/torch.linalg.norm((v - metadata.pos3D[nearest[:,0]]),dim=1, keepdim=True).to(features.device)
w1 = 1/torch.linalg.norm((v - metadata.pos3D[nearest[:,1]]),dim=1, keepdim=True).to(features.device)
w2 = 1/torch.linalg.norm((v - metadata.pos3D[nearest[:,2]]),dim=1, keepdim=True).to(features.device)
w0 = torch.nan_to_num(w0, nan=1e6)
w1 = torch.nan_to_num(w1, nan=1e6)
w2 = torch.nan_to_num(w2, nan=1e6)
w0 = torch.clamp(w0,0,1e6)
w1 = torch.clamp(w1,0,1e6)
w2 = torch.clamp(w2,0,1e6)
total = w0 + w1 + w2
#w0,w1,w2 = mh.getBarycentricWeights(v,metadata.pos3D[nearest[:,0]],metadata.pos3D[nearest[:,1]],metadata.pos3D[nearest[:,2]])
#w0 = w0.unsqueeze(1).to(features.device)
#w1 = w1.unsqueeze(1).to(features.device)
#w2 = w2.unsqueeze(1).to(features.device)
result = (w0*features[nearest[:,0]] + w1*features[nearest[:,1]] + w2*features[nearest[:,2]])/total
#result = result.clamp(0,1)
if hasattr(metadata,"mask"):
mask = utils.toNumpy(metadata.mask.squeeze(),permute=False)
canvas = utils.makeCanvas(result,metadata.original)
result = np.reshape(result.data.cpu().numpy(),(metadata.rows,metadata.cols,features.shape[1]))
canvas[np.where(mask)] = result[np.where(mask)]
return canvas
else:
return np.reshape(result.data.cpu().numpy(),(metadata.rows,metadata.cols,features.shape[1]))
def splat2Graph(data, mesh, up_vector = None, N = 100000, ratio=.25, depth = 1, device = 'cpu'):
""" Sample mesh faces to determine graph """
if up_vector == None:
up_vector = torch.tensor([[1,1,1]],dtype=torch.float)
#up_vector = 2*torch.rand((1,3))-1
up_vector = up_vector/torch.linalg.norm(up_vector,dim=1)
#position, normal vector, uv coordinates in the texture map, x is color
pos3D, normals = mh.sampleSurface(mesh,N)
# Build initial graph
#edge_index are neighbors of a point, directions are the directions from that point
edge_index,directions = gh.surface2Edges(pos3D,normals,up_vector,k_neighbors=16)
#directions need to be turned into selections "W sub n" from the star-like coordinate system from Dr. Hart's github interpolated-selectionconv
edge_index,selections,interps = gh.edges2Selections(edge_index,directions,interpolated=True)
# Generate info for downsampled versions of the graph
clusters, edge_indexes, selections_list, interps_list = cl.makeSurfaceClusters(pos3D,normals,edge_index,selections,interps,ratio=ratio,up_vector=up_vector,depth=depth,device=device)
#clusters, edge_indexes, selections_list, interps_list = cl.makeMeshClusters(pos3D,mesh,edge_index,selections,interps,ratio=ratio,up_vector=up_vector,depth=depth,device=device)
# Make final graph and metadata needed for mapping the result after going through the network
graph = Data(clusters=clusters,edge_indexes=edge_indexes,selections_list=selections_list,interps_list=interps_list)
metadata = Data(original=data,pos3D=pos3D,mesh=mesh)
return graph,metadata
def mesh2Graph(data, mesh, up_vector = None, N = 100000, ratio=.25, mask = None, depth = 1, x_only = False, device = 'cpu'):
""" Sample mesh faces to determine graph """
if up_vector == None:
up_vector = torch.tensor([[1,1,1]],dtype=torch.float)
#up_vector = 2*torch.rand((1,3))-1
up_vector = up_vector/torch.linalg.norm(up_vector,dim=1)
if mask is not None:
warn("Masks are not currently implemented for mesh graphs")
#position, normal vector, uv coordinates in the texture map, x is color
pos3D, normals, uvs, x = mh.sampleSurface(mesh,N,return_x=True)
x = x.to(device)
if x_only:
warn("x_only returns randomly selected points for mesh2Graph. Do not use with previous graph structures")
return x
# Build initial graph
#edge_index are neighbors of a point, directions are the directions from that point
edge_index,directions = gh.surface2Edges(pos3D,normals,up_vector,k_neighbors=16)
#directions need to be turned into selections "W sub n" from the star-like coordinate system from Dr. Hart's github interpolated-selectionconv
edge_index,selections,interps = gh.edges2Selections(edge_index,directions,interpolated=True)
# Generate info for downsampled versions of the graph
clusters, edge_indexes, selections_list, interps_list = cl.makeSurfaceClusters(pos3D,normals,edge_index,selections,interps,ratio=ratio,up_vector=up_vector,depth=depth,device=device)
#clusters, edge_indexes, selections_list, interps_list = cl.makeMeshClusters(pos3D,mesh,edge_index,selections,interps,ratio=ratio,up_vector=up_vector,depth=depth,device=device)
# Make final graph and metadata needed for mapping the result after going through the network
graph = Data(x=x,clusters=clusters,edge_indexes=edge_indexes,selections_list=selections_list,interps_list=interps_list)
metadata = Data(original=data,pos3D=pos3D,uvs=uvs,mesh=mesh)
return graph,metadata
def graph2Splat(features,metadata,view3D=False):
features = features.cpu().numpy()
canvas = utils.toNumpy(metadata.original)
rows,cols,ch = canvas.shape
# Get 2D positions by scaling uv
pos2D = metadata.uvs.cpu().numpy()
pos2D[:,0] = pos2D[:,0]*cols
pos2D[:,1] = 1-pos2D[:,1] # UV puts y=0 at the bottom
pos2D[:,1] = pos2D[:,1]*rows
# Generate desired points
row_space = np.arange(rows)
col_space = np.arange(cols)
col_image,row_image = np.meshgrid(col_space,row_space)
canvas = utils.interpolatePointCloud2D(pos2D,features,col_image,row_image)
canvas = np.clip(canvas,0,1)
if view3D:
mesh = mh.setTexture(metadata.mesh,canvas)
mesh.show()
return canvas
def graph2Mesh(features,metadata,view3D=False):
features = features.cpu().numpy()
canvas = utils.toNumpy(metadata.original)
rows,cols,ch = canvas.shape
# Get 2D positions by scaling uv
pos2D = metadata.uvs.cpu().numpy()
pos2D[:,0] = pos2D[:,0]*cols
pos2D[:,1] = 1-pos2D[:,1] # UV puts y=0 at the bottom
pos2D[:,1] = pos2D[:,1]*rows
# Generate desired points
row_space = np.arange(rows)
col_space = np.arange(cols)
col_image,row_image = np.meshgrid(col_space,row_space)
canvas = utils.interpolatePointCloud2D(pos2D,features,col_image,row_image)
canvas = np.clip(canvas,0,1)
if view3D:
mesh = mh.setTexture(metadata.mesh,canvas)
mesh.show()
return canvas
|