repo_name
stringclasses
6 values
pr_number
int64
99
20.3k
pr_title
stringlengths
8
158
pr_description
stringlengths
0
6.54k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
37
6.57k
filepath
stringlengths
8
153
before_content
stringlengths
0
876M
after_content
stringlengths
0
876M
label
int64
-1
1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/camera/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/projects/local_implicit_grid/core/evaluator.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Utility modules for evaluating model from checkpoint. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile from tensorflow_graphics.projects.local_implicit_grid.core import implicit_nets as im from tensorflow_graphics.projects.local_implicit_grid.core import local_implicit_grid_layer as lig from tensorflow_graphics.projects.local_implicit_grid.core import model_g2g as g2g from tensorflow_graphics.projects.local_implicit_grid.core import model_g2v as g2v tf.logging.set_verbosity(tf.logging.ERROR) def parse_param_file(param_file): """Parse parameter file for parameters.""" with gfile.GFile(param_file, 'r') as fh: lines = fh.readlines() d = {} for l in lines: l = l.rstrip('\n') splits = l.split(':') key = splits[0] val_ = splits[1].strip() if not val_: val = '' else: try: val = ast.literal_eval(val_) except (ValueError, SyntaxError): val = str(val_) d[key] = val return d class RefinerEvaluator(object): """Load pretrained refiner and evaluate for a given code. """ def __init__(self, ckpt, codelen, dim=3, out_features=1, num_filters=128, point_batch=20000): self.ckpt = ckpt self.codelen = codelen self.dim = dim self.out_features = out_features self.num_filters = num_filters self.point_batch = point_batch self.graph = tf.Graph() self._init_graph() self.global_step_ = self.global_step.eval(session=self.sess) def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.refiner = im.ImNet(dim=self.dim, in_features=self.codelen, out_features=self.out_features, num_filters=self.num_filters) self.global_step = tf.get_variable('global_step', shape=[], dtype=tf.int64) self.pts_ph = tf.placeholder(tf.float32, shape=[self.point_batch, 3]) self.lat_ph = tf.placeholder(tf.float32, shape=[self.codelen]) lat = tf.broadcast_to(self.lat_ph[tf.newaxis], [self.point_batch, self.codelen]) code = tf.concat((self.pts_ph, lat), axis=-1) # [pb, 3+c] vals = self.refiner(code, training=False) # [pb, 1] self.vals = tf.squeeze(vals, axis=1) # [pb] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _get_grid_points(self, xmin, xmax, res): x = np.linspace(xmin, xmax, res) xyz = np.meshgrid(*tuple([x] * self.dim), indexing='ij') xyz = np.stack(xyz, axis=-1) xyz = xyz.reshape([-1, self.dim]) return xyz def eval_points(self, lat, points): """Evaluate network at locations specified by points. Args: lat: [self.codelen,] np array, latent code. points: [#v, self.dim] np array, point locations to evaluate. Returns: all_vals: [#v] np array, function values at locations. """ npt = points.shape[0] npb = int(np.ceil(float(npt)/self.point_batch)) all_vals = np.zeros([npt], dtype=np.float32) for idx in range(npb): sid = int(idx * self.point_batch) eid = int(min(npt, sid+self.point_batch)) pts = points[sid:eid] pad_w = self.point_batch - (eid - sid) pts = np.pad(pts, ((0, pad_w), (0, 0)), mode='constant') with self.graph.as_default(): val = self.sess.run(self.vals, feed_dict={self.pts_ph: pts, self.lat_ph: lat}) all_vals[sid:eid] = val[:(eid-sid)] return all_vals def eval_grid(self, lat, xmin=-1.0, xmax=1.0, res=64): """Evaluate network on a grid. Args: lat: [self.codelen,] np array, latent code. xmin: float, minimum coordinate value for grid. xmax: float, maximum coordinate value for grid. res: int, resolution (per dimension) of grid. Returns: grid_val: [res, res, res] np.float32 array, grid of values from query. """ grid_points = self._get_grid_points(xmin=xmin, xmax=xmax, res=res) point_val = self.eval_points(lat, grid_points) grid_val = point_val.reshape([res, res, res]) return grid_val class EncoderEvaluator(object): """Load pretrained grid encoder and evaluate single crops.""" def __init__(self, ckpt, in_grid_res=32, encoder_nf=32, codelen=32, grid_batch=128): """Initialization function. Args: ckpt: str, path to checkpoint. in_grid_res: int, resolution of grid to feed to encoder. encoder_nf: int, number of base filters for encoder. codelen: int, length of output latent code. grid_batch: int, batch size of cut-out grid to evaluate at a time. """ self.ckpt = ckpt self.codelen = codelen self.grid_batch = grid_batch self.in_grid_res = in_grid_res self.encoder_nf = encoder_nf self.graph = tf.Graph() self._init_graph() # creates self.sess def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.encoder = g2v.GridEncoder(in_grid_res=self.in_grid_res, num_filters=self.encoder_nf, codelen=self.codelen, name='g2v') self.grid_ph = tf.placeholder( tf.float32, shape=[None, self.in_grid_res, self.in_grid_res, self.in_grid_res, 1]) self.lats = self.encoder(self.grid_ph, training=False) # [gb, codelen] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def eval_grid(self, grid): """Strided evaluation of full grid into feature grid. Args: grid: [batch, gres, gres, gres, 1] input feature grid. Returns: codes: [batch, codelen] output feature gird. """ # initialize output feature grid niters = int(np.ceil(grid.shape[0] / self.grid_batch)) codes = [] for idx in range(niters): sid = idx * self.grid_batch eid = min(sid+self.grid_batch, grid.shape[0]) c = self.sess.run(self.lats, feed_dict={self.grid_ph: grid[sid:eid]}) codes.append(c) codes = np.concatenate(codes, axis=0) return codes.astype(np.float32) class FullGridEncoderEvaluator(object): """Load pretrained grid encoder and evaluate a full input grid. Performs windowed encoding and outputs an encoded feature grid. """ def __init__(self, ckpt, in_grid_res=32, num_filters=32, codelen=128, grid_batch=128, gres=256, overlap=True): """Initialization function. Args: ckpt: str, path to checkpoint. in_grid_res: int, resolution of grid to feed to encoder. num_filters: int, number of base filters for encoder. codelen: int, length of output latent code. grid_batch: int, batch size of cut-out grid to evaluate at a time. gres: int, resolution of the full grid. overlap: bool, whether to do overlapping or non-overlapping cutout evaluations. """ self.ckpt = ckpt self.codelen = codelen self.grid_batch = grid_batch self.in_grid_res = in_grid_res self.gres = gres self.num_filters = num_filters self.graph = tf.Graph() self._init_graph() self.global_step_ = self.global_step.eval(session=self.sess) if overlap: ijk = np.arange(0, gres-int(in_grid_res/2), int(in_grid_res/2)) self.out_grid_res = ijk.shape[0] else: ijk = np.arange(0, gres, in_grid_res) self.out_grid_res = ijk.shape[0] self.ijk = np.meshgrid(ijk, ijk, ijk, indexing='ij') self.ijk = np.stack(self.ijk, axis=-1).reshape([-1, 3]) def _init_graph(self): """Initialize computation graph for tensorflow.""" with self.graph.as_default(): self.encoder = g2v.GridEncoder( in_grid_res=self.in_grid_res, num_filters=self.num_filters, codelen=self.codelen, name='g2v') self.global_step = tf.get_variable( 'global_step', shape=[], dtype=tf.int64) self.grid_ph = tf.placeholder( tf.float32, shape=[self.gres, self.gres, self.gres]) self.start_ph = tf.placeholder(tf.int32, shape=[self.grid_batch, 3]) self.ingrid = self._batch_slice(self.grid_ph, self.start_ph, self.in_grid_res, self.grid_batch) self.ingrid = self.ingrid[..., tf.newaxis] self.lats = self.encoder(self.ingrid, training=False) # [gb, codelen] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _batch_slice(self, ary, start_ijk, w, batch_size): """Batched slicing of original grid. Args: ary: tensor, rank = 3. start_ijk: [batch_size, 3] tensor, starting index. w: width of cube to extract. batch_size: int, batch size. Returns: batched_slices: [batch_size, w, w, w] tensor, batched slices of ary. """ batch_size = start_ijk.shape[0] ijk = tf.range(w, dtype=tf.int32) slice_idx = tf.meshgrid(ijk, ijk, ijk, indexing='ij') slice_idx = tf.stack( slice_idx, axis=-1) # [in_grid_res, in_grid_res, in_grid_res, 3] slice_idx = tf.broadcast_to(slice_idx[tf.newaxis], [batch_size, w, w, w, 3]) offset = tf.broadcast_to( start_ijk[:, tf.newaxis, tf.newaxis, tf.newaxis, :], [batch_size, w, w, w, 3]) slice_idx += offset # [batch_size, in_grid_res, in_grid_res, in_grid_res, 3] batched_slices = tf.gather_nd(ary, slice_idx) # [batch_size, in_grid_res, in_grid_res, in_grid_res] return batched_slices def eval_grid(self, grid): """Strided evaluation of full grid into feature grid. Args: grid: [gres, gres, gres] input feature grid. Returns: ogrid: [out_grid_res, out_grid_res, out_grid_res, codelen] output feature gird. """ # initialize output feature grid ogrid = np.zeros([self.ijk.shape[0], self.codelen]) niters = np.ceil(self.ijk.shape[0] / self.grid_batch).astype(np.int) for idx in range(niters): sid = idx * self.grid_batch eid = min(sid + self.grid_batch, self.ijk.shape[0]) start_ijk = self.ijk[sid:eid] # pad if last iteration does not have a full batch pad_w = self.grid_batch - start_ijk.shape[0] start_ijk = np.pad(start_ijk, ((0, pad_w), (0, 0)), mode='constant') lats = self.sess.run( self.lats, feed_dict={ self.grid_ph: grid, self.start_ph: start_ijk }) ogrid[sid:eid] = lats[:eid - sid] ogrid = ogrid.reshape( [self.out_grid_res, self.out_grid_res, self.out_grid_res, self.codelen]) return ogrid.astype(np.float32) class LIGEvaluator(object): """Load pretrained grid refiner and evaluate a feature grid. """ def __init__(self, ckpt, size=(15, 15, 15), in_features=32, out_features=1, x_location_max=1, num_filters=32, min_grid_value=(0., 0., 0.), max_grid_value=(1., 1., 1.), net_type='imnet', method='linear', point_batch=20000, scope=''): """Initialization function. Args: ckpt: str, path to checkpoint. size: list or tuple of ints, grid dimension in each dimension. in_features: int, number of input channels. out_features: int, number of output channels. x_location_max: float, relative coordinate range for one voxel. num_filters: int, number of filters for refiner. min_grid_value: tuple, lower bound of query points. max_grid_value: tuple, upper bound of query points. net_type: str, one of occnet/deepsdf. method: str, one of linear/nn. point_batch: int, pseudo batch size for evaluating points. scope: str, scope of imnet layer. """ self.dim = 3 # hardcode for dim = 3 self.ckpt = ckpt self.size = size self.x_location_max = x_location_max self.num_filters = num_filters self.in_features = in_features self.out_features = out_features self.net_type = net_type self.method = method self.point_batch = point_batch self.scope = scope self.min_grid_value = min_grid_value self.max_grid_value = max_grid_value self.graph = tf.Graph() self._init_graph() def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.lig = lig.LocalImplicitGrid(size=self.size, in_features=self.in_features, out_features=self.out_features, num_filters=self.num_filters, net_type=self.net_type, method=self.method, x_location_max=self.x_location_max, min_grid_value=self.min_grid_value, max_grid_value=self.max_grid_value, name='lig') self.pts_ph = tf.placeholder(tf.float32, shape=[self.point_batch, 3]) self.latgrid_ph = tf.placeholder(tf.float32, shape=[self.size[0], self.size[1], self.size[2], self.in_features]) self.latgrid = self.latgrid_ph[tf.newaxis] self.points = self.pts_ph[tf.newaxis] vals = self.lig(self.latgrid, self.points, training=False) # [1,npts,1] self.vals = tf.squeeze(vals, axis=[0, 2]) # [npts] self.map_dict = self._get_var_mapping(model=self.lig) self.saver = tf.train.Saver(self.map_dict) self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _get_grid_points(self, xmin, xmax, res): x = np.linspace(xmin, xmax, res) xyz = np.meshgrid(*tuple([x] * self.dim), indexing='ij') xyz = np.stack(xyz, axis=-1) xyz = xyz.reshape([-1, self.dim]) return xyz def eval_points(self, latgrid, points): """Evaluate network at locations specified by points. Args: latgrid: [size0, size1, size2, self.codelen] np array, latent code. points: [#v, self.dim] np array, point locations to evaluate. Returns: all_vals: [#v] np array, function values at locations. """ npt = points.shape[0] npb = int(np.ceil(float(npt)/self.point_batch)) all_vals = np.zeros([npt], dtype=np.float32) for idx in range(npb): sid = int(idx * self.point_batch) eid = int(min(npt, sid+self.point_batch)) pts = points[sid:eid] pad_w = self.point_batch - (eid - sid) if pts.shape[0] < self.point_batch: pts_pad = np.tile(pts[0:1], (pad_w, 1)) # repeat the first point in the batch pts = np.concatenate([pts, pts_pad], axis=0) with self.graph.as_default(): val = self.sess.run(self.vals, feed_dict={self.pts_ph: pts, self.latgrid_ph: latgrid}) all_vals[sid:eid] = val[:(eid-sid)] return all_vals def eval_grid(self, latgrid, xmin=0.0, xmax=1.0, res=128): """Evaluate network on a grid. Args: latgrid: [size0, size1, size2, self.codelen] np array, latent code. xmin: float, minimum coordinate value for grid. xmax: float, maximum coordinate value for grid. res: int, resolution (per dimension) of grid. Returns: grid_val: [res, res, res] np.float32 array, grid of values from query. """ grid_points = self._get_grid_points(xmin=xmin, xmax=xmax, res=res) point_val = self.eval_points(latgrid, grid_points) grid_val = point_val.reshape([res, res, res]) return grid_val def _get_var_mapping(self, model): vars_ = model.trainable_variables varnames = [v.name for v in vars_] # .split(':')[0] varnames = [self.scope+v.replace('lig/', '').strip(':0') for v in varnames] map_dict = dict(zip(varnames, vars_)) return map_dict class UNetEvaluator(object): """Load pretrained UNet for generating feature grid for coarse voxel inputs.""" def __init__(self, ckpt, in_grid_res, out_grid_res, num_filters, max_filters, out_features, sph_norm=0.): self.ckpt = ckpt self.in_grid_res = in_grid_res self.out_grid_res = out_grid_res self.num_filters = num_filters self.max_filters = max_filters self.out_features = out_features self.sph_norm = sph_norm self.graph = tf.Graph() self._init_graph() def _init_graph(self): """Initialize computation graph for tensorflow.""" with self.graph.as_default(): self.unet = g2g.UNet3D(in_grid_res=self.in_grid_res, out_grid_res=self.out_grid_res, num_filters=self.num_filters, max_filters=self.max_filters, out_features=self.out_features) self.input_grid_ph = tf.placeholder( tf.float32, [None, None, None]) self.input_grid = self.input_grid_ph[tf.newaxis, ..., tf.newaxis] self.feat_grid = self.unet(self.input_grid) self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def eval_grid(self, input_grid): """Evaluate input grid (no batching). Args: input_grid: [in_grid_res, in_grid_res, in_grid_res] tensor. Returns: [out_grid_res, out_grid_res, out_grid_res, out_features] """ with self.graph.as_default(): feat_grid = self.sess.run(self.feat_grid, feed_dict={self.input_grid_ph: input_grid}) feat_grid = feat_grid[0] if self.sph_norm > 0: feat_grid = (feat_grid / np.linalg.norm(feat_grid, axis=-1, keepdims=True) * self.sph_norm) return feat_grid class SparseLIGEvaluator(object): """Evaluate sparse encoded feature grids.""" def __init__(self, ckpt, num_filters, codelen, origin, grid_shape, part_size, overlap=True, scope=''): self.scope = scope self.overlap = overlap self.ckpt = ckpt self.num_filters = num_filters self.codelen = codelen if overlap: self.res = (np.array(grid_shape) - 1) / 2.0 else: self.res = np.array(grid_shape) - 1 self.res = self.res.astype(np.int32) self.xmin = np.array(origin) self.xmax = self.xmin + self.res * part_size self.part_size = part_size self.lvg = LIGEvaluator(ckpt=ckpt, size=grid_shape, in_features=codelen, out_features=1, x_location_max=2-float(overlap), num_filters=num_filters, min_grid_value=self.xmin, max_grid_value=self.xmax, net_type='imnet', method='linear' if overlap else 'nn', scope=scope) def evaluate_feature_grid(self, feature_grid, mask, res_per_part=4, conservative=False): """Evaluate feature grid. Args: feature_grid: [*grid_size, codelen] np.array, feature grid to evaluate. mask: [*grid_size] bool np.array, mask for feature locations. res_per_part: int, resolution of output evaluation per part. conservative: bool, whether to do conservative evaluations. If true, evalutes a cell if either neighbor is masked. Else, evaluates a cell if all neighbors are masked. Returns: output grid. """ # setup grid eps = 1e-6 s = self.res l = [np.linspace(self.xmin[i]+eps, self.xmax[i]-eps, res_per_part*s[i]) for i in range(3)] xyz = np.stack(np.meshgrid(l[0], l[1], l[2], indexing='ij'), axis=-1).reshape(-1, 3) output_grid = np.ones([res_per_part*s[0], res_per_part*s[1], res_per_part*s[2]], dtype=np.float32).reshape(-1) mask = mask.astype(np.bool) if self.overlap: mask = np.stack([mask[:-1, :-1, :-1], mask[:-1, :-1, 1:], mask[:-1, 1:, :-1], mask[:-1, 1:, 1:], mask[1:, :-1, :-1], mask[1:, :-1, 1:], mask[1:, 1:, :-1], mask[1:, 1:, 1:]], axis=-1) if conservative: mask = np.any(mask, axis=-1) else: mask = np.all(mask, axis=-1) g = np.stack(np.meshgrid(np.arange(mask.shape[0]), np.arange(mask.shape[1]), np.arange(mask.shape[2]), indexing='ij'), axis=-1).reshape(-1, 3) g = g[:, 0]*(mask.shape[1]*mask.shape[2]) + g[:, 1]*mask.shape[2] + g[:, 2] g_valid = g[mask.ravel()] if self.overlap: ijk = np.floor((xyz - self.xmin) / self.part_size * 2).astype(np.int32) else: ijk = np.floor((xyz - self.xmin + 0.5 * self.part_size) / self.part_size).astype(np.int32) ijk_idx = (ijk[:, 0]*(mask.shape[1] * mask.shape[2]) + ijk[:, 1]*mask.shape[2] + ijk[:, 2]) pt_mask = np.isin(ijk_idx, g_valid) output_grid[pt_mask] = self.lvg.eval_points(feature_grid, xyz[pt_mask]) output_grid = output_grid.reshape(res_per_part*s[0], # pylint: disable=too-many-function-args res_per_part*s[1], res_per_part*s[2]) return output_grid
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Utility modules for evaluating model from checkpoint. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.io import gfile from tensorflow_graphics.projects.local_implicit_grid.core import implicit_nets as im from tensorflow_graphics.projects.local_implicit_grid.core import local_implicit_grid_layer as lig from tensorflow_graphics.projects.local_implicit_grid.core import model_g2g as g2g from tensorflow_graphics.projects.local_implicit_grid.core import model_g2v as g2v tf.logging.set_verbosity(tf.logging.ERROR) def parse_param_file(param_file): """Parse parameter file for parameters.""" with gfile.GFile(param_file, 'r') as fh: lines = fh.readlines() d = {} for l in lines: l = l.rstrip('\n') splits = l.split(':') key = splits[0] val_ = splits[1].strip() if not val_: val = '' else: try: val = ast.literal_eval(val_) except (ValueError, SyntaxError): val = str(val_) d[key] = val return d class RefinerEvaluator(object): """Load pretrained refiner and evaluate for a given code. """ def __init__(self, ckpt, codelen, dim=3, out_features=1, num_filters=128, point_batch=20000): self.ckpt = ckpt self.codelen = codelen self.dim = dim self.out_features = out_features self.num_filters = num_filters self.point_batch = point_batch self.graph = tf.Graph() self._init_graph() self.global_step_ = self.global_step.eval(session=self.sess) def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.refiner = im.ImNet(dim=self.dim, in_features=self.codelen, out_features=self.out_features, num_filters=self.num_filters) self.global_step = tf.get_variable('global_step', shape=[], dtype=tf.int64) self.pts_ph = tf.placeholder(tf.float32, shape=[self.point_batch, 3]) self.lat_ph = tf.placeholder(tf.float32, shape=[self.codelen]) lat = tf.broadcast_to(self.lat_ph[tf.newaxis], [self.point_batch, self.codelen]) code = tf.concat((self.pts_ph, lat), axis=-1) # [pb, 3+c] vals = self.refiner(code, training=False) # [pb, 1] self.vals = tf.squeeze(vals, axis=1) # [pb] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _get_grid_points(self, xmin, xmax, res): x = np.linspace(xmin, xmax, res) xyz = np.meshgrid(*tuple([x] * self.dim), indexing='ij') xyz = np.stack(xyz, axis=-1) xyz = xyz.reshape([-1, self.dim]) return xyz def eval_points(self, lat, points): """Evaluate network at locations specified by points. Args: lat: [self.codelen,] np array, latent code. points: [#v, self.dim] np array, point locations to evaluate. Returns: all_vals: [#v] np array, function values at locations. """ npt = points.shape[0] npb = int(np.ceil(float(npt)/self.point_batch)) all_vals = np.zeros([npt], dtype=np.float32) for idx in range(npb): sid = int(idx * self.point_batch) eid = int(min(npt, sid+self.point_batch)) pts = points[sid:eid] pad_w = self.point_batch - (eid - sid) pts = np.pad(pts, ((0, pad_w), (0, 0)), mode='constant') with self.graph.as_default(): val = self.sess.run(self.vals, feed_dict={self.pts_ph: pts, self.lat_ph: lat}) all_vals[sid:eid] = val[:(eid-sid)] return all_vals def eval_grid(self, lat, xmin=-1.0, xmax=1.0, res=64): """Evaluate network on a grid. Args: lat: [self.codelen,] np array, latent code. xmin: float, minimum coordinate value for grid. xmax: float, maximum coordinate value for grid. res: int, resolution (per dimension) of grid. Returns: grid_val: [res, res, res] np.float32 array, grid of values from query. """ grid_points = self._get_grid_points(xmin=xmin, xmax=xmax, res=res) point_val = self.eval_points(lat, grid_points) grid_val = point_val.reshape([res, res, res]) return grid_val class EncoderEvaluator(object): """Load pretrained grid encoder and evaluate single crops.""" def __init__(self, ckpt, in_grid_res=32, encoder_nf=32, codelen=32, grid_batch=128): """Initialization function. Args: ckpt: str, path to checkpoint. in_grid_res: int, resolution of grid to feed to encoder. encoder_nf: int, number of base filters for encoder. codelen: int, length of output latent code. grid_batch: int, batch size of cut-out grid to evaluate at a time. """ self.ckpt = ckpt self.codelen = codelen self.grid_batch = grid_batch self.in_grid_res = in_grid_res self.encoder_nf = encoder_nf self.graph = tf.Graph() self._init_graph() # creates self.sess def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.encoder = g2v.GridEncoder(in_grid_res=self.in_grid_res, num_filters=self.encoder_nf, codelen=self.codelen, name='g2v') self.grid_ph = tf.placeholder( tf.float32, shape=[None, self.in_grid_res, self.in_grid_res, self.in_grid_res, 1]) self.lats = self.encoder(self.grid_ph, training=False) # [gb, codelen] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def eval_grid(self, grid): """Strided evaluation of full grid into feature grid. Args: grid: [batch, gres, gres, gres, 1] input feature grid. Returns: codes: [batch, codelen] output feature gird. """ # initialize output feature grid niters = int(np.ceil(grid.shape[0] / self.grid_batch)) codes = [] for idx in range(niters): sid = idx * self.grid_batch eid = min(sid+self.grid_batch, grid.shape[0]) c = self.sess.run(self.lats, feed_dict={self.grid_ph: grid[sid:eid]}) codes.append(c) codes = np.concatenate(codes, axis=0) return codes.astype(np.float32) class FullGridEncoderEvaluator(object): """Load pretrained grid encoder and evaluate a full input grid. Performs windowed encoding and outputs an encoded feature grid. """ def __init__(self, ckpt, in_grid_res=32, num_filters=32, codelen=128, grid_batch=128, gres=256, overlap=True): """Initialization function. Args: ckpt: str, path to checkpoint. in_grid_res: int, resolution of grid to feed to encoder. num_filters: int, number of base filters for encoder. codelen: int, length of output latent code. grid_batch: int, batch size of cut-out grid to evaluate at a time. gres: int, resolution of the full grid. overlap: bool, whether to do overlapping or non-overlapping cutout evaluations. """ self.ckpt = ckpt self.codelen = codelen self.grid_batch = grid_batch self.in_grid_res = in_grid_res self.gres = gres self.num_filters = num_filters self.graph = tf.Graph() self._init_graph() self.global_step_ = self.global_step.eval(session=self.sess) if overlap: ijk = np.arange(0, gres-int(in_grid_res/2), int(in_grid_res/2)) self.out_grid_res = ijk.shape[0] else: ijk = np.arange(0, gres, in_grid_res) self.out_grid_res = ijk.shape[0] self.ijk = np.meshgrid(ijk, ijk, ijk, indexing='ij') self.ijk = np.stack(self.ijk, axis=-1).reshape([-1, 3]) def _init_graph(self): """Initialize computation graph for tensorflow.""" with self.graph.as_default(): self.encoder = g2v.GridEncoder( in_grid_res=self.in_grid_res, num_filters=self.num_filters, codelen=self.codelen, name='g2v') self.global_step = tf.get_variable( 'global_step', shape=[], dtype=tf.int64) self.grid_ph = tf.placeholder( tf.float32, shape=[self.gres, self.gres, self.gres]) self.start_ph = tf.placeholder(tf.int32, shape=[self.grid_batch, 3]) self.ingrid = self._batch_slice(self.grid_ph, self.start_ph, self.in_grid_res, self.grid_batch) self.ingrid = self.ingrid[..., tf.newaxis] self.lats = self.encoder(self.ingrid, training=False) # [gb, codelen] self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _batch_slice(self, ary, start_ijk, w, batch_size): """Batched slicing of original grid. Args: ary: tensor, rank = 3. start_ijk: [batch_size, 3] tensor, starting index. w: width of cube to extract. batch_size: int, batch size. Returns: batched_slices: [batch_size, w, w, w] tensor, batched slices of ary. """ batch_size = start_ijk.shape[0] ijk = tf.range(w, dtype=tf.int32) slice_idx = tf.meshgrid(ijk, ijk, ijk, indexing='ij') slice_idx = tf.stack( slice_idx, axis=-1) # [in_grid_res, in_grid_res, in_grid_res, 3] slice_idx = tf.broadcast_to(slice_idx[tf.newaxis], [batch_size, w, w, w, 3]) offset = tf.broadcast_to( start_ijk[:, tf.newaxis, tf.newaxis, tf.newaxis, :], [batch_size, w, w, w, 3]) slice_idx += offset # [batch_size, in_grid_res, in_grid_res, in_grid_res, 3] batched_slices = tf.gather_nd(ary, slice_idx) # [batch_size, in_grid_res, in_grid_res, in_grid_res] return batched_slices def eval_grid(self, grid): """Strided evaluation of full grid into feature grid. Args: grid: [gres, gres, gres] input feature grid. Returns: ogrid: [out_grid_res, out_grid_res, out_grid_res, codelen] output feature gird. """ # initialize output feature grid ogrid = np.zeros([self.ijk.shape[0], self.codelen]) niters = np.ceil(self.ijk.shape[0] / self.grid_batch).astype(np.int) for idx in range(niters): sid = idx * self.grid_batch eid = min(sid + self.grid_batch, self.ijk.shape[0]) start_ijk = self.ijk[sid:eid] # pad if last iteration does not have a full batch pad_w = self.grid_batch - start_ijk.shape[0] start_ijk = np.pad(start_ijk, ((0, pad_w), (0, 0)), mode='constant') lats = self.sess.run( self.lats, feed_dict={ self.grid_ph: grid, self.start_ph: start_ijk }) ogrid[sid:eid] = lats[:eid - sid] ogrid = ogrid.reshape( [self.out_grid_res, self.out_grid_res, self.out_grid_res, self.codelen]) return ogrid.astype(np.float32) class LIGEvaluator(object): """Load pretrained grid refiner and evaluate a feature grid. """ def __init__(self, ckpt, size=(15, 15, 15), in_features=32, out_features=1, x_location_max=1, num_filters=32, min_grid_value=(0., 0., 0.), max_grid_value=(1., 1., 1.), net_type='imnet', method='linear', point_batch=20000, scope=''): """Initialization function. Args: ckpt: str, path to checkpoint. size: list or tuple of ints, grid dimension in each dimension. in_features: int, number of input channels. out_features: int, number of output channels. x_location_max: float, relative coordinate range for one voxel. num_filters: int, number of filters for refiner. min_grid_value: tuple, lower bound of query points. max_grid_value: tuple, upper bound of query points. net_type: str, one of occnet/deepsdf. method: str, one of linear/nn. point_batch: int, pseudo batch size for evaluating points. scope: str, scope of imnet layer. """ self.dim = 3 # hardcode for dim = 3 self.ckpt = ckpt self.size = size self.x_location_max = x_location_max self.num_filters = num_filters self.in_features = in_features self.out_features = out_features self.net_type = net_type self.method = method self.point_batch = point_batch self.scope = scope self.min_grid_value = min_grid_value self.max_grid_value = max_grid_value self.graph = tf.Graph() self._init_graph() def _init_graph(self): """Initialize computation graph for tensorflow. """ with self.graph.as_default(): self.lig = lig.LocalImplicitGrid(size=self.size, in_features=self.in_features, out_features=self.out_features, num_filters=self.num_filters, net_type=self.net_type, method=self.method, x_location_max=self.x_location_max, min_grid_value=self.min_grid_value, max_grid_value=self.max_grid_value, name='lig') self.pts_ph = tf.placeholder(tf.float32, shape=[self.point_batch, 3]) self.latgrid_ph = tf.placeholder(tf.float32, shape=[self.size[0], self.size[1], self.size[2], self.in_features]) self.latgrid = self.latgrid_ph[tf.newaxis] self.points = self.pts_ph[tf.newaxis] vals = self.lig(self.latgrid, self.points, training=False) # [1,npts,1] self.vals = tf.squeeze(vals, axis=[0, 2]) # [npts] self.map_dict = self._get_var_mapping(model=self.lig) self.saver = tf.train.Saver(self.map_dict) self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def _get_grid_points(self, xmin, xmax, res): x = np.linspace(xmin, xmax, res) xyz = np.meshgrid(*tuple([x] * self.dim), indexing='ij') xyz = np.stack(xyz, axis=-1) xyz = xyz.reshape([-1, self.dim]) return xyz def eval_points(self, latgrid, points): """Evaluate network at locations specified by points. Args: latgrid: [size0, size1, size2, self.codelen] np array, latent code. points: [#v, self.dim] np array, point locations to evaluate. Returns: all_vals: [#v] np array, function values at locations. """ npt = points.shape[0] npb = int(np.ceil(float(npt)/self.point_batch)) all_vals = np.zeros([npt], dtype=np.float32) for idx in range(npb): sid = int(idx * self.point_batch) eid = int(min(npt, sid+self.point_batch)) pts = points[sid:eid] pad_w = self.point_batch - (eid - sid) if pts.shape[0] < self.point_batch: pts_pad = np.tile(pts[0:1], (pad_w, 1)) # repeat the first point in the batch pts = np.concatenate([pts, pts_pad], axis=0) with self.graph.as_default(): val = self.sess.run(self.vals, feed_dict={self.pts_ph: pts, self.latgrid_ph: latgrid}) all_vals[sid:eid] = val[:(eid-sid)] return all_vals def eval_grid(self, latgrid, xmin=0.0, xmax=1.0, res=128): """Evaluate network on a grid. Args: latgrid: [size0, size1, size2, self.codelen] np array, latent code. xmin: float, minimum coordinate value for grid. xmax: float, maximum coordinate value for grid. res: int, resolution (per dimension) of grid. Returns: grid_val: [res, res, res] np.float32 array, grid of values from query. """ grid_points = self._get_grid_points(xmin=xmin, xmax=xmax, res=res) point_val = self.eval_points(latgrid, grid_points) grid_val = point_val.reshape([res, res, res]) return grid_val def _get_var_mapping(self, model): vars_ = model.trainable_variables varnames = [v.name for v in vars_] # .split(':')[0] varnames = [self.scope+v.replace('lig/', '').strip(':0') for v in varnames] map_dict = dict(zip(varnames, vars_)) return map_dict class UNetEvaluator(object): """Load pretrained UNet for generating feature grid for coarse voxel inputs.""" def __init__(self, ckpt, in_grid_res, out_grid_res, num_filters, max_filters, out_features, sph_norm=0.): self.ckpt = ckpt self.in_grid_res = in_grid_res self.out_grid_res = out_grid_res self.num_filters = num_filters self.max_filters = max_filters self.out_features = out_features self.sph_norm = sph_norm self.graph = tf.Graph() self._init_graph() def _init_graph(self): """Initialize computation graph for tensorflow.""" with self.graph.as_default(): self.unet = g2g.UNet3D(in_grid_res=self.in_grid_res, out_grid_res=self.out_grid_res, num_filters=self.num_filters, max_filters=self.max_filters, out_features=self.out_features) self.input_grid_ph = tf.placeholder( tf.float32, [None, None, None]) self.input_grid = self.input_grid_ph[tf.newaxis, ..., tf.newaxis] self.feat_grid = self.unet(self.input_grid) self.saver = tf.train.Saver() self.sess = tf.Session() self.saver.restore(self.sess, self.ckpt) def eval_grid(self, input_grid): """Evaluate input grid (no batching). Args: input_grid: [in_grid_res, in_grid_res, in_grid_res] tensor. Returns: [out_grid_res, out_grid_res, out_grid_res, out_features] """ with self.graph.as_default(): feat_grid = self.sess.run(self.feat_grid, feed_dict={self.input_grid_ph: input_grid}) feat_grid = feat_grid[0] if self.sph_norm > 0: feat_grid = (feat_grid / np.linalg.norm(feat_grid, axis=-1, keepdims=True) * self.sph_norm) return feat_grid class SparseLIGEvaluator(object): """Evaluate sparse encoded feature grids.""" def __init__(self, ckpt, num_filters, codelen, origin, grid_shape, part_size, overlap=True, scope=''): self.scope = scope self.overlap = overlap self.ckpt = ckpt self.num_filters = num_filters self.codelen = codelen if overlap: self.res = (np.array(grid_shape) - 1) / 2.0 else: self.res = np.array(grid_shape) - 1 self.res = self.res.astype(np.int32) self.xmin = np.array(origin) self.xmax = self.xmin + self.res * part_size self.part_size = part_size self.lvg = LIGEvaluator(ckpt=ckpt, size=grid_shape, in_features=codelen, out_features=1, x_location_max=2-float(overlap), num_filters=num_filters, min_grid_value=self.xmin, max_grid_value=self.xmax, net_type='imnet', method='linear' if overlap else 'nn', scope=scope) def evaluate_feature_grid(self, feature_grid, mask, res_per_part=4, conservative=False): """Evaluate feature grid. Args: feature_grid: [*grid_size, codelen] np.array, feature grid to evaluate. mask: [*grid_size] bool np.array, mask for feature locations. res_per_part: int, resolution of output evaluation per part. conservative: bool, whether to do conservative evaluations. If true, evalutes a cell if either neighbor is masked. Else, evaluates a cell if all neighbors are masked. Returns: output grid. """ # setup grid eps = 1e-6 s = self.res l = [np.linspace(self.xmin[i]+eps, self.xmax[i]-eps, res_per_part*s[i]) for i in range(3)] xyz = np.stack(np.meshgrid(l[0], l[1], l[2], indexing='ij'), axis=-1).reshape(-1, 3) output_grid = np.ones([res_per_part*s[0], res_per_part*s[1], res_per_part*s[2]], dtype=np.float32).reshape(-1) mask = mask.astype(np.bool) if self.overlap: mask = np.stack([mask[:-1, :-1, :-1], mask[:-1, :-1, 1:], mask[:-1, 1:, :-1], mask[:-1, 1:, 1:], mask[1:, :-1, :-1], mask[1:, :-1, 1:], mask[1:, 1:, :-1], mask[1:, 1:, 1:]], axis=-1) if conservative: mask = np.any(mask, axis=-1) else: mask = np.all(mask, axis=-1) g = np.stack(np.meshgrid(np.arange(mask.shape[0]), np.arange(mask.shape[1]), np.arange(mask.shape[2]), indexing='ij'), axis=-1).reshape(-1, 3) g = g[:, 0]*(mask.shape[1]*mask.shape[2]) + g[:, 1]*mask.shape[2] + g[:, 2] g_valid = g[mask.ravel()] if self.overlap: ijk = np.floor((xyz - self.xmin) / self.part_size * 2).astype(np.int32) else: ijk = np.floor((xyz - self.xmin + 0.5 * self.part_size) / self.part_size).astype(np.int32) ijk_idx = (ijk[:, 0]*(mask.shape[1] * mask.shape[2]) + ijk[:, 1]*mask.shape[2] + ijk[:, 2]) pt_mask = np.isin(ijk_idx, g_valid) output_grid[pt_mask] = self.lvg.eval_points(feature_grid, xyz[pt_mask]) output_grid = output_grid.reshape(res_per_part*s[0], # pylint: disable=too-many-function-args res_per_part*s[1], res_per_part*s[2]) return output_grid
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./.git/hooks/commit-msg.sample
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/kernels/rasterize_triangles_impl.h
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_ #include "absl/base/integral_types.h" // Determines the mode for face culling. Analogous to OpenGL's glCullFace // parameters. enum class FaceCullingMode { kNone = 0, kBack, kFront }; // Computes the triangle id, barycentric coordinates, and z-buffer at each pixel // in the image. // // vertices: A flattened 2D array with 4*vertex_count elements. // Each contiguous triplet is the XYZW location of the vertex with that // triplet's id. The coordinates are assumed to be OpenGL-style clip-space // (i.e., post-projection, pre-divide), where X points right, Y points up, // Z points away. // triangles: A flattened 2D array with 3*triangle_count elements. // Each contiguous triplet is the three vertex ids indexing into vertices // describing one triangle with clockwise winding. // triangle_count: The number of triangles stored in the array triangles. // num_layers: Number of surface layers to store at each pixel, esentially // depth-peeling (https://en.wikipedia.org/wiki/Depth_peeling). // face_culling_mode: mode for culling back-facing triangles, front-facing // triangles, or none. // triangle_ids: A flattened 2D array with num_layers*image_height*image_width // elements. At return, each pixel contains a triangle id in the range // [0, triangle_count). The id value is also 0 if there is no triangle // at the pixel. The barycentric_coordinates must be checked to // distinguish the two cases. // z_buffer: A flattened 2D array with num_layers*image_height*image_width // elements. At return, contains the normalized device Z coordinates of the // rendered triangles. // barycentric_coordinates: A flattened 3D array with // num_layers*image_height*image_width*3 elements. At return, contains the // triplet of barycentric coordinates at each pixel in the same vertex // ordering as triangles. If no triangle is present, all coordinates are 0. // May be nullptr if barycentric coordinates are not desired. void RasterizeTrianglesImpl(const float* vertices, const int32* triangles, int32 triangle_count, int32 image_width, int32 image_height, int32 num_layers, FaceCullingMode face_culling_mode, int32* triangle_ids, float* z_buffer, float* barycentric_coordinates); #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_ #include "absl/base/integral_types.h" // Determines the mode for face culling. Analogous to OpenGL's glCullFace // parameters. enum class FaceCullingMode { kNone = 0, kBack, kFront }; // Computes the triangle id, barycentric coordinates, and z-buffer at each pixel // in the image. // // vertices: A flattened 2D array with 4*vertex_count elements. // Each contiguous triplet is the XYZW location of the vertex with that // triplet's id. The coordinates are assumed to be OpenGL-style clip-space // (i.e., post-projection, pre-divide), where X points right, Y points up, // Z points away. // triangles: A flattened 2D array with 3*triangle_count elements. // Each contiguous triplet is the three vertex ids indexing into vertices // describing one triangle with clockwise winding. // triangle_count: The number of triangles stored in the array triangles. // num_layers: Number of surface layers to store at each pixel, esentially // depth-peeling (https://en.wikipedia.org/wiki/Depth_peeling). // face_culling_mode: mode for culling back-facing triangles, front-facing // triangles, or none. // triangle_ids: A flattened 2D array with num_layers*image_height*image_width // elements. At return, each pixel contains a triangle id in the range // [0, triangle_count). The id value is also 0 if there is no triangle // at the pixel. The barycentric_coordinates must be checked to // distinguish the two cases. // z_buffer: A flattened 2D array with num_layers*image_height*image_width // elements. At return, contains the normalized device Z coordinates of the // rendered triangles. // barycentric_coordinates: A flattened 3D array with // num_layers*image_height*image_width*3 elements. At return, contains the // triplet of barycentric coordinates at each pixel in the same vertex // ordering as triangles. If no triangle is present, all coordinates are 0. // May be nullptr if barycentric coordinates are not desired. void RasterizeTrianglesImpl(const float* vertices, const int32* triangles, int32 triangle_count, int32 image_width, int32 image_height, int32 num_layers, FaceCullingMode face_culling_mode, int32* triangle_ids, float* z_buffer, float* barycentric_coordinates); #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_KERNELS_RASTERIZE_TRIANGLES_IMPL_H_
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/reflectance/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reflectance module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.reflectance import blinn_phong from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.reflectance. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reflectance module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.reflectance import blinn_phong from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.reflectance. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/datasets/pix3d/fakes/mask/bed/0010.png
PNG  IHDRJ (IDATxrG EQ&eA )q(N7s*Eu{F.~Ϝ ܳOf?q$m>q3_Y%XYV%Xvfwh3`F @0``p&L @0` a 1}&L @0` !!Y &L ?\!L 5Q &L @0`  $@F @0` &Gd&L @0 /o&L I&L @0` %PC.:` &L @0x?*a ` |ms@0` #| &L @0 ?ܸE < &L @0`1 y_I @0`|v "1Q ͸Ɖ!wvg:rkW <JzroQA ߖB1D"gp b87?&h~$w3<^FN0*{¨[p#T=?|Ce^Kcq 7 @.|ͨ0H/foStp -6{\&A _.p_AGpp |fSiTC>A\@03!Ju {AxIqx+}߹> kWك@& ]t1 fs%߽H rႯ_. \? \|%w  "k9 ȼsx+q7`y'q x|)p$rxQl?MEjn 窸 p +m4"vpKb?MG`nϗ$.YF$._i;I$]-|/+{ITϝrF%(9 ~1Ӓ$H'21!M8(#2&"W %󈈹 @=CIxt@-ƒ+ '̿?5~F`L;<106=IS0I4ifF_<M~ c51 k`?6w`]Ӎ cjZ^aX?:Y1+S3~CgkTfR?'9^0(c s lglL`bf fļAykLgq6 Bƭ`ahaKugY#<.VzuFl9-& ^Lأq`AϞt K3}]0h5 zٔl) l7)1CkO3_f;."Fb8tY?uL^p1`{xV\F?F~(QC=m`\v @sSTl =мL{8[3\ 5Z?O+Oy|T@㶒@߃jCI- MTZ8]HMǵn(tR7J'V<Nj?ݴ٢hyN8% pr )BS]{x @3?Mo;AhZ?ubv|[k6å젽Rz=*` @c3EYNg_k4E`gkآDf+a4`T@3R&3mg jQhqD0&0;|` `t`g@+?W~7@=>[PPi?ȱ!$}}jDwpҏ(}fu?q*T> ȳ6D~i  @SP `Uv[ UezlU?يn!ܚ\%(\?8Vq \.+`E]8=fෳ`Uu89~`s`r ة(;جNj?+_`bEjsxoVW`Uz85ڼj^ ,W@`:ߎ:?'p7&L %T V+\&z> ,Vb`R@0`/,oVG@0` Px&T_WO  $ߊ-7&L ؚx ,TeX آTpxh [B= [r 2ރ @A<oL @% 7&L @(d ,li*y` /Ur@0`-@A 7XO @@0`+wyD [_@ U_| /C&p@À4 XUbϮ)#4Rv~3ݳ YO֘h^5ˆdu׬'[E58hPw~2fu?[u׬'#h޲ "Gs,F-+ѠEhk4l Չ9IENDB`
PNG  IHDRJ (IDATxrG EQ&eA )q(N7s*Eu{F.~Ϝ ܳOf?q$m>q3_Y%XYV%Xvfwh3`F @0``p&L @0` a 1}&L @0` !!Y &L ?\!L 5Q &L @0`  $@F @0` &Gd&L @0 /o&L I&L @0` %PC.:` &L @0x?*a ` |ms@0` #| &L @0 ?ܸE < &L @0`1 y_I @0`|v "1Q ͸Ɖ!wvg:rkW <JzroQA ߖB1D"gp b87?&h~$w3<^FN0*{¨[p#T=?|Ce^Kcq 7 @.|ͨ0H/foStp -6{\&A _.p_AGpp |fSiTC>A\@03!Ju {AxIqx+}߹> kWك@& ]t1 fs%߽H rႯ_. \? \|%w  "k9 ȼsx+q7`y'q x|)p$rxQl?MEjn 窸 p +m4"vpKb?MG`nϗ$.YF$._i;I$]-|/+{ITϝrF%(9 ~1Ӓ$H'21!M8(#2&"W %󈈹 @=CIxt@-ƒ+ '̿?5~F`L;<106=IS0I4ifF_<M~ c51 k`?6w`]Ӎ cjZ^aX?:Y1+S3~CgkTfR?'9^0(c s lglL`bf fļAykLgq6 Bƭ`ahaKugY#<.VzuFl9-& ^Lأq`AϞt K3}]0h5 zٔl) l7)1CkO3_f;."Fb8tY?uL^p1`{xV\F?F~(QC=m`\v @sSTl =мL{8[3\ 5Z?O+Oy|T@㶒@߃jCI- MTZ8]HMǵn(tR7J'V<Nj?ݴ٢hyN8% pr )BS]{x @3?Mo;AhZ?ubv|[k6å젽Rz=*` @c3EYNg_k4E`gkآDf+a4`T@3R&3mg jQhqD0&0;|` `t`g@+?W~7@=>[PPi?ȱ!$}}jDwpҏ(}fu?q*T> ȳ6D~i  @SP `Uv[ UezlU?يn!ܚ\%(\?8Vq \.+`E]8=fෳ`Uu89~`s`r ة(;جNj?+_`bEjsxoVW`Uz85ڼj^ ,W@`:ߎ:?'p7&L %T V+\&z> ,Vb`R@0`/,oVG@0` Px&T_WO  $ߊ-7&L ؚx ,TeX آTpxh [B= [r 2ރ @A<oL @% 7&L @(d ,li*y` /Ur@0`-@A 7XO @@0`+wyD [_@ U_| /C&p@À4 XUbϮ)#4Rv~3ݳ YO֘h^5ˆdu׬'[E58hPw~2fu?[u׬'#h޲ "Gs,F-+ѠEhk4l Չ9IENDB`
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/triangle_rasterizer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width, 1]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) rasterized = rasterization_backend.rasterize(vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = { "mask": rasterized.foreground_mask, "triangle_indices": rasterized.triangle_id } # Extract batch shape in order to make sure it is preserved after `gather` # operation. batch_shape = rasterized.triangle_id.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices_per_pixel = tf.gather( vertices, rasterized.vertex_ids, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(rasterized.foreground_mask, vertices.dtype) outputs["barycentrics"] = mask_float * barycentrics for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) outputs[key] = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, rasterized.triangle_id[..., 0], len(batch_shape)) return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width, 1]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) rasterized = rasterization_backend.rasterize(vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = { "mask": rasterized.foreground_mask, "triangle_indices": rasterized.triangle_id } # Extract batch shape in order to make sure it is preserved after `gather` # operation. batch_shape = rasterized.triangle_id.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices_per_pixel = tf.gather( vertices, rasterized.vertex_ids, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(rasterized.foreground_mask, vertices.dtype) outputs["barycentrics"] = mask_float * barycentrics for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) outputs[key] = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, rasterized.triangle_id[..., 0], len(batch_shape)) return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/opengl/gl_shader_storage_buffer.h
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_ #include <GLES3/gl32.h> #include "absl/types/span.h" #include "macros.h" #include "cleanup.h" #include "tensorflow/core/lib/core/status.h" namespace gl_utils { // Class for creating and uploading data to storage buffers. class ShaderStorageBuffer { public: ~ShaderStorageBuffer(); tensorflow::Status BindBufferBase(GLuint index) const; static tensorflow::Status Create( std::unique_ptr<ShaderStorageBuffer>* shader_storage_buffer); // Uploads data to the buffer. template <typename T> tensorflow::Status Upload(absl::Span<T> data) const; private: ShaderStorageBuffer() = delete; ShaderStorageBuffer(GLuint buffer); ShaderStorageBuffer(const ShaderStorageBuffer&) = delete; ShaderStorageBuffer(ShaderStorageBuffer&&) = delete; ShaderStorageBuffer& operator=(const ShaderStorageBuffer&) = delete; ShaderStorageBuffer& operator=(ShaderStorageBuffer&&) = delete; GLuint buffer_; }; template <typename T> tensorflow::Status ShaderStorageBuffer::Upload(absl::Span<T> data) const { // Bind the buffer to the read/write storage for shaders. TFG_RETURN_IF_GL_ERROR(glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer_)); auto bind_cleanup = MakeCleanup([]() { glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); }); // Create a new data store for the bound buffer and initializes it with the // input data. TFG_RETURN_IF_GL_ERROR(glBufferData(GL_SHADER_STORAGE_BUFFER, data.size() * sizeof(T), data.data(), GL_DYNAMIC_COPY)); // bind_cleanup is not released, leading the buffer to be unbound. return tensorflow::Status::OK(); } } // namespace gl_utils #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_ #define THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_ #include <GLES3/gl32.h> #include "absl/types/span.h" #include "macros.h" #include "cleanup.h" #include "tensorflow/core/lib/core/status.h" namespace gl_utils { // Class for creating and uploading data to storage buffers. class ShaderStorageBuffer { public: ~ShaderStorageBuffer(); tensorflow::Status BindBufferBase(GLuint index) const; static tensorflow::Status Create( std::unique_ptr<ShaderStorageBuffer>* shader_storage_buffer); // Uploads data to the buffer. template <typename T> tensorflow::Status Upload(absl::Span<T> data) const; private: ShaderStorageBuffer() = delete; ShaderStorageBuffer(GLuint buffer); ShaderStorageBuffer(const ShaderStorageBuffer&) = delete; ShaderStorageBuffer(ShaderStorageBuffer&&) = delete; ShaderStorageBuffer& operator=(const ShaderStorageBuffer&) = delete; ShaderStorageBuffer& operator=(ShaderStorageBuffer&&) = delete; GLuint buffer_; }; template <typename T> tensorflow::Status ShaderStorageBuffer::Upload(absl::Span<T> data) const { // Bind the buffer to the read/write storage for shaders. TFG_RETURN_IF_GL_ERROR(glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer_)); auto bind_cleanup = MakeCleanup([]() { glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); }); // Create a new data store for the bound buffer and initializes it with the // input data. TFG_RETURN_IF_GL_ERROR(glBufferData(GL_SHADER_STORAGE_BUFFER, data.size() * sizeof(T), data.data(), GL_DYNAMIC_COPY)); // bind_cleanup is not released, leading the buffer to be unbound. return tensorflow::Status::OK(); } } // namespace gl_utils #endif // THIRD_PARTY_PY_TENSORFLOW_GRAPHICS_RENDERING_OPENGL_GL_SHADER_STORAGE_BUFFER_H_
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/opensource_only.files
tensorflow_graphics/rendering/opengl/BUILD
tensorflow_graphics/rendering/opengl/BUILD
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/voxels/visual_hull.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the visual hull voxel rendering.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def render(voxels, axis=2, name=None): """Renders the visual hull of a voxel grid, as described in ["Escaping Plato's Cave: 3D Shape From Adversarial Rendering" (Henzler 2019)](https://github.com/henzler/platonicgan). Note: In the following, A1 to An are optional batch dimensions. Args: voxels: A tensor of shape `[A1, ..., An, Vx, Vy, Vz, Vd]`, where Vx, Vy, Vz are the dimensions of the voxel grid and Vd the dimension of the information stored in each voxel (e.g. 3 for RGB color). axis: An index to the projection axis (0 for X, 1 for Y or 2 for Z). name: A name for this op. Defaults to "visual_hull_render". Returns: A tensor of shape `[A1, ..., An, Vx, Vy, Vd]` representing images of size (Vx,Vy). Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.compat.v1.name_scope(name, "visual_hull_render", [voxels]): voxels = tf.convert_to_tensor(value=voxels) shape.check_static( tensor=voxels, tensor_name="voxels", has_rank_greater_than=3) if axis not in [0, 1, 2]: raise ValueError("'axis' needs to be 0, 1 or 2") image = tf.reduce_sum(input_tensor=voxels, axis=axis - 4) image = tf.ones_like(image) - tf.math.exp(-image) return image # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the visual hull voxel rendering.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def render(voxels, axis=2, name=None): """Renders the visual hull of a voxel grid, as described in ["Escaping Plato's Cave: 3D Shape From Adversarial Rendering" (Henzler 2019)](https://github.com/henzler/platonicgan). Note: In the following, A1 to An are optional batch dimensions. Args: voxels: A tensor of shape `[A1, ..., An, Vx, Vy, Vz, Vd]`, where Vx, Vy, Vz are the dimensions of the voxel grid and Vd the dimension of the information stored in each voxel (e.g. 3 for RGB color). axis: An index to the projection axis (0 for X, 1 for Y or 2 for Z). name: A name for this op. Defaults to "visual_hull_render". Returns: A tensor of shape `[A1, ..., An, Vx, Vy, Vd]` representing images of size (Vx,Vy). Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.compat.v1.name_scope(name, "visual_hull_render", [voxels]): voxels = tf.convert_to_tensor(value=voxels) shape.check_static( tensor=voxels, tensor_name="voxels", has_rank_greater_than=3) if axis not in [0, 1, 2]: raise ValueError("'axis' needs to be 0, 1 or 2") image = tf.reduce_sum(input_tensor=voxels, axis=axis - 4) image = tf.ones_like(image) - tf.math.exp(-image) return image # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/reflectance/blinn_phong.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/opengl/BUILD
# OpenGL functionalities for tf-graphics. licenses(["notice"]) # Apache 2.0 package(default_visibility = ["//visibility:public"]) genrule( name = "rasterizer_op", srcs = [ "cleanup.h", "egl_offscreen_context.cc", "egl_offscreen_context.h", "egl_util.cc", "egl_util.h", "gl_program.cc", "gl_program.h", "gl_render_targets.cc", "gl_render_targets.h", "gl_shader_storage_buffer.cc", "gl_shader_storage_buffer.h", "macros.h", "rasterizer.cc", "rasterizer.h", "rasterizer_op.cc", "rasterizer_with_context.cc", "rasterizer_with_context.h", "thread_safe_resource_pool.h", ], outs = ["rasterizer_op.so"], cmd = "TF_CFLAGS=$$(python -c 'import tensorflow as tf; print(\" \".join(tf.sysconfig.get_compile_flags()))');\ TF_LFLAGS=$$(python -c 'import tensorflow as tf; print(\" \".join(tf.sysconfig.get_link_flags()))');\ g++ -std=c++11 -shared $(SRCS) -o $(OUTS) -fPIC $${TF_CFLAGS[@]} $${TF_LFLAGS[@]}\ -DUSE_OZONE -Wl,-L/usr/lib/x86_64-linux-gnu/mesa-egl -Wl,-L/usr/lib/x86_64-linux-gnu -Wl,-lEGL -Wl,-lGLESv2 -O2;\ VAR_OUTS=$(OUTS);\ VAR_GENDIR=$(GENDIR);\ cp $(OUTS) $(BASEDIR)/$${VAR_OUTS#$$VAR_GENDIR}", )
# OpenGL functionalities for tf-graphics. licenses(["notice"]) # Apache 2.0 package(default_visibility = ["//visibility:public"]) genrule( name = "rasterizer_op", srcs = [ "cleanup.h", "egl_offscreen_context.cc", "egl_offscreen_context.h", "egl_util.cc", "egl_util.h", "gl_program.cc", "gl_program.h", "gl_render_targets.cc", "gl_render_targets.h", "gl_shader_storage_buffer.cc", "gl_shader_storage_buffer.h", "macros.h", "rasterizer.cc", "rasterizer.h", "rasterizer_op.cc", "rasterizer_with_context.cc", "rasterizer_with_context.h", "thread_safe_resource_pool.h", ], outs = ["rasterizer_op.so"], cmd = "TF_CFLAGS=$$(python -c 'import tensorflow as tf; print(\" \".join(tf.sysconfig.get_compile_flags()))');\ TF_LFLAGS=$$(python -c 'import tensorflow as tf; print(\" \".join(tf.sysconfig.get_link_flags()))');\ g++ -std=c++11 -shared $(SRCS) -o $(OUTS) -fPIC $${TF_CFLAGS[@]} $${TF_LFLAGS[@]}\ -DUSE_OZONE -Wl,-L/usr/lib/x86_64-linux-gnu/mesa-egl -Wl,-L/usr/lib/x86_64-linux-gnu -Wl,-lEGL -Wl,-lGLESv2 -O2;\ VAR_OUTS=$(OUTS);\ VAR_GENDIR=$(GENDIR);\ cp $(OUTS) $(BASEDIR)/$${VAR_OUTS#$$VAR_GENDIR}", )
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./.pylintrc
[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS, __pycache__, .git, .tox, .pytest_cache, tensorflow_graphics/projects/* # Pickle collected data for later comparisons. persistent=yes # Use multiple processes to speed up Pylint. jobs=4 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= [MESSAGES CONTROL] # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. enable=indexing-exception,old-raise-syntax # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=design, similarities, no-self-use, attribute-defined-outside-init, locally-disabled, star-args, pointless-except, bad-option-value, global-statement, fixme, suppressed-message, useless-suppression, locally-enabled, no-member, no-name-in-module, import-error, unsubscriptable-object, unbalanced-tuple-unpacking, undefined-variable, not-context-manager, E1130, # (TFG) Invalid-unary-operand-type for Numpy array R1705, # (TFG) Unnecessary "else" after "return" (no-else-return) R1720, # (TFG) Unnecessary "else" after "raise" (no-else-raise) R1721, # (TFG) Unnecessary use of a comprehension (unnecessary-comprehension) # Set the cache size for astng objects. cache-size=500 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent # List of decorators that create context managers from functions, such as # contextlib.contextmanager. contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the beginning of the name of dummy variables # (i.e. not used). dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_) # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= [BASIC] # Required attributes for module, separated by a comma required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=apply,input,reduce # Disable the report(s) with the given id(s). # All non-Google reports are disabled by default. disable-report=R0001,R0002,R0003,R0004,R0101,R0102,R0201,R0202,R0220,R0401,R0402,R0701,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,R0923 # Regular expression which should only match correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression which should only match correct module level names const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ # Regular expression which should only match correct class names class-rgx=^_?[A-Z][a-zA-Z0-9]*$ # Regular expression which should only match correct function names function-rgx=^(?:(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$ # Regular expression which should only match correct method names method-rgx=^(?:(?P<exempt>__[a-z0-9_]+__|next)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$ # Regular expression which should only match correct instance attribute names attr-rgx=^_{0,2}[a-z][a-z0-9_]*$ # Regular expression which should only match correct argument names argument-rgx=^[a-z][a-z0-9_]*$ # Regular expression which should only match correct variable names variable-rgx=^[a-z][a-z0-9_]*$ # Regular expression which should only match correct attribute names in class # bodies class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ # Regular expression which should only match correct list comprehension / # generator expression variable names inlinevar-rgx=^[a-z][a-z0-9_]*$ # Good variable names which should always be accepted, separated by a comma good-names=main,_ # Bad variable names which should always be refused, separated by a comma bad-names= # Regular expression which should only match function or class names that do # not require a docstring. # # no-docstring-rgx=(__.*__|main) #< TF version no-docstring-rgx=(__.*__|main|.*Test|^test_|^_) # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=10 [FORMAT] # Maximum number of characters on a single line. max-line-length=80 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=(?x) (^\s*(import|from)\s |\$Id:\s\/\/depot\/.+#\d+\s\$ |^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*("[^"]\S+"|'[^']\S+') |^\s*\#\ LINT\.ThenChange |^[^#]*\#\ type:\ [a-zA-Z_][a-zA-Z0-9_.,[\] ]*$ |pylint |""" |\# |lambda |(https?|ftp):) # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=y # List of optional constructs for which whitespace checking is disabled no-space-check= # Maximum number of lines in a module max-module-lines=99999 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes= [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,TERMIOS,Bastion,rexec,sets # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls,class_ # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception,StandardError,BaseException [AST] # Maximum line length for lambdas short-func-length=1 # List of module members that should be marked as deprecated. # All of the string functions are listed in 4.1.4 Deprecated string functions # in the Python 2.4 docs. deprecated-members=string.atof,string.atoi,string.atol,string.capitalize,string.expandtabs,string.find,string.rfind,string.index,string.rindex,string.count,string.lower,string.split,string.rsplit,string.splitfields,string.join,string.joinfields,string.lstrip,string.rstrip,string.strip,string.swapcase,string.translate,string.upper,string.ljust,string.rjust,string.center,string.zfill,string.replace,sys.exitfunc [DOCSTRING] # List of exceptions that do not need to be mentioned in the Raises section of # a docstring. ignore-exceptions=AssertionError,NotImplementedError,StopIteration,TypeError [TOKENS] # Number of spaces of indent required when the last token on the preceding line # is an open (, [, or {. indent-after-paren=4 [GOOGLE LINES] # Regexp for a proper copyright notice. copyright=Copyright \d{4} The TensorFlow Authors\. +All [Rr]ights [Rr]eserved\.
[MASTER] # Specify a configuration file. #rcfile= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Profiled execution. profile=no # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS, __pycache__, .git, .tox, .pytest_cache, tensorflow_graphics/projects/* # Pickle collected data for later comparisons. persistent=yes # Use multiple processes to speed up Pylint. jobs=4 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. load-plugins= [MESSAGES CONTROL] # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time. See also the "--disable" option for examples. enable=indexing-exception,old-raise-syntax # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once).You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=design, similarities, no-self-use, attribute-defined-outside-init, locally-disabled, star-args, pointless-except, bad-option-value, global-statement, fixme, suppressed-message, useless-suppression, locally-enabled, no-member, no-name-in-module, import-error, unsubscriptable-object, unbalanced-tuple-unpacking, undefined-variable, not-context-manager, E1130, # (TFG) Invalid-unary-operand-type for Numpy array R1705, # (TFG) Unnecessary "else" after "return" (no-else-return) R1720, # (TFG) Unnecessary "else" after "raise" (no-else-raise) R1721, # (TFG) Unnecessary use of a comprehension (unnecessary-comprehension) # Set the cache size for astng objects. cache-size=500 [REPORTS] # Set the output format. Available formats are text, parseable, colorized, msvs # (visual studio) and html. You can also give a reporter class, eg # mypackage.mymodule.MyReporterClass. output-format=text # Put messages in a separate file for each module / package specified on the # command line instead of printing them on stdout. Reports (if any) will be # written in a file name "pylint_global.[txt|html]". files-output=no # Tells whether to display a full report or only the messages reports=no # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Add a comment according to your evaluation note. This is used by the global # evaluation report (RP0004). comment=no # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details #msg-template= [TYPECHECK] # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # List of classes names for which member attributes should not be checked # (useful for classes with attributes dynamically set). ignored-classes=SQLObject # When zope mode is activated, add a predefined set of Zope acquired attributes # to generated-members. zope=no # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E0201 when accessed. Python regular # expressions are accepted. generated-members=REQUEST,acl_users,aq_parent # List of decorators that create context managers from functions, such as # contextlib.contextmanager. contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager [VARIABLES] # Tells whether we should check for unused import in __init__ files. init-import=no # A regular expression matching the beginning of the name of dummy variables # (i.e. not used). dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_) # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= [BASIC] # Required attributes for module, separated by a comma required-attributes= # List of builtins function names that should not be used, separated by a comma bad-functions=apply,input,reduce # Disable the report(s) with the given id(s). # All non-Google reports are disabled by default. disable-report=R0001,R0002,R0003,R0004,R0101,R0102,R0201,R0202,R0220,R0401,R0402,R0701,R0801,R0901,R0902,R0903,R0904,R0911,R0912,R0913,R0914,R0915,R0921,R0922,R0923 # Regular expression which should only match correct module names module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Regular expression which should only match correct module level names const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ # Regular expression which should only match correct class names class-rgx=^_?[A-Z][a-zA-Z0-9]*$ # Regular expression which should only match correct function names function-rgx=^(?:(?P<camel_case>_?[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_?[a-z][a-z0-9_]*))$ # Regular expression which should only match correct method names method-rgx=^(?:(?P<exempt>__[a-z0-9_]+__|next)|(?P<camel_case>_{0,2}[A-Z][a-zA-Z0-9]*)|(?P<snake_case>_{0,2}[a-z][a-z0-9_]*))$ # Regular expression which should only match correct instance attribute names attr-rgx=^_{0,2}[a-z][a-z0-9_]*$ # Regular expression which should only match correct argument names argument-rgx=^[a-z][a-z0-9_]*$ # Regular expression which should only match correct variable names variable-rgx=^[a-z][a-z0-9_]*$ # Regular expression which should only match correct attribute names in class # bodies class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ # Regular expression which should only match correct list comprehension / # generator expression variable names inlinevar-rgx=^[a-z][a-z0-9_]*$ # Good variable names which should always be accepted, separated by a comma good-names=main,_ # Bad variable names which should always be refused, separated by a comma bad-names= # Regular expression which should only match function or class names that do # not require a docstring. # # no-docstring-rgx=(__.*__|main) #< TF version no-docstring-rgx=(__.*__|main|.*Test|^test_|^_) # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=10 [FORMAT] # Maximum number of characters on a single line. max-line-length=80 # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=(?x) (^\s*(import|from)\s |\$Id:\s\/\/depot\/.+#\d+\s\$ |^[a-zA-Z_][a-zA-Z0-9_]*\s*=\s*("[^"]\S+"|'[^']\S+') |^\s*\#\ LINT\.ThenChange |^[^#]*\#\ type:\ [a-zA-Z_][a-zA-Z0-9_.,[\] ]*$ |pylint |""" |\# |lambda |(https?|ftp):) # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=y # List of optional constructs for which whitespace checking is disabled no-space-check= # Maximum number of lines in a module max-module-lines=99999 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' [SIMILARITIES] # Minimum lines number of a similarity. min-similarity-lines=4 # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes= [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules=regsub,TERMIOS,Bastion,rexec,sets # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled) import-graph= # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled) ext-import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled) int-import-graph= [CLASSES] # List of interface methods to ignore, separated by a comma. This is used for # instance to not check methods defines in Zope's Interface base class. ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__,__new__,setUp # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls,class_ # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=mcs [DESIGN] # Maximum number of arguments for function / method max-args=5 # Argument names that match this expression will be ignored. Default to name # with leading underscore ignored-argument-names=_.* # Maximum number of locals for function / method body max-locals=15 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body max-branches=12 # Maximum number of statements in function / method body max-statements=50 # Maximum number of parents for a class (see R0901). max-parents=7 # Maximum number of attributes for a class (see R0902). max-attributes=7 # Minimum number of public methods for a class (see R0903). min-public-methods=2 # Maximum number of public methods for a class (see R0904). max-public-methods=20 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception" overgeneral-exceptions=Exception,StandardError,BaseException [AST] # Maximum line length for lambdas short-func-length=1 # List of module members that should be marked as deprecated. # All of the string functions are listed in 4.1.4 Deprecated string functions # in the Python 2.4 docs. deprecated-members=string.atof,string.atoi,string.atol,string.capitalize,string.expandtabs,string.find,string.rfind,string.index,string.rindex,string.count,string.lower,string.split,string.rsplit,string.splitfields,string.join,string.joinfields,string.lstrip,string.rstrip,string.strip,string.swapcase,string.translate,string.upper,string.ljust,string.rjust,string.center,string.zfill,string.replace,sys.exitfunc [DOCSTRING] # List of exceptions that do not need to be mentioned in the Raises section of # a docstring. ignore-exceptions=AssertionError,NotImplementedError,StopIteration,TypeError [TOKENS] # Number of spaces of indent required when the last token on the preceding line # is an open (, [, or {. indent-after-paren=4 [GOOGLE LINES] # Regexp for a proper copyright notice. copyright=Copyright \d{4} The TensorFlow Authors\. +All [Rr]ights [Rr]eserved\.
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/voxels/emission_absorption.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the emission absorption voxel rendering.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def render(voxels, absorption_factor=0.1, cell_size=1.0, axis=2, name=None): """Renders a voxel grid using the emission-absorption model, as described in ["Escaping Plato's Cave: 3D Shape From Adversarial Rendering" (Henzler 2019)](https://github.com/henzler/platonicgan). Note: In the following, A1 to An are optional batch dimensions. Args: voxels: A tensor of shape `[A1, ..., An, Vx, Vy, Vz, Vd]`, where Vx, Vy, Vz are the dimensions of the voxel grid and Vd the dimension of the information stored in each voxel (e.g. 3 for RGB color). absorption_factor: A scalar representing the density of the volume. cell_size: A scalar representing the size of a cell. axis: An index to the projection axis (0 for X, 1 for Y or 2 for Z). name: A name for this op. Defaults to "emission_absorption_render". Returns: A tensor of shape `[A1, ..., An, Vx, Vy, Vd]` representing images of size (Vx,Vy). Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.compat.v1.name_scope(name, "emission_absorption_render", [voxels]): voxels = tf.convert_to_tensor(value=voxels) shape.check_static( tensor=voxels, tensor_name="voxels", has_rank_greater_than=3) if axis not in [0, 1, 2]: raise ValueError("'axis' needs to be 0, 1 or 2") signal, density = tf.split(voxels, (-1, 1), axis=-1) density = tf.scalar_mul(absorption_factor / cell_size, density) one_minus_density = tf.ones_like(density) - density transmission = tf.math.cumprod(one_minus_density, axis=axis - 4) weight = density * transmission weight_sum = tf.reduce_sum(input_tensor=weight, axis=axis - 4) rendering = tf.reduce_sum(input_tensor=weight * signal, axis=axis - 4) rendering = rendering / (weight_sum + 1e-8) transparency = tf.reduce_prod(input_tensor=one_minus_density, axis=axis - 4) alpha = tf.ones_like(transparency) - transparency rendering = rendering * alpha image = tf.concat([rendering, alpha], axis=-1) return image # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the emission absorption voxel rendering.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def render(voxels, absorption_factor=0.1, cell_size=1.0, axis=2, name=None): """Renders a voxel grid using the emission-absorption model, as described in ["Escaping Plato's Cave: 3D Shape From Adversarial Rendering" (Henzler 2019)](https://github.com/henzler/platonicgan). Note: In the following, A1 to An are optional batch dimensions. Args: voxels: A tensor of shape `[A1, ..., An, Vx, Vy, Vz, Vd]`, where Vx, Vy, Vz are the dimensions of the voxel grid and Vd the dimension of the information stored in each voxel (e.g. 3 for RGB color). absorption_factor: A scalar representing the density of the volume. cell_size: A scalar representing the size of a cell. axis: An index to the projection axis (0 for X, 1 for Y or 2 for Z). name: A name for this op. Defaults to "emission_absorption_render". Returns: A tensor of shape `[A1, ..., An, Vx, Vy, Vd]` representing images of size (Vx,Vy). Raises: ValueError: If the shape of the input tensors are not supported. """ with tf.compat.v1.name_scope(name, "emission_absorption_render", [voxels]): voxels = tf.convert_to_tensor(value=voxels) shape.check_static( tensor=voxels, tensor_name="voxels", has_rank_greater_than=3) if axis not in [0, 1, 2]: raise ValueError("'axis' needs to be 0, 1 or 2") signal, density = tf.split(voxels, (-1, 1), axis=-1) density = tf.scalar_mul(absorption_factor / cell_size, density) one_minus_density = tf.ones_like(density) - density transmission = tf.math.cumprod(one_minus_density, axis=axis - 4) weight = density * transmission weight_sum = tf.reduce_sum(input_tensor=weight, axis=axis - 4) rendering = tf.reduce_sum(input_tensor=weight * signal, axis=axis - 4) rendering = rendering / (weight_sum + 1e-8) transparency = tf.reduce_prod(input_tensor=one_minus_density, axis=axis - 4) alpha = tf.ones_like(transparency) - transparency rendering = rendering * alpha image = tf.concat([rendering, alpha], axis=-1) return image # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
492
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
copybara-service[bot]
"2021-02-07T23:14:10Z"
"2021-02-11T19:18:36Z"
03973810bbcffe2b0f23dc130444277045dd21b0
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/convolution to using TensorFlow 2. - tf.compat.v1.name_scope -> tf.name_scope - tf.compat.v1.where -> tf.where - tf.compat.v1.dimension_value -> tf.compat.dimension_value Do not replace tf.compat.v1.convert_to_tensor_or_sparse_tensor as it has no TensorFlow v2 equivalent. Additional changes are made to the test code: - tf.compat.v1.keras.initializers.zeros -> tf.keras.initializers.Zeros (or 'zeros') - tf.compat.v1.constant_initializer -> tf.constant_initializer Do not remove tf.compat.v1.global_variables_initializer as it is required for tests using tf.keras.layers.Conv2DTranspose to run in graph mode. The following call site is updated: - nn.layer.graph_convolution.feature_steered_convolution_layer
./tensorflow_graphics/rendering/opengl/rasterizer_with_context.cc
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "rasterizer_with_context.h" RasterizerWithContext::RasterizerWithContext( std::unique_ptr<EGLOffscreenContext>&& egl_context, std::unique_ptr<gl_utils::Program>&& program, std::unique_ptr<gl_utils::RenderTargets>&& render_targets, float clear_red, float clear_green, float clear_blue, float clear_alpha, float clear_depth, bool enable_cull_face) : Rasterizer(std::move(program), std::move(render_targets), clear_red, clear_green, clear_blue, clear_alpha, clear_depth, enable_cull_face), egl_context_(std::move(egl_context)) {} RasterizerWithContext::~RasterizerWithContext() { // Destroy the rasterizer in the correct EGL context. auto status = egl_context_->MakeCurrent(); if (status != tensorflow::Status::OK()) std::cerr << "~RasterizerWithContext: failure to set the context as current." << std::endl; // Reset all the members of the Rasterizer parent class before destroying the // context. this->Reset(); // egl_context_ is destroyed here, which calls // egl_offscreen_context::Release(). } tensorflow::Status RasterizerWithContext::Create( int width, int height, const std::string& vertex_shader_source, const std::string& geometry_shader_source, const std::string& fragment_shader_source, std::unique_ptr<RasterizerWithContext>* rasterizer_with_context, float clear_red, float clear_green, float clear_blue, float clear_alpha, float clear_depth, bool enable_cull_face) { std::unique_ptr<gl_utils::Program> program; std::unique_ptr<gl_utils::RenderTargets> render_targets; std::vector<std::pair<std::string, GLenum>> shaders; std::unique_ptr<EGLOffscreenContext> offscreen_context; TF_RETURN_IF_ERROR(EGLOffscreenContext::Create(&offscreen_context)); TF_RETURN_IF_ERROR(offscreen_context->MakeCurrent()); // No need to have a MakeCleanup here as EGLOffscreenContext::Release() // would be called on destruction of the offscreen_context object, which // would happen here if the whole creation process was not successful. shaders.push_back(std::make_pair(vertex_shader_source, GL_VERTEX_SHADER)); shaders.push_back(std::make_pair(geometry_shader_source, GL_GEOMETRY_SHADER)); shaders.push_back(std::make_pair(fragment_shader_source, GL_FRAGMENT_SHADER)); TF_RETURN_IF_ERROR(gl_utils::Program::Create(shaders, &program)); TF_RETURN_IF_ERROR( gl_utils::RenderTargets::Create<float>(width, height, &render_targets)); TF_RETURN_IF_ERROR(offscreen_context->Release()); *rasterizer_with_context = std::unique_ptr<RasterizerWithContext>(new RasterizerWithContext( std::move(offscreen_context), std::move(program), std::move(render_targets), clear_red, clear_green, clear_blue, clear_alpha, clear_depth, enable_cull_face)); return tensorflow::Status::OK(); } tensorflow::Status RasterizerWithContext::Render(int num_points, absl::Span<float> result) { TF_RETURN_IF_ERROR(egl_context_->MakeCurrent()); auto context_cleanup = MakeCleanup([this]() { return this->egl_context_->Release(); }); TF_RETURN_IF_ERROR(Rasterizer::Render(num_points, result)); // context_cleanup calls EGLOffscreenContext::Release here. return tensorflow::Status::OK(); } tensorflow::Status RasterizerWithContext::Render( int num_points, absl::Span<unsigned char> result) { TF_RETURN_IF_ERROR(egl_context_->MakeCurrent()); auto context_cleanup = MakeCleanup([this]() { return this->egl_context_->Release(); }); TF_RETURN_IF_ERROR(Rasterizer::Render(num_points, result)); // context_cleanup calls EGLOffscreenContext::Release here. return tensorflow::Status::OK(); }
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "rasterizer_with_context.h" RasterizerWithContext::RasterizerWithContext( std::unique_ptr<EGLOffscreenContext>&& egl_context, std::unique_ptr<gl_utils::Program>&& program, std::unique_ptr<gl_utils::RenderTargets>&& render_targets, float clear_red, float clear_green, float clear_blue, float clear_alpha, float clear_depth, bool enable_cull_face) : Rasterizer(std::move(program), std::move(render_targets), clear_red, clear_green, clear_blue, clear_alpha, clear_depth, enable_cull_face), egl_context_(std::move(egl_context)) {} RasterizerWithContext::~RasterizerWithContext() { // Destroy the rasterizer in the correct EGL context. auto status = egl_context_->MakeCurrent(); if (status != tensorflow::Status::OK()) std::cerr << "~RasterizerWithContext: failure to set the context as current." << std::endl; // Reset all the members of the Rasterizer parent class before destroying the // context. this->Reset(); // egl_context_ is destroyed here, which calls // egl_offscreen_context::Release(). } tensorflow::Status RasterizerWithContext::Create( int width, int height, const std::string& vertex_shader_source, const std::string& geometry_shader_source, const std::string& fragment_shader_source, std::unique_ptr<RasterizerWithContext>* rasterizer_with_context, float clear_red, float clear_green, float clear_blue, float clear_alpha, float clear_depth, bool enable_cull_face) { std::unique_ptr<gl_utils::Program> program; std::unique_ptr<gl_utils::RenderTargets> render_targets; std::vector<std::pair<std::string, GLenum>> shaders; std::unique_ptr<EGLOffscreenContext> offscreen_context; TF_RETURN_IF_ERROR(EGLOffscreenContext::Create(&offscreen_context)); TF_RETURN_IF_ERROR(offscreen_context->MakeCurrent()); // No need to have a MakeCleanup here as EGLOffscreenContext::Release() // would be called on destruction of the offscreen_context object, which // would happen here if the whole creation process was not successful. shaders.push_back(std::make_pair(vertex_shader_source, GL_VERTEX_SHADER)); shaders.push_back(std::make_pair(geometry_shader_source, GL_GEOMETRY_SHADER)); shaders.push_back(std::make_pair(fragment_shader_source, GL_FRAGMENT_SHADER)); TF_RETURN_IF_ERROR(gl_utils::Program::Create(shaders, &program)); TF_RETURN_IF_ERROR( gl_utils::RenderTargets::Create<float>(width, height, &render_targets)); TF_RETURN_IF_ERROR(offscreen_context->Release()); *rasterizer_with_context = std::unique_ptr<RasterizerWithContext>(new RasterizerWithContext( std::move(offscreen_context), std::move(program), std::move(render_targets), clear_red, clear_green, clear_blue, clear_alpha, clear_depth, enable_cull_face)); return tensorflow::Status::OK(); } tensorflow::Status RasterizerWithContext::Render(int num_points, absl::Span<float> result) { TF_RETURN_IF_ERROR(egl_context_->MakeCurrent()); auto context_cleanup = MakeCleanup([this]() { return this->egl_context_->Release(); }); TF_RETURN_IF_ERROR(Rasterizer::Render(num_points, result)); // context_cleanup calls EGLOffscreenContext::Release here. return tensorflow::Status::OK(); } tensorflow::Status RasterizerWithContext::Render( int num_points, absl::Span<unsigned char> result) { TF_RETURN_IF_ERROR(egl_context_->MakeCurrent()); auto context_cleanup = MakeCleanup([this]() { return this->egl_context_->Release(); }); TF_RETURN_IF_ERROR(Rasterizer::Render(num_points, result)); // context_cleanup calls EGLOffscreenContext::Release here. return tensorflow::Status::OK(); }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/grid.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow grid utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _grid(starts, stops, nums): """Generates a M-D uniform axis-aligned grid. Warning: This op is not differentiable. Indeed, the gradient of tf.linspace and tf.meshgrid are currently not defined. Args: starts: A tensor of shape `[M]` representing the start points for each dimension. stops: A tensor of shape `[M]` representing the end points for each dimension. nums: A tensor of shape `[M]` representing the number of subdivisions for each dimension. Returns: A tensor of shape `[nums[0], ..., nums[M-1], M]` containing an M-D uniform grid. """ params = [tf.unstack(tensor) for tensor in [starts, stops, nums]] layout = [tf.linspace(*param) for param in zip(*params)] return tf.stack(tf.meshgrid(*layout, indexing="ij"), axis=-1) def generate(starts, stops, nums, name=None): r"""Generates a M-D uniform axis-aligned grid. Warning: This op is not differentiable. Indeed, the gradient of tf.linspace and tf.meshgrid are currently not defined. Note: In the following, `B` is an optional batch dimension. Args: starts: A tensor of shape `[M]` or `[B, M]`, where the last dimension represents a M-D start point. stops: A tensor of shape `[M]` or `[B, M]`, where the last dimension represents a M-D end point. nums: A tensor of shape `[M]` representing the number of subdivisions for each dimension. name: A name for this op. Defaults to "grid_generate". Returns: A tensor of shape `[nums[0], ..., nums[M-1], M]` containing an M-D uniform grid or a tensor of shape `[B, nums[0], ..., nums[M-1], M]` containing B M-D uniform grids. Please refer to the example below for more details. Raises: ValueError: If the shape of `starts`, `stops`, or `nums` is not supported. Examples: ```python print(generate((-1.0, -2.0), (1.0, 2.0), (3, 5))) >>> [[[-1. -2.] [-1. -1.] [-1. 0.] [-1. 1.] [-1. 2.]] [[ 0. -2.] [ 0. -1.] [ 0. 0.] [ 0. 1.] [ 0. 2.]] [[ 1. -2.] [ 1. -1.] [ 1. 0.] [ 1. 1.] [ 1. 2.]]] ``` Generates a 3x5 2d grid from -1.0 to 1.0 with 3 subdivisions for the x axis and from -2.0 to 2.0 with 5 subdivisions for the y axis. This lead to a tensor of shape (3, 5, 2). """ with tf.compat.v1.name_scope(name, "grid_generate", [starts, stops, nums]): starts = tf.convert_to_tensor(value=starts) stops = tf.convert_to_tensor(value=stops) nums = tf.convert_to_tensor(value=nums) shape.check_static( tensor=starts, tensor_name="starts", has_rank_greater_than=0, has_rank_less_than=3) shape.check_static( tensor=stops, tensor_name="stops", has_rank_greater_than=0, has_rank_less_than=3) shape.check_static(tensor=nums, tensor_name="nums", has_rank=1) shape.compare_batch_dimensions( tensors=(starts, stops), last_axes=(-1, -1), broadcast_compatible=False) shape.compare_dimensions((starts, stops, nums), -1, ("starts", "stops", "nums")) if starts.shape.ndims == 1: return _grid(starts, stops, nums) else: return tf.stack([ _grid(starts, stops, nums) for starts, stops in zip(tf.unstack(starts), tf.unstack(stops)) ]) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow grid utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _grid(starts, stops, nums): """Generates a M-D uniform axis-aligned grid. Warning: This op is not differentiable. Indeed, the gradient of tf.linspace and tf.meshgrid are currently not defined. Args: starts: A tensor of shape `[M]` representing the start points for each dimension. stops: A tensor of shape `[M]` representing the end points for each dimension. nums: A tensor of shape `[M]` representing the number of subdivisions for each dimension. Returns: A tensor of shape `[nums[0], ..., nums[M-1], M]` containing an M-D uniform grid. """ params = [tf.unstack(tensor) for tensor in [starts, stops, nums]] layout = [tf.linspace(*param) for param in zip(*params)] return tf.stack(tf.meshgrid(*layout, indexing="ij"), axis=-1) def generate(starts, stops, nums, name="grid_generate"): r"""Generates a M-D uniform axis-aligned grid. Warning: This op is not differentiable. Indeed, the gradient of tf.linspace and tf.meshgrid are currently not defined. Note: In the following, `B` is an optional batch dimension. Args: starts: A tensor of shape `[M]` or `[B, M]`, where the last dimension represents a M-D start point. stops: A tensor of shape `[M]` or `[B, M]`, where the last dimension represents a M-D end point. nums: A tensor of shape `[M]` representing the number of subdivisions for each dimension. name: A name for this op. Defaults to "grid_generate". Returns: A tensor of shape `[nums[0], ..., nums[M-1], M]` containing an M-D uniform grid or a tensor of shape `[B, nums[0], ..., nums[M-1], M]` containing B M-D uniform grids. Please refer to the example below for more details. Raises: ValueError: If the shape of `starts`, `stops`, or `nums` is not supported. Examples: ```python print(generate((-1.0, -2.0), (1.0, 2.0), (3, 5))) >>> [[[-1. -2.] [-1. -1.] [-1. 0.] [-1. 1.] [-1. 2.]] [[ 0. -2.] [ 0. -1.] [ 0. 0.] [ 0. 1.] [ 0. 2.]] [[ 1. -2.] [ 1. -1.] [ 1. 0.] [ 1. 1.] [ 1. 2.]]] ``` Generates a 3x5 2d grid from -1.0 to 1.0 with 3 subdivisions for the x axis and from -2.0 to 2.0 with 5 subdivisions for the y axis. This lead to a tensor of shape (3, 5, 2). """ with tf.name_scope(name): starts = tf.convert_to_tensor(value=starts) stops = tf.convert_to_tensor(value=stops) nums = tf.convert_to_tensor(value=nums) shape.check_static( tensor=starts, tensor_name="starts", has_rank_greater_than=0, has_rank_less_than=3) shape.check_static( tensor=stops, tensor_name="stops", has_rank_greater_than=0, has_rank_less_than=3) shape.check_static(tensor=nums, tensor_name="nums", has_rank=1) shape.compare_batch_dimensions( tensors=(starts, stops), last_axes=(-1, -1), broadcast_compatible=False) shape.compare_dimensions((starts, stops, nums), -1, ("starts", "stops", "nums")) if starts.shape.ndims == 1: return _grid(starts, stops, nums) else: return tf.stack([ _grid(starts, stops, nums) for starts, stops in zip(tf.unstack(starts), tf.unstack(stops)) ]) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/mesh/normals.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow utility functions to compute normals on meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def gather_faces(vertices, indices, name=None): """Gather corresponding vertices for each face. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, D]`, where `V` is the number of vertices and `D` the dimensionality of each vertex. The rank of this tensor should be at least 2. indices: A tensor of shape `[A1, ..., An, F, M]`, where `F` is the number of faces, and `M` is the number of vertices per face. The rank of this tensor should be at least 2. name: A name for this op. Defaults to "normals_gather_faces". Returns: A tensor of shape `[A1, ..., An, F, M, D]` containing the vertices of each face. Raises: ValueError: If the shape of `vertices` or `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_gather_faces", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=False) if hasattr(tf, "batch_gather"): expanded_vertices = tf.expand_dims(vertices, axis=-3) broadcasted_shape = tf.concat([tf.shape(input=indices)[:-1], tf.shape(input=vertices)[-2:]], axis=-1) broadcasted_vertices = tf.broadcast_to( expanded_vertices, broadcasted_shape) return tf.compat.v1.batch_gather(broadcasted_vertices, indices) else: return tf.gather( vertices, indices, axis=-2, batch_dims=indices.shape.ndims - 2) def face_normals(faces, clockwise=True, normalize=True, name=None): """Computes face normals for meshes. This function supports planar convex polygon faces. Note that for non-triangular faces, this function uses the first 3 vertices of each face to calculate the face normal. Note: In the following, A1 to An are optional batch dimensions. Args: faces: A tensor of shape `[A1, ..., An, M, 3]`, which stores vertices positions of each face, where M is the number of vertices of each face. The rank of this tensor should be at least 2. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. normalize: A `bool` defining whether output normals are normalized. name: A name for this op. Defaults to "normals_face_normals". Returns: A tensor of shape `[A1, ..., An, 3]` containing the face normals. Raises: ValueError: If the shape of `vertices`, `faces` is not supported. """ with tf.compat.v1.name_scope(name, "normals_face_normals", [faces]): faces = tf.convert_to_tensor(value=faces) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 2)) vertices = tf.unstack(faces, axis=-2) vertices = vertices[:3] return triangle.normal(*vertices, clockwise=clockwise, normalize=normalize) def vertex_normals(vertices, indices, clockwise=True, name=None): """Computes vertex normals from a mesh. This function computes vertex normals as the weighted sum of the adjacent face normals, where the weights correspond to the area of each face. This function supports planar convex polygon faces. For non-triangular meshes, this function converts them into triangular meshes to calculate vertex normals. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. indices: A tensor of shape `[A1, ..., An, F, M]`, where F is the number of faces and M is the number of vertices per face. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. name: A name for this op. Defaults to "normals_vertex_normals". Returns: A tensor of shape `[A1, ..., An, V, 3]` containing vertex normals. If vertices and indices have different batch dimensions, this function broadcasts them into the same batch dimensions and the output batch dimensions are the broadcasted. Raises: ValueError: If the shape of `vertices`, `indices` is not supported. """ with tf.compat.v1.name_scope(name, "normals_vertex_normals", [vertices, indices]): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1, has_dim_greater_than=(-1, 2)) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=True) shape_indices = indices.shape.as_list() if None in shape_indices[:-2]: raise ValueError("'indices' must have specified batch dimensions.") common_batch_dims = shape.get_broadcasted_shape(vertices.shape[:-2], indices.shape[:-2]) vertices_repeat = [ common_batch_dims[x] // vertices.shape.as_list()[x] for x in range(len(common_batch_dims)) ] indices_repeat = [ common_batch_dims[x] // shape_indices[x] for x in range(len(common_batch_dims)) ] vertices = tf.tile( vertices, vertices_repeat + [1, 1], name="vertices_broadcast") indices = tf.tile( indices, indices_repeat + [1, 1], name="indices_broadcast") # Triangulate non-triangular faces. if shape_indices[-1] > 3: triangle_indices = [] for i in range(1, shape_indices[-1] - 1): triangle_indices.append( tf.concat((indices[..., 0:1], indices[..., i:i + 2]), axis=-1)) indices = tf.concat(triangle_indices, axis=-2) shape_indices = indices.shape.as_list() face_vertices = gather_faces(vertices, indices) # Use unnormalized face normals to scale normals by area. mesh_face_normals = face_normals( face_vertices, clockwise=clockwise, normalize=False) if vertices.shape.ndims > 2: outer_indices = np.meshgrid( *[np.arange(i) for i in shape_indices[:-2]], sparse=False, indexing="ij") outer_indices = [np.expand_dims(i, axis=-1) for i in outer_indices] outer_indices = np.concatenate(outer_indices, axis=-1) outer_indices = np.expand_dims(outer_indices, axis=-2) outer_indices = tf.constant(outer_indices, dtype=tf.int32) outer_indices = tf.tile(outer_indices, [1] * len(shape_indices[:-2]) + [tf.shape(input=indices)[-2]] + [1]) unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): scatter_indices = tf.concat([outer_indices, indices[..., i:i + 1]], axis=-1) unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, scatter_indices, mesh_face_normals) else: unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): unnormalized_vertex_normals = tf.compat.v1.tensor_scatter_add( unnormalized_vertex_normals, indices[..., i:i + 1], mesh_face_normals) vector_norms = tf.sqrt( tf.reduce_sum( input_tensor=unnormalized_vertex_normals**2, axis=-1, keepdims=True)) return safe_ops.safe_unsigned_div(unnormalized_vertex_normals, vector_norms) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow utility functions to compute normals on meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def gather_faces(vertices, indices, name="normals_gather_faces"): """Gather corresponding vertices for each face. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, D]`, where `V` is the number of vertices and `D` the dimensionality of each vertex. The rank of this tensor should be at least 2. indices: A tensor of shape `[A1, ..., An, F, M]`, where `F` is the number of faces, and `M` is the number of vertices per face. The rank of this tensor should be at least 2. name: A name for this op. Defaults to "normals_gather_faces". Returns: A tensor of shape `[A1, ..., An, F, M, D]` containing the vertices of each face. Raises: ValueError: If the shape of `vertices` or `indices` is not supported. """ with tf.name_scope(name): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=False) if hasattr(tf, "batch_gather"): expanded_vertices = tf.expand_dims(vertices, axis=-3) broadcasted_shape = tf.concat([tf.shape(input=indices)[:-1], tf.shape(input=vertices)[-2:]], axis=-1) broadcasted_vertices = tf.broadcast_to( expanded_vertices, broadcasted_shape) return tf.gather(broadcasted_vertices, indices, batch_dims=-1) else: return tf.gather( vertices, indices, axis=-2, batch_dims=indices.shape.ndims - 2) def face_normals(faces, clockwise=True, normalize=True, name="normals_face_normals"): """Computes face normals for meshes. This function supports planar convex polygon faces. Note that for non-triangular faces, this function uses the first 3 vertices of each face to calculate the face normal. Note: In the following, A1 to An are optional batch dimensions. Args: faces: A tensor of shape `[A1, ..., An, M, 3]`, which stores vertices positions of each face, where M is the number of vertices of each face. The rank of this tensor should be at least 2. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. normalize: A `bool` defining whether output normals are normalized. name: A name for this op. Defaults to "normals_face_normals". Returns: A tensor of shape `[A1, ..., An, 3]` containing the face normals. Raises: ValueError: If the shape of `vertices`, `faces` is not supported. """ with tf.name_scope(name): faces = tf.convert_to_tensor(value=faces) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 2)) vertices = tf.unstack(faces, axis=-2) vertices = vertices[:3] return triangle.normal(*vertices, clockwise=clockwise, normalize=normalize) def vertex_normals(vertices, indices, clockwise=True, name="normals_vertex_normals"): """Computes vertex normals from a mesh. This function computes vertex normals as the weighted sum of the adjacent face normals, where the weights correspond to the area of each face. This function supports planar convex polygon faces. For non-triangular meshes, this function converts them into triangular meshes to calculate vertex normals. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. indices: A tensor of shape `[A1, ..., An, F, M]`, where F is the number of faces and M is the number of vertices per face. clockwise: Winding order to determine front-facing faces. The order of vertices should be either clockwise or counterclockwise. name: A name for this op. Defaults to "normals_vertex_normals". Returns: A tensor of shape `[A1, ..., An, V, 3]` containing vertex normals. If vertices and indices have different batch dimensions, this function broadcasts them into the same batch dimensions and the output batch dimensions are the broadcasted. Raises: ValueError: If the shape of `vertices`, `indices` is not supported. """ with tf.name_scope(name): vertices = tf.convert_to_tensor(value=vertices) indices = tf.convert_to_tensor(value=indices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=(-1, 3)) shape.check_static( tensor=indices, tensor_name="indices", has_rank_greater_than=1, has_dim_greater_than=(-1, 2)) shape.compare_batch_dimensions( tensors=(vertices, indices), last_axes=(-3, -3), broadcast_compatible=True) shape_indices = indices.shape.as_list() if None in shape_indices[:-2]: raise ValueError("'indices' must have specified batch dimensions.") common_batch_dims = shape.get_broadcasted_shape(vertices.shape[:-2], indices.shape[:-2]) vertices_repeat = [ common_batch_dims[x] // vertices.shape.as_list()[x] for x in range(len(common_batch_dims)) ] indices_repeat = [ common_batch_dims[x] // shape_indices[x] for x in range(len(common_batch_dims)) ] vertices = tf.tile( vertices, vertices_repeat + [1, 1], name="vertices_broadcast") indices = tf.tile( indices, indices_repeat + [1, 1], name="indices_broadcast") # Triangulate non-triangular faces. if shape_indices[-1] > 3: triangle_indices = [] for i in range(1, shape_indices[-1] - 1): triangle_indices.append( tf.concat((indices[..., 0:1], indices[..., i:i + 2]), axis=-1)) indices = tf.concat(triangle_indices, axis=-2) shape_indices = indices.shape.as_list() face_vertices = gather_faces(vertices, indices) # Use unnormalized face normals to scale normals by area. mesh_face_normals = face_normals( face_vertices, clockwise=clockwise, normalize=False) if vertices.shape.ndims > 2: outer_indices = np.meshgrid( *[np.arange(i) for i in shape_indices[:-2]], sparse=False, indexing="ij") outer_indices = [np.expand_dims(i, axis=-1) for i in outer_indices] outer_indices = np.concatenate(outer_indices, axis=-1) outer_indices = np.expand_dims(outer_indices, axis=-2) outer_indices = tf.constant(outer_indices, dtype=tf.int32) outer_indices = tf.tile(outer_indices, [1] * len(shape_indices[:-2]) + [tf.shape(input=indices)[-2]] + [1]) unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): scatter_indices = tf.concat([outer_indices, indices[..., i:i + 1]], axis=-1) unnormalized_vertex_normals = tf.tensor_scatter_nd_add( unnormalized_vertex_normals, scatter_indices, mesh_face_normals) else: unnormalized_vertex_normals = tf.zeros_like(vertices) for i in range(shape_indices[-1]): unnormalized_vertex_normals = tf.tensor_scatter_nd_add( unnormalized_vertex_normals, indices[..., i:i + 1], mesh_face_normals) vector_norms = tf.sqrt( tf.reduce_sum( input_tensor=unnormalized_vertex_normals**2, axis=-1, keepdims=True)) return safe_ops.safe_unsigned_div(unnormalized_vertex_normals, vector_norms) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/mesh/sampler.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Computes a weighted point sampling of a triangular mesh. This op computes a uniform sampling of points on the surface of the mesh. Points are sampled from the surface of each triangle using a uniform distribution, proportional to a specified face density (e.g. face area). Uses the approach mentioned in the TOG 2002 paper "Shape distributions" (https://dl.acm.org/citation.cfm?id=571648) to generate random barycentric coordinates. This op can be used for several tasks, including better mesh reconstruction. For example, see these recent papers demonstrating reconstruction losses using this op: 1. "GEOMetrics: Exploiting Geometric Structure for Graph-Encoded Objects" (https://arxiv.org/abs/1901.11461) ICML 2019. 2. "Mesh R-CNN" (https://arxiv.org/abs/1906.02739) ICCV 2019. Op is differentiable w.r.t mesh vertex positions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def triangle_area(vertex0, vertex1, vertex2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. In the following, A1 to An are optional batch dimensions. Args: vertex0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. vertex1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. vertex2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents the triangle areas. """ with tf.compat.v1.name_scope(name, "triangle_area"): vertex0 = tf.convert_to_tensor(value=vertex0) vertex1 = tf.convert_to_tensor(value=vertex1) vertex2 = tf.convert_to_tensor(value=vertex2) triangle_normals = triangle.normal( vertex0, vertex1, vertex2, normalize=False) areas = 0.5 * tf.linalg.norm(tensor=triangle_normals, axis=-1) return areas def _random_categorical_sample(num_samples, weights, seed=None, stateless=False, name=None, sample_dtype=tf.int32): """Samples from a categorical distribution with arbitrary batch dimensions. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional random seed, value depends on `stateless`. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "random_categorical_sample". sample_dtype: Type of output samples. Returns: A `sample_dtype` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "random_categorical_sample"): asserts.assert_all_above(weights, 0) logits = tf.math.log(weights) num_faces = tf.shape(input=logits)[-1] batch_shape = tf.shape(input=logits)[:-1] logits_2d = tf.reshape(logits, [-1, num_faces]) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_categorical else: sample_fn = tf.random.categorical draws = sample_fn( logits=logits_2d, num_samples=num_samples, dtype=sample_dtype, seed=seed) samples = tf.reshape( draws, shape=tf.concat((batch_shape, (num_samples,)), axis=0)) return samples def generate_random_face_indices(num_samples, face_weights, seed=None, stateless=False, name=None): """Generate a sample of face ids given per face probability. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. face_weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional seed for the random number generator. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_face_indices". Returns: An `int32` tensor of shape `[A1, ..., An, num_samples]` denoting sampled face indices. """ with tf.compat.v1.name_scope(name, "generate_random_face_indices"): num_samples = tf.convert_to_tensor(value=num_samples) face_weights = tf.convert_to_tensor(value=face_weights) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.check_static( tensor=num_samples, tensor_name="num_samples", has_rank=0) face_weights = asserts.assert_all_above(face_weights, minval=0.0) eps = asserts.select_eps_for_division(face_weights.dtype) face_weights = face_weights + eps sampled_face_indices = _random_categorical_sample( num_samples=num_samples, weights=face_weights, seed=seed, stateless=stateless) return sampled_face_indices def generate_random_barycentric_coordinates(sample_shape, dtype=tf.dtypes.float32, seed=None, stateless=False, name=None): """Generate uniformly sampled random barycentric coordinates. Note: In the following, A1 to An are optional batch dimensions. Args: sample_shape: An `int` tensor with shape `[n+1,]` and values `(A1, ..., An, num_samples)` denoting total number of random samples drawn, where `n` is number of batch dimensions, and `num_samples` is the number of samples drawn for each mesh. dtype: Optional type of generated barycentric coordinates, defaults to float32. seed: An optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_barycentric_coordinates". Returns: A `dtype` tensor of shape [A1, ..., An, num_samples, 3], where the last dimension contains the sampled barycentric coordinates. """ with tf.compat.v1.name_scope(name, "generate_random_barycentric_coordinates"): sample_shape = tf.convert_to_tensor(value=sample_shape) shape.check_static( tensor=sample_shape, tensor_name="sample_shape", has_rank=1) sample_shape = tf.concat((sample_shape, (2,)), axis=0) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_uniform else: sample_fn = tf.random.uniform random_uniform = sample_fn( shape=sample_shape, minval=0.0, maxval=1.0, dtype=dtype, seed=seed) random1 = tf.sqrt(random_uniform[..., 0]) random2 = random_uniform[..., 1] barycentric = tf.stack( (1 - random1, random1 * (1 - random2), random1 * random2), axis=-1) return barycentric def weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, face_weights, seed=None, stateless=False, name=None): """Performs a face probability weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of each vertex. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: A `int` 0-D tensor denoting number of samples to be drawn from each mesh. face_weights: A `float` tensor of shape ``[A1, ..., An, F]`, denoting unnormalized sampling probability of each face, where F is the number of faces. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "weighted_random_sample_triangle_mesh". Returns: sample_points: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) face_weights = tf.convert_to_tensor(value=face_weights) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.compare_batch_dimensions( tensors=(faces, face_weights), last_axes=(-2, -1), tensor_names=("faces", "face_weights"), broadcast_compatible=False) shape.compare_batch_dimensions( tensors=(vertex_attributes, faces, face_weights), last_axes=(-3, -3, -2), tensor_names=("vertex_attributes", "faces", "face_weights"), broadcast_compatible=False) asserts.assert_all_above(face_weights, 0) batch_dims = faces.shape.ndims - 2 batch_shape = faces.shape.as_list()[:-2] sample_shape = tf.concat( (batch_shape, tf.convert_to_tensor( value=(num_samples,), dtype=tf.int32)), axis=0) sample_face_indices = generate_random_face_indices( num_samples, face_weights, seed=seed, stateless=stateless) sample_vertex_indices = tf.gather( faces, sample_face_indices, batch_dims=batch_dims) sample_vertices = tf.gather( vertex_attributes, sample_vertex_indices, batch_dims=batch_dims) barycentric = generate_random_barycentric_coordinates( sample_shape, dtype=vertex_attributes.dtype, seed=seed, stateless=stateless) barycentric = tf.expand_dims(barycentric, axis=-1) sample_points = tf.math.multiply(sample_vertices, barycentric) sample_points = tf.reduce_sum(input_tensor=sample_points, axis=-2) return sample_points, sample_face_indices def area_weighted_random_sample_triangle_mesh(vertex_attributes, faces, num_samples, vertex_positions=None, seed=None, stateless=False, name=None): """Performs a face area weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of a feature defined on each vertex. If `vertex_positions` is not provided, then first 3 dimensions of `vertex_attributes` denote the vertex positions. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: An `int` scalar denoting number of samples to be drawn from each mesh. vertex_positions: An optional `float` tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. If None, then vertex_attributes[..., :3] is used as vertex positions. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "area_weighted_random_sample_triangle_mesh". Returns: sample_pts: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.compat.v1.name_scope(name, "area_weighted_random_sample_triangle_mesh"): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_dim_greater_than=(-1, 2)) if vertex_positions is not None: vertex_positions = tf.convert_to_tensor(value=vertex_positions) else: vertex_positions = vertex_attributes[..., :3] shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_rank_greater_than=1) shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_dim_equals=(-1, 3)) triangle_vertex_positions = normals.gather_faces(vertex_positions, faces) triangle_areas = triangle_area(triangle_vertex_positions[..., 0, :], triangle_vertex_positions[..., 1, :], triangle_vertex_positions[..., 2, :]) return weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, face_weights=triangle_areas, seed=seed, stateless=stateless) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Computes a weighted point sampling of a triangular mesh. This op computes a uniform sampling of points on the surface of the mesh. Points are sampled from the surface of each triangle using a uniform distribution, proportional to a specified face density (e.g. face area). Uses the approach mentioned in the TOG 2002 paper "Shape distributions" (https://dl.acm.org/citation.cfm?id=571648) to generate random barycentric coordinates. This op can be used for several tasks, including better mesh reconstruction. For example, see these recent papers demonstrating reconstruction losses using this op: 1. "GEOMetrics: Exploiting Geometric Structure for Graph-Encoded Objects" (https://arxiv.org/abs/1901.11461) ICML 2019. 2. "Mesh R-CNN" (https://arxiv.org/abs/1906.02739) ICCV 2019. Op is differentiable w.r.t mesh vertex positions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.representation import triangle from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def triangle_area(vertex0, vertex1, vertex2, name="triangle_area"): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. In the following, A1 to An are optional batch dimensions. Args: vertex0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. vertex1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. vertex2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents the triangle areas. """ with tf.name_scope(name): vertex0 = tf.convert_to_tensor(value=vertex0) vertex1 = tf.convert_to_tensor(value=vertex1) vertex2 = tf.convert_to_tensor(value=vertex2) triangle_normals = triangle.normal( vertex0, vertex1, vertex2, normalize=False) areas = 0.5 * tf.linalg.norm(tensor=triangle_normals, axis=-1) return areas def _random_categorical_sample(num_samples, weights, seed=None, stateless=False, name="random_categorical_sample", sample_dtype=tf.int32): """Samples from a categorical distribution with arbitrary batch dimensions. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional random seed, value depends on `stateless`. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "random_categorical_sample". sample_dtype: Type of output samples. Returns: A `sample_dtype` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.name_scope(name): asserts.assert_all_above(weights, 0) logits = tf.math.log(weights) num_faces = tf.shape(input=logits)[-1] batch_shape = tf.shape(input=logits)[:-1] logits_2d = tf.reshape(logits, [-1, num_faces]) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_categorical else: sample_fn = tf.random.categorical draws = sample_fn( logits=logits_2d, num_samples=num_samples, dtype=sample_dtype, seed=seed) samples = tf.reshape( draws, shape=tf.concat((batch_shape, (num_samples,)), axis=0)) return samples def generate_random_face_indices(num_samples, face_weights, seed=None, stateless=False, name="generate_random_face_indices"): """Generate a sample of face ids given per face probability. Note: In the following, A1 to An are optional batch dimensions. Args: num_samples: An `int32` scalar denoting the number of samples to generate per mesh. face_weights: A `float` tensor of shape `[A1, ..., An, F]` where F is number of faces. All weights must be > 0. seed: Optional seed for the random number generator. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_face_indices". Returns: An `int32` tensor of shape `[A1, ..., An, num_samples]` denoting sampled face indices. """ with tf.name_scope(name): num_samples = tf.convert_to_tensor(value=num_samples) face_weights = tf.convert_to_tensor(value=face_weights) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.check_static( tensor=num_samples, tensor_name="num_samples", has_rank=0) face_weights = asserts.assert_all_above(face_weights, minval=0.0) eps = asserts.select_eps_for_division(face_weights.dtype) face_weights = face_weights + eps sampled_face_indices = _random_categorical_sample( num_samples=num_samples, weights=face_weights, seed=seed, stateless=stateless) return sampled_face_indices def generate_random_barycentric_coordinates( sample_shape, dtype=tf.dtypes.float32, seed=None, stateless=False, name="generate_random_barycentric_coordinates"): """Generate uniformly sampled random barycentric coordinates. Note: In the following, A1 to An are optional batch dimensions. Args: sample_shape: An `int` tensor with shape `[n+1,]` and values `(A1, ..., An, num_samples)` denoting total number of random samples drawn, where `n` is number of batch dimensions, and `num_samples` is the number of samples drawn for each mesh. dtype: Optional type of generated barycentric coordinates, defaults to float32. seed: An optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then `seed` must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate the same reproducible sequence across calls. If stateless=False, then a stateful random number generator is used (default behavior). name: Name for op. Defaults to "generate_random_barycentric_coordinates". Returns: A `dtype` tensor of shape [A1, ..., An, num_samples, 3], where the last dimension contains the sampled barycentric coordinates. """ with tf.name_scope(name): sample_shape = tf.convert_to_tensor(value=sample_shape) shape.check_static( tensor=sample_shape, tensor_name="sample_shape", has_rank=1) sample_shape = tf.concat((sample_shape, (2,)), axis=0) if stateless: seed = tf.convert_to_tensor(value=seed) shape.check_static( tensor=seed, tensor_name="seed", has_dim_equals=(-1, 2)) sample_fn = tf.random.stateless_uniform else: sample_fn = tf.random.uniform random_uniform = sample_fn( shape=sample_shape, minval=0.0, maxval=1.0, dtype=dtype, seed=seed) random1 = tf.sqrt(random_uniform[..., 0]) random2 = random_uniform[..., 1] barycentric = tf.stack( (1 - random1, random1 * (1 - random2), random1 * random2), axis=-1) return barycentric def weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, face_weights, seed=None, stateless=False, name="weighted_random_sample_triangle_mesh"): """Performs a face probability weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of each vertex. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: A `int` 0-D tensor denoting number of samples to be drawn from each mesh. face_weights: A `float` tensor of shape ``[A1, ..., An, F]`, denoting unnormalized sampling probability of each face, where F is the number of faces. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "weighted_random_sample_triangle_mesh". Returns: sample_points: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.name_scope(name): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) face_weights = tf.convert_to_tensor(value=face_weights) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=faces, tensor_name="faces", has_rank_greater_than=1) shape.check_static( tensor=face_weights, tensor_name="face_weights", has_rank_greater_than=0) shape.compare_batch_dimensions( tensors=(faces, face_weights), last_axes=(-2, -1), tensor_names=("faces", "face_weights"), broadcast_compatible=False) shape.compare_batch_dimensions( tensors=(vertex_attributes, faces, face_weights), last_axes=(-3, -3, -2), tensor_names=("vertex_attributes", "faces", "face_weights"), broadcast_compatible=False) asserts.assert_all_above(face_weights, 0) batch_dims = faces.shape.ndims - 2 batch_shape = faces.shape.as_list()[:-2] sample_shape = tf.concat( (batch_shape, tf.convert_to_tensor( value=(num_samples,), dtype=tf.int32)), axis=0) sample_face_indices = generate_random_face_indices( num_samples, face_weights, seed=seed, stateless=stateless) sample_vertex_indices = tf.gather( faces, sample_face_indices, batch_dims=batch_dims) sample_vertices = tf.gather( vertex_attributes, sample_vertex_indices, batch_dims=batch_dims) barycentric = generate_random_barycentric_coordinates( sample_shape, dtype=vertex_attributes.dtype, seed=seed, stateless=stateless) barycentric = tf.expand_dims(barycentric, axis=-1) sample_points = tf.math.multiply(sample_vertices, barycentric) sample_points = tf.reduce_sum(input_tensor=sample_points, axis=-2) return sample_points, sample_face_indices def area_weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, vertex_positions=None, seed=None, stateless=False, name="area_weighted_random_sample_triangle_mesh"): """Performs a face area weighted random sampling of a tri mesh. Note: In the following, A1 to An are optional batch dimensions. Args: vertex_attributes: A `float` tensor of shape `[A1, ..., An, V, D]`, where V is the number of vertices, and D is dimensionality of a feature defined on each vertex. If `vertex_positions` is not provided, then first 3 dimensions of `vertex_attributes` denote the vertex positions. faces: A `int` tensor of shape `[A1, ..., An, F, 3]`, where F is the number of faces. num_samples: An `int` scalar denoting number of samples to be drawn from each mesh. vertex_positions: An optional `float` tensor of shape `[A1, ..., An, V, 3]`, where V is the number of vertices. If None, then vertex_attributes[..., :3] is used as vertex positions. seed: Optional random seed. stateless: Optional flag to use stateless random sampler. If stateless=True, then seed must be provided as shape `[2]` int tensor. Stateless random sampling is useful for testing to generate same sequence across calls. name: Name for op. Defaults to "area_weighted_random_sample_triangle_mesh". Returns: sample_pts: A `float` tensor of shape `[A1, ..., An, num_samples, D]`, where D is dimensionality of each sampled point. sample_face_indices: A `int` tensor of shape `[A1, ..., An, num_samples]`. """ with tf.name_scope(name): faces = tf.convert_to_tensor(value=faces) vertex_attributes = tf.convert_to_tensor(value=vertex_attributes) num_samples = tf.convert_to_tensor(value=num_samples) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_rank_greater_than=1) shape.check_static( tensor=vertex_attributes, tensor_name="vertex_attributes", has_dim_greater_than=(-1, 2)) if vertex_positions is not None: vertex_positions = tf.convert_to_tensor(value=vertex_positions) else: vertex_positions = vertex_attributes[..., :3] shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_rank_greater_than=1) shape.check_static( tensor=vertex_positions, tensor_name="vertex_positions", has_dim_equals=(-1, 3)) triangle_vertex_positions = normals.gather_faces(vertex_positions, faces) triangle_areas = triangle_area(triangle_vertex_positions[..., 0, :], triangle_vertex_positions[..., 1, :], triangle_vertex_positions[..., 2, :]) return weighted_random_sample_triangle_mesh( vertex_attributes, faces, num_samples, face_weights=triangle_areas, seed=seed, stateless=stateless) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/point.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow point utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def distance_to_ray(point, origin, direction, keepdims=True, name=None): """Computes the distance from a M-d point to a M-d ray. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, M]`. origin: A tensor of shape `[A1, ..., An, M]`. direction: A tensor of shape `[A1, ..., An, M]`. The last dimension must be normalized. keepdims: A `bool`, whether to keep the last dimension with length 1 or to remove it. name: A name for this op. Defaults to "point_distance_to_ray". Returns: A tensor of shape `[A1, ..., An, 1]` containing the distance from each point to the corresponding ray. Raises: ValueError: If the shape of `point`, `origin`, or 'direction' is not supported. """ with tf.compat.v1.name_scope(name, "point_distance_to_ray", [point, origin, direction]): point = tf.convert_to_tensor(value=point) origin = tf.convert_to_tensor(value=origin) direction = tf.convert_to_tensor(value=direction) shape.compare_dimensions((point, origin, direction), -1, ("point", "origin", "direction")) shape.compare_batch_dimensions( tensors=(point, origin, direction), last_axes=-2, broadcast_compatible=True) direction = asserts.assert_normalized(direction) vec = point - origin dot = vector.dot(vec, direction) vec -= dot * direction return tf.norm(tensor=vec, axis=-1, keepdims=keepdims) def project_to_ray(point, origin, direction, name=None): """Computes the projection of a M-d point on a M-d ray. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, M]`. origin: A tensor of shape `[A1, ..., An, M]`. direction: A tensor of shape `[A1, ..., An, M]`. The last dimension must be normalized. name: A name for this op. Defaults to "point_project_to_ray". Returns: A tensor of shape `[A1, ..., An, M]` containing the projected point. Raises: ValueError: If the shape of `point`, `origin`, or 'direction' is not supported. """ with tf.compat.v1.name_scope(name, "point_project_to_ray", [point, origin, direction]): point = tf.convert_to_tensor(value=point) origin = tf.convert_to_tensor(value=origin) direction = tf.convert_to_tensor(value=direction) shape.compare_dimensions((point, origin, direction), -1, ("point", "origin", "direction")) shape.compare_batch_dimensions( tensors=(point, origin, direction), last_axes=-2, broadcast_compatible=True) direction = asserts.assert_normalized(direction) vec = point - origin dot = vector.dot(vec, direction) return origin + dot * direction # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow point utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def distance_to_ray(point, origin, direction, keepdims=True, name="point_distance_to_ray"): """Computes the distance from a M-d point to a M-d ray. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, M]`. origin: A tensor of shape `[A1, ..., An, M]`. direction: A tensor of shape `[A1, ..., An, M]`. The last dimension must be normalized. keepdims: A `bool`, whether to keep the last dimension with length 1 or to remove it. name: A name for this op. Defaults to "point_distance_to_ray". Returns: A tensor of shape `[A1, ..., An, 1]` containing the distance from each point to the corresponding ray. Raises: ValueError: If the shape of `point`, `origin`, or 'direction' is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) origin = tf.convert_to_tensor(value=origin) direction = tf.convert_to_tensor(value=direction) shape.compare_dimensions((point, origin, direction), -1, ("point", "origin", "direction")) shape.compare_batch_dimensions( tensors=(point, origin, direction), last_axes=-2, broadcast_compatible=True) direction = asserts.assert_normalized(direction) vec = point - origin dot = vector.dot(vec, direction) vec -= dot * direction return tf.norm(tensor=vec, axis=-1, keepdims=keepdims) def project_to_ray(point, origin, direction, name="point_project_to_ray"): """Computes the projection of a M-d point on a M-d ray. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, M]`. origin: A tensor of shape `[A1, ..., An, M]`. direction: A tensor of shape `[A1, ..., An, M]`. The last dimension must be normalized. name: A name for this op. Defaults to "point_project_to_ray". Returns: A tensor of shape `[A1, ..., An, M]` containing the projected point. Raises: ValueError: If the shape of `point`, `origin`, or 'direction' is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) origin = tf.convert_to_tensor(value=origin) direction = tf.convert_to_tensor(value=direction) shape.compare_dimensions((point, origin, direction), -1, ("point", "origin", "direction")) shape.compare_batch_dimensions( tensors=(point, origin, direction), last_axes=-2, broadcast_compatible=True) direction = asserts.assert_normalized(direction) vec = point - origin dot = vector.dot(vec, direction) return origin + dot * direction # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/ray.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow ray utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def triangulate(startpoints, endpoints, weights, name=None): """Triangulates 3d points by miminizing the sum of squared distances to rays. The rays are defined by their start points and endpoints. At least two rays are required to triangulate any given point. Contrary to the standard reprojection-error metric, the sum of squared distances to rays can be minimized in a closed form. Note: In the following, A1 to An are optional batch dimensions. Args: startpoints: A tensor of ray start points with shape `[A1, ..., An, V, 3]`, the number of rays V around which the solution points live should be greater or equal to 2, otherwise triangulation is impossible. endpoints: A tensor of ray endpoints with shape `[A1, ..., An, V, 3]`, the number of rays V around which the solution points live should be greater or equal to 2, otherwise triangulation is impossible. The `endpoints` tensor should have the same shape as the `startpoints` tensor. weights: A tensor of ray weights (certainties) with shape `[A1, ..., An, V]`. Weights should have all positive entries. Weight should have at least two non-zero entries for each point (at least two rays should have certainties > 0). name: A name for this op. The default value of None means "ray_triangulate". Returns: A tensor of triangulated points with shape `[A1, ..., An, 3]`. Raises: ValueError: If the shape of the arguments is not supported. """ with tf.compat.v1.name_scope(name, "ray_triangulate", [startpoints, endpoints, weights]): startpoints = tf.convert_to_tensor(value=startpoints) endpoints = tf.convert_to_tensor(value=endpoints) weights = tf.convert_to_tensor(value=weights) shape.check_static( tensor=startpoints, tensor_name="startpoints", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 1)) shape.check_static( tensor=endpoints, tensor_name="endpoints", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 1)) shape.compare_batch_dimensions( tensors=(startpoints, endpoints, weights), last_axes=(-2, -2, -1), broadcast_compatible=False) weights = asserts.assert_all_above(weights, 0.0, open_bound=False) weights = asserts.assert_at_least_k_non_zero_entries(weights, k=2) left_hand_side_list = [] right_hand_side_list = [] # TODO(b/130892100): Replace the inefficient for loop and add comments here. for ray_id in range(weights.shape[-1]): weights_single_ray = weights[..., ray_id] startpoints_single_ray = startpoints[..., ray_id, :] endpoints_singleview = endpoints[..., ray_id, :] ray = endpoints_singleview - startpoints_single_ray ray = tf.nn.l2_normalize(ray, axis=-1) ray_x, ray_y, ray_z = tf.unstack(ray, axis=-1) zeros = tf.zeros_like(ray_x) cross_product_matrix = tf.stack( (zeros, -ray_z, ray_y, ray_z, zeros, -ray_x, -ray_y, ray_x, zeros), axis=-1) cross_product_matrix_shape = tf.concat( (tf.shape(input=cross_product_matrix)[:-1], (3, 3)), axis=-1) cross_product_matrix = tf.reshape( cross_product_matrix, shape=cross_product_matrix_shape) weights_single_ray = tf.expand_dims(weights_single_ray, axis=-1) weights_single_ray = tf.expand_dims(weights_single_ray, axis=-1) left_hand_side = weights_single_ray * cross_product_matrix left_hand_side_list.append(left_hand_side) dot_product = tf.matmul(cross_product_matrix, tf.expand_dims(startpoints_single_ray, axis=-1)) right_hand_side = weights_single_ray * dot_product right_hand_side_list.append(right_hand_side) left_hand_side_multi_rays = tf.concat(left_hand_side_list, axis=-2) right_hand_side_multi_rays = tf.concat(right_hand_side_list, axis=-2) points = tf.linalg.lstsq(left_hand_side_multi_rays, right_hand_side_multi_rays) points = tf.squeeze(points, axis=-1) return points # TODO(b/130893491): Add batch support for radii and return [A1, ... , 3, 2]. def intersection_ray_sphere(sphere_center, sphere_radius, ray, point_on_ray, name=None): """Finds positions and surface normals where the sphere and the ray intersect. Note: In the following, A1 to An are optional batch dimensions. Args: sphere_center: A tensor of shape `[3]` representing the 3d sphere center. sphere_radius: A tensor of shape `[1]` containing a strictly positive value defining the radius of the sphere. ray: A tensor of shape `[A1, ..., An, 3]` containing normalized 3D vectors. point_on_ray: A tensor of shape `[A1, ..., An, 3]`. name: A name for this op. The default value of None means "ray_intersection_ray_sphere". Returns: A tensor of shape `[2, A1, ..., An, 3]` containing the position of the intersections, and a tensor of shape `[2, A1, ..., An, 3]` the associated surface normals at that point. Both tensors contain NaNs when there is no intersections. The first dimension of the returned tensor provides access to the first and second intersections of the ray with the sphere. Raises: ValueError: if the shape of `sphere_center`, `sphere_radius`, `ray` or `point_on_ray` is not supported. tf.errors.InvalidArgumentError: If `ray` is not normalized. """ with tf.compat.v1.name_scope( name, "ray_intersection_ray_sphere", [sphere_center, sphere_radius, ray, point_on_ray]): sphere_center = tf.convert_to_tensor(value=sphere_center) sphere_radius = tf.convert_to_tensor(value=sphere_radius) ray = tf.convert_to_tensor(value=ray) point_on_ray = tf.convert_to_tensor(value=point_on_ray) shape.check_static( tensor=sphere_center, tensor_name="sphere_center", has_rank=1, has_dim_equals=(0, 3)) shape.check_static( tensor=sphere_radius, tensor_name="sphere_radius", has_rank=1, has_dim_equals=(0, 1)) shape.check_static(tensor=ray, tensor_name="ray", has_dim_equals=(-1, 3)) shape.check_static( tensor=point_on_ray, tensor_name="point_on_ray", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(ray, point_on_ray), last_axes=(-2, -2), broadcast_compatible=False) sphere_radius = asserts.assert_all_above( sphere_radius, 0.0, open_bound=True) ray = asserts.assert_normalized(ray) vector_sphere_center_to_point_on_ray = sphere_center - point_on_ray distance_sphere_center_to_point_on_ray = tf.norm( tensor=vector_sphere_center_to_point_on_ray, axis=-1, keepdims=True) distance_projection_sphere_center_on_ray = vector.dot( vector_sphere_center_to_point_on_ray, ray) closest_distance_sphere_center_to_ray = tf.sqrt( tf.square(distance_sphere_center_to_point_on_ray) - tf.pow(distance_projection_sphere_center_on_ray, 2)) half_secant_length = tf.sqrt( tf.square(sphere_radius) - tf.square(closest_distance_sphere_center_to_ray)) distances = tf.stack( (distance_projection_sphere_center_on_ray - half_secant_length, distance_projection_sphere_center_on_ray + half_secant_length), axis=0) intersections_points = distances * ray + point_on_ray normals = tf.math.l2_normalize( intersections_points - sphere_center, axis=-1) return intersections_points, normals # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow ray utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def triangulate(startpoints, endpoints, weights, name="ray_triangulate"): """Triangulates 3d points by miminizing the sum of squared distances to rays. The rays are defined by their start points and endpoints. At least two rays are required to triangulate any given point. Contrary to the standard reprojection-error metric, the sum of squared distances to rays can be minimized in a closed form. Note: In the following, A1 to An are optional batch dimensions. Args: startpoints: A tensor of ray start points with shape `[A1, ..., An, V, 3]`, the number of rays V around which the solution points live should be greater or equal to 2, otherwise triangulation is impossible. endpoints: A tensor of ray endpoints with shape `[A1, ..., An, V, 3]`, the number of rays V around which the solution points live should be greater or equal to 2, otherwise triangulation is impossible. The `endpoints` tensor should have the same shape as the `startpoints` tensor. weights: A tensor of ray weights (certainties) with shape `[A1, ..., An, V]`. Weights should have all positive entries. Weight should have at least two non-zero entries for each point (at least two rays should have certainties > 0). name: A name for this op. The default value of None means "ray_triangulate". Returns: A tensor of triangulated points with shape `[A1, ..., An, 3]`. Raises: ValueError: If the shape of the arguments is not supported. """ with tf.name_scope(name): startpoints = tf.convert_to_tensor(value=startpoints) endpoints = tf.convert_to_tensor(value=endpoints) weights = tf.convert_to_tensor(value=weights) shape.check_static( tensor=startpoints, tensor_name="startpoints", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 1)) shape.check_static( tensor=endpoints, tensor_name="endpoints", has_rank_greater_than=1, has_dim_equals=(-1, 3), has_dim_greater_than=(-2, 1)) shape.compare_batch_dimensions( tensors=(startpoints, endpoints, weights), last_axes=(-2, -2, -1), broadcast_compatible=False) weights = asserts.assert_all_above(weights, 0.0, open_bound=False) weights = asserts.assert_at_least_k_non_zero_entries(weights, k=2) left_hand_side_list = [] right_hand_side_list = [] # TODO(b/130892100): Replace the inefficient for loop and add comments here. for ray_id in range(weights.shape[-1]): weights_single_ray = weights[..., ray_id] startpoints_single_ray = startpoints[..., ray_id, :] endpoints_singleview = endpoints[..., ray_id, :] ray = endpoints_singleview - startpoints_single_ray ray = tf.nn.l2_normalize(ray, axis=-1) ray_x, ray_y, ray_z = tf.unstack(ray, axis=-1) zeros = tf.zeros_like(ray_x) cross_product_matrix = tf.stack( (zeros, -ray_z, ray_y, ray_z, zeros, -ray_x, -ray_y, ray_x, zeros), axis=-1) cross_product_matrix_shape = tf.concat( (tf.shape(input=cross_product_matrix)[:-1], (3, 3)), axis=-1) cross_product_matrix = tf.reshape( cross_product_matrix, shape=cross_product_matrix_shape) weights_single_ray = tf.expand_dims(weights_single_ray, axis=-1) weights_single_ray = tf.expand_dims(weights_single_ray, axis=-1) left_hand_side = weights_single_ray * cross_product_matrix left_hand_side_list.append(left_hand_side) dot_product = tf.matmul(cross_product_matrix, tf.expand_dims(startpoints_single_ray, axis=-1)) right_hand_side = weights_single_ray * dot_product right_hand_side_list.append(right_hand_side) left_hand_side_multi_rays = tf.concat(left_hand_side_list, axis=-2) right_hand_side_multi_rays = tf.concat(right_hand_side_list, axis=-2) points = tf.linalg.lstsq(left_hand_side_multi_rays, right_hand_side_multi_rays) points = tf.squeeze(points, axis=-1) return points # TODO(b/130893491): Add batch support for radii and return [A1, ... , 3, 2]. def intersection_ray_sphere(sphere_center, sphere_radius, ray, point_on_ray, name="ray_intersection_ray_sphere"): """Finds positions and surface normals where the sphere and the ray intersect. Note: In the following, A1 to An are optional batch dimensions. Args: sphere_center: A tensor of shape `[3]` representing the 3d sphere center. sphere_radius: A tensor of shape `[1]` containing a strictly positive value defining the radius of the sphere. ray: A tensor of shape `[A1, ..., An, 3]` containing normalized 3D vectors. point_on_ray: A tensor of shape `[A1, ..., An, 3]`. name: A name for this op. The default value of None means "ray_intersection_ray_sphere". Returns: A tensor of shape `[2, A1, ..., An, 3]` containing the position of the intersections, and a tensor of shape `[2, A1, ..., An, 3]` the associated surface normals at that point. Both tensors contain NaNs when there is no intersections. The first dimension of the returned tensor provides access to the first and second intersections of the ray with the sphere. Raises: ValueError: if the shape of `sphere_center`, `sphere_radius`, `ray` or `point_on_ray` is not supported. tf.errors.InvalidArgumentError: If `ray` is not normalized. """ with tf.name_scope(name): sphere_center = tf.convert_to_tensor(value=sphere_center) sphere_radius = tf.convert_to_tensor(value=sphere_radius) ray = tf.convert_to_tensor(value=ray) point_on_ray = tf.convert_to_tensor(value=point_on_ray) shape.check_static( tensor=sphere_center, tensor_name="sphere_center", has_rank=1, has_dim_equals=(0, 3)) shape.check_static( tensor=sphere_radius, tensor_name="sphere_radius", has_rank=1, has_dim_equals=(0, 1)) shape.check_static(tensor=ray, tensor_name="ray", has_dim_equals=(-1, 3)) shape.check_static( tensor=point_on_ray, tensor_name="point_on_ray", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(ray, point_on_ray), last_axes=(-2, -2), broadcast_compatible=False) sphere_radius = asserts.assert_all_above( sphere_radius, 0.0, open_bound=True) ray = asserts.assert_normalized(ray) vector_sphere_center_to_point_on_ray = sphere_center - point_on_ray distance_sphere_center_to_point_on_ray = tf.norm( tensor=vector_sphere_center_to_point_on_ray, axis=-1, keepdims=True) distance_projection_sphere_center_on_ray = vector.dot( vector_sphere_center_to_point_on_ray, ray) closest_distance_sphere_center_to_ray = tf.sqrt( tf.square(distance_sphere_center_to_point_on_ray) - tf.pow(distance_projection_sphere_center_on_ray, 2)) half_secant_length = tf.sqrt( tf.square(sphere_radius) - tf.square(closest_distance_sphere_center_to_ray)) distances = tf.stack( (distance_projection_sphere_center_on_ray - half_secant_length, distance_projection_sphere_center_on_ray + half_secant_length), axis=0) intersections_points = distances * ray + point_on_ray normals = tf.math.l2_normalize( intersections_points - sphere_center, axis=-1) return intersections_points, normals # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/triangle.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow triangle utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def normal(v0, v1, v2, clockwise=False, normalize=True, name=None): """Computes face normals (triangles). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. clockwise: Winding order to determine front-facing triangles. normalize: A `bool` indicating whether output normals should be normalized by the function. name: A name for this op. Defaults to "triangle_normal". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized vector. Raises: ValueError: If the shape of `v0`, `v1`, or `v2` is not supported. """ with tf.compat.v1.name_scope(name, "triangle_normal", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normal_vector = vector.cross(v1 - v0, v2 - v0, axis=-1) normal_vector = asserts.assert_nonzero_norm(normal_vector) if not clockwise: normal_vector *= -1.0 if normalize: return tf.nn.l2_normalize(normal_vector, axis=-1) return normal_vector def area(v0, v1, v2, name=None): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. A degenerate triangle will return 0 area, whereas the normal for a degenerate triangle is not defined. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized vector. """ with tf.compat.v1.name_scope(name, "triangle_area", [v0, v1, v2]): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normals = vector.cross(v1 - v0, v2 - v0, axis=-1) return 0.5 * tf.linalg.norm(tensor=normals, axis=-1, keepdims=True) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow triangle utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def normal(v0, v1, v2, clockwise=False, normalize=True, name="triangle_normal"): """Computes face normals (triangles). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. clockwise: Winding order to determine front-facing triangles. normalize: A `bool` indicating whether output normals should be normalized by the function. name: A name for this op. Defaults to "triangle_normal". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized vector. Raises: ValueError: If the shape of `v0`, `v1`, or `v2` is not supported. """ with tf.name_scope(name): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normal_vector = vector.cross(v1 - v0, v2 - v0, axis=-1) normal_vector = asserts.assert_nonzero_norm(normal_vector) if not clockwise: normal_vector *= -1.0 if normalize: return tf.nn.l2_normalize(normal_vector, axis=-1) return normal_vector def area(v0, v1, v2, name="triangle_area"): """Computes triangle areas. Note: Computed triangle area = 0.5 * | e1 x e2 | where e1 and e2 are edges of triangle. A degenerate triangle will return 0 area, whereas the normal for a degenerate triangle is not defined. In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: v0: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vertex of a triangle. v1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vertex of a triangle. v2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the third vertex of a triangle. name: A name for this op. Defaults to "triangle_area". Returns: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized vector. """ with tf.name_scope(name): v0 = tf.convert_to_tensor(value=v0) v1 = tf.convert_to_tensor(value=v1) v2 = tf.convert_to_tensor(value=v2) shape.check_static(tensor=v0, tensor_name="v0", has_dim_equals=(-1, 3)) shape.check_static(tensor=v1, tensor_name="v1", has_dim_equals=(-1, 3)) shape.check_static(tensor=v2, tensor_name="v2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(v0, v1, v2), last_axes=-2, broadcast_compatible=True) normals = vector.cross(v1 - v0, v2 - v0, axis=-1) return 0.5 * tf.linalg.norm(tensor=normals, axis=-1, keepdims=True) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/util/tests/test_case_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for shape utility functions.""" import unittest from absl.testing import parameterized import tensorflow as tf from tensorflow_graphics.util import test_case class TestCaseTest(test_case.TestCase): def _dummy_tf_lite_compatible_function(self, data): """Executes a simple supported function to test TFLite conversion.""" data = tf.convert_to_tensor(value=data) return 2.0 * data def _dummy_tf_lite_incompatible_function(self, data): """Executes a simple unsupported function to test TFLite conversion.""" del data # Unused return 2.0 * tf.ones(shape=[2] * 10) @parameterized.parameters(None, (((1.0,),),)) def test_assert_tf_lite_convertible_exception_not_raised(self, test_inputs): """Tests that assert_tf_lite_convertible succeeds with a simple function.""" tc = test_case.TestCase(methodName="assert_tf_lite_convertible") # We can't use self.assert_exception_is_not_raised here because we need to # use `shapes` as both a named argument and a kwarg. try: tc.assert_tf_lite_convertible( func=self._dummy_tf_lite_compatible_function, shapes=((1,),), test_inputs=test_inputs) except unittest.SkipTest as e: # Forwarding SkipTest exception in order to skip the test. raise e except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % type(e)) @parameterized.parameters(None, (((1.0,),),)) def test_assert_tf_lite_convertible_exception_raised(self, test_inputs): """Tests that assert_tf_lite_convertible succeeds with a simple function.""" # TODO(b/131912561): TFLite conversion throws SIGABRT instead of Exception. return # pylint: disable=unreachable # This code should be able to catch exceptions correctly once TFLite bug # is fixed. tc = test_case.TestCase(methodName="assert_tf_lite_convertible") with self.assertRaises(Exception): tc.assert_tf_lite_convertible( func=self._dummy_tf_lite_incompatible_function, shapes=((1,),), test_inputs=test_inputs) # pylint: enable=unreachable def _dummy_failing_function(self, data): """Fails instantly.""" del data # Unused raise ValueError("Fail.") def test_assert_exception_is_not_raised_raises_exception(self): """Tests that assert_exception_is_not_raised raises exception.""" if tf.executing_eagerly(): # In eager mode placeholders are assigned zeros by default, which fails # for various tests. Therefore this function can only be tested in graph # mode. return tc = test_case.TestCase(methodName="assert_exception_is_not_raised") with self.assertRaises(AssertionError): tc.assert_exception_is_not_raised( self._dummy_failing_function, shapes=((1,),)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for shape utility functions.""" import unittest from absl.testing import parameterized import tensorflow as tf from tensorflow_graphics.util import test_case class TestCaseTest(test_case.TestCase): def _dummy_tf_lite_compatible_function(self, data): """Executes a simple supported function to test TFLite conversion.""" data = tf.convert_to_tensor(value=data) return 2.0 * data def _dummy_tf_lite_incompatible_function(self, data): """Executes a simple unsupported function to test TFLite conversion.""" del data # Unused return 2.0 * tf.ones(shape=[2] * 10) @parameterized.parameters(None, (((1.0,),),)) def test_assert_tf_lite_convertible_exception_not_raised(self, test_inputs): """Tests that assert_tf_lite_convertible succeeds with a simple function.""" tc = test_case.TestCase(methodName="assert_tf_lite_convertible") # We can't use self.assert_exception_is_not_raised here because we need to # use `shapes` as both a named argument and a kwarg. try: tc.assert_tf_lite_convertible( func=self._dummy_tf_lite_compatible_function, shapes=((1,),), test_inputs=test_inputs) except unittest.SkipTest as e: # Forwarding SkipTest exception in order to skip the test. raise e except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % type(e)) @parameterized.parameters(None, (((1.0,),),)) def test_assert_tf_lite_convertible_exception_raised(self, test_inputs): """Tests that assert_tf_lite_convertible succeeds with a simple function.""" # TODO(b/131912561): TFLite conversion throws SIGABRT instead of Exception. return # pylint: disable=unreachable # This code should be able to catch exceptions correctly once TFLite bug # is fixed. tc = test_case.TestCase(methodName="assert_tf_lite_convertible") with self.assertRaises(Exception): tc.assert_tf_lite_convertible( func=self._dummy_tf_lite_incompatible_function, shapes=((1,),), test_inputs=test_inputs) # pylint: enable=unreachable def _dummy_failing_function(self, data): """Fails instantly.""" del data # Unused raise ValueError("Fail.") def test_assert_exception_is_not_raised_raises_exception(self): """Tests that assert_exception_is_not_raised raises exception.""" if tf.executing_eagerly(): # In eager mode placeholders are assigned zeros by default, which fails # for various tests. Therefore this function can only be tested in graph # mode. return tc = test_case.TestCase(methodName="assert_exception_is_not_raised") with self.assertRaises(AssertionError): tc.assert_exception_is_not_raised( self._dummy_failing_function, shapes=((1,),)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/image/tests/transformer_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for image transformation functionalities.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_addons import image as tfa_image from tensorflow_graphics.image import transformer from tensorflow_graphics.util import test_case class TransformerTest(test_case.TestCase, parameterized.TestCase): @parameterized.parameters( ((None, 1, 2, None), (None, 3, 3)), ((1, 2, 3, 4), (1, 3, 3)), ) def test_perspective_transform_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(transformer.perspective_transform, shape) @parameterized.parameters( ("must have a rank of 4.", (1, 1, 1), (1, 3, 3)), ("must have a rank of 3.", (1, 1, 1, 1), (3, 3)), ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 3, 3)), ) def test_perspective_transform_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(transformer.perspective_transform, error_msg, shape) @parameterized.parameters( (tf.float32, "NEAREST"), (tf.float64, "NEAREST"), (tf.float32, "BILINEAR"), (tf.float64, "BILINEAR"), ) def test_perspective_transform_half_integer_centers_preset( self, dtype, interpolation): """Tests that we can reproduce the results of tf.image.resize.""" image = tf.constant( ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)), dtype=dtype) scale = 3 transformation = tf.constant( ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)), dtype=dtype) image_shape = tf.shape(image) image_resized_shape = image_shape * scale image = image[tf.newaxis, ..., tf.newaxis] transformation = transformation[tf.newaxis, ...] image_resized = tf.image.resize( image, size=image_resized_shape, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR if interpolation == "NEAREST" else tf.image.ResizeMethod.BILINEAR) image_transformed = transformer.perspective_transform( image, transformation, resampling_type=transformer.ResamplingType.NEAREST if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR, border_type=transformer.BorderType.DUPLICATE, output_shape=image_resized_shape) self.assertAllClose(image_resized, image_transformed) @parameterized.parameters( (tf.float32, "NEAREST"), (tf.float64, "NEAREST"), (tf.float32, "BILINEAR"), (tf.float64, "BILINEAR"), ) def test_perspective_transform_integer_centers_preset(self, dtype, interpolation): """Tests that we can reproduce the results of tfa_image.transform.""" image = tf.constant( ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)), dtype=dtype) scale = 3 transformation = tf.constant( ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)), dtype=dtype) image_shape = tf.shape(image) image_resized_shape = image_shape * scale image = image[tf.newaxis, ..., tf.newaxis] transformation = transformation[tf.newaxis, ...] image_resized = tfa_image.transform( tf.cast(image, tf.float32), tf.cast( tfa_image.transform_ops.matrices_to_flat_transforms(transformation), tf.float32), interpolation=interpolation, output_shape=image_resized_shape) image_transformed = transformer.perspective_transform( image, transformation, resampling_type=transformer.ResamplingType.NEAREST if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR, pixel_type=transformer.PixelType.INTEGER, output_shape=image_resized_shape) self.assertAllClose(image_resized, image_transformed) def test_perspective_transform_jacobian_random(self): """Tests the Jacobian of the transform function.""" tensor_shape = np.random.randint(2, 4, size=4) image_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist()) transformation_init = np.random.uniform( 0.0, 1.0, size=(tensor_shape[0], 3, 3)) self.assert_jacobian_is_correct_fn( lambda x: transformer.perspective_transform(x, transformation_init), [image_init]) self.assert_jacobian_is_correct_fn( lambda x: transformer.perspective_transform(image_init, x), [transformation_init]) @parameterized.parameters( ((None, 1, 2, None), (None, 2)), ((1, 3, 2, 4), (1, 2)), ) def test_sample_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(transformer.sample, shape) @parameterized.parameters( ("must have a rank of 4.", (1, 1, 1), (1, 2)), ("must have a rank greater than 1", (1, 1, 1, 1), (2,)), ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 2)), ) def test_sample_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(transformer.sample, error_msg, shape) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for image transformation functionalities.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_addons import image as tfa_image from tensorflow_graphics.image import transformer from tensorflow_graphics.util import test_case class TransformerTest(test_case.TestCase, parameterized.TestCase): @parameterized.parameters( ((None, 1, 2, None), (None, 3, 3)), ((1, 2, 3, 4), (1, 3, 3)), ) def test_perspective_transform_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(transformer.perspective_transform, shape) @parameterized.parameters( ("must have a rank of 4.", (1, 1, 1), (1, 3, 3)), ("must have a rank of 3.", (1, 1, 1, 1), (3, 3)), ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 3, 3)), ) def test_perspective_transform_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(transformer.perspective_transform, error_msg, shape) @parameterized.parameters( (tf.float32, "NEAREST"), (tf.float64, "NEAREST"), (tf.float32, "BILINEAR"), (tf.float64, "BILINEAR"), ) def test_perspective_transform_half_integer_centers_preset( self, dtype, interpolation): """Tests that we can reproduce the results of tf.image.resize.""" image = tf.constant( ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)), dtype=dtype) scale = 3 transformation = tf.constant( ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)), dtype=dtype) image_shape = tf.shape(image) image_resized_shape = image_shape * scale image = image[tf.newaxis, ..., tf.newaxis] transformation = transformation[tf.newaxis, ...] image_resized = tf.image.resize( image, size=image_resized_shape, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR if interpolation == "NEAREST" else tf.image.ResizeMethod.BILINEAR) image_transformed = transformer.perspective_transform( image, transformation, resampling_type=transformer.ResamplingType.NEAREST if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR, border_type=transformer.BorderType.DUPLICATE, output_shape=image_resized_shape) self.assertAllClose(image_resized, image_transformed) @parameterized.parameters( (tf.float32, "NEAREST"), (tf.float64, "NEAREST"), (tf.float32, "BILINEAR"), (tf.float64, "BILINEAR"), ) def test_perspective_transform_integer_centers_preset(self, dtype, interpolation): """Tests that we can reproduce the results of tfa_image.transform.""" image = tf.constant( ((1.0, 2.0, 3.0), (4.0, 5.0, 6.0), (7.0, 8.0, 9.0), (10.0, 11.0, 12.0)), dtype=dtype) scale = 3 transformation = tf.constant( ((1.0 / scale, 0.0, 0.0), (0.0, 1.0 / scale, 0.0), (0.0, 0.0, 1.0)), dtype=dtype) image_shape = tf.shape(image) image_resized_shape = image_shape * scale image = image[tf.newaxis, ..., tf.newaxis] transformation = transformation[tf.newaxis, ...] image_resized = tfa_image.transform( tf.cast(image, tf.float32), tf.cast( tfa_image.transform_ops.matrices_to_flat_transforms(transformation), tf.float32), interpolation=interpolation, output_shape=image_resized_shape) image_transformed = transformer.perspective_transform( image, transformation, resampling_type=transformer.ResamplingType.NEAREST if interpolation == "NEAREST" else transformer.ResamplingType.BILINEAR, pixel_type=transformer.PixelType.INTEGER, output_shape=image_resized_shape) self.assertAllClose(image_resized, image_transformed) def test_perspective_transform_jacobian_random(self): """Tests the Jacobian of the transform function.""" tensor_shape = np.random.randint(2, 4, size=4) image_init = np.random.uniform(0.0, 1.0, size=tensor_shape.tolist()) transformation_init = np.random.uniform( 0.0, 1.0, size=(tensor_shape[0], 3, 3)) self.assert_jacobian_is_correct_fn( lambda x: transformer.perspective_transform(x, transformation_init), [image_init]) self.assert_jacobian_is_correct_fn( lambda x: transformer.perspective_transform(image_init, x), [transformation_init]) @parameterized.parameters( ((None, 1, 2, None), (None, 2)), ((1, 3, 2, 4), (1, 2)), ) def test_sample_exception_not_raised(self, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(transformer.sample, shape) @parameterized.parameters( ("must have a rank of 4.", (1, 1, 1), (1, 2)), ("must have a rank greater than 1", (1, 1, 1, 1), (2,)), ("Not all batch dimensions are identical.", (1, 1, 1, 1), (2, 2)), ) def test_sample_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(transformer.sample, error_msg, shape) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/dual_quaternion.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name="dual_quaternion_conjugate"): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.name_scope(name): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow dual quaternion utility functions. A dual quaternion is an extension of a quaternion with the real and dual parts and written as $$q = q_r + epsilon q_d$$, where $$epsilon$$ is the dual number with the property $$e^2 = 0$$. It can thus be represented as two quaternions, and thus stored as 8 numbers. We define the operations in terms of the two quaternions $$q_r$$ and $$q_d$$. Dual quaternions are extensions of quaternions to represent rigid transformations (rotations and translations). They are in particular important for deforming geometries as linear blending is a very close approximation of closest path blending, which is not the case for any other representation. Note: Some of the functions expect normalized quaternions as inputs where $$|q_r| = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def conjugate(dual_quaternion, name="dual_quaternion_conjugate"): """Computes the conjugate of a dual quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: dual_quaternion: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. name: A name for this op that defaults to "dual_quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 8]`, where the last dimension represents a normalized dual quaternion. Raises: ValueError: If the shape of `dual_quaternion` is not supported. """ with tf.name_scope(name): dual_quaternion = tf.convert_to_tensor(value=dual_quaternion) shape.check_static( tensor=dual_quaternion, tensor_name="dual_quaternion", has_dim_equals=(-1, 8)) quaternion_real, quaternion_dual = tf.split( dual_quaternion, (4, 4), axis=-1) quaternion_real = asserts.assert_normalized(quaternion_real) return tf.concat((quaternion.conjugate(quaternion_real), quaternion.conjugate(quaternion_dual)), axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/util/tests/export_api_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for export API functionalities.""" from tensorflow_graphics.util import export_api from tensorflow_graphics.util import test_case class ExportAPITest(test_case.TestCase): def test_get_functions_and_classes(self): """Tests that get_functions_and_classes does not raise an exception.""" try: export_api.get_functions_and_classes() except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) def test_get_modules(self): """Tests that get_modules does not raise an exception.""" try: export_api.get_modules() except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for export API functionalities.""" from tensorflow_graphics.util import export_api from tensorflow_graphics.util import test_case class ExportAPITest(test_case.TestCase): def test_get_functions_and_classes(self): """Tests that get_functions_and_classes does not raise an exception.""" try: export_api.get_functions_and_classes() except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) def test_get_modules(self): """Tests that get_modules does not raise an exception.""" try: export_api.get_modules() except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/math/interpolation/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/local_implicit_grid/core/model_g2v.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Model for part autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow.compat.v1 as tf layers = tf.keras.layers class ResBlock3D(layers.Layer): """3D convolutional Residue Block. Maintains same resolution. """ def __init__(self, neck_channels, out_channels): """Initialization. Args: neck_channels: int, number of channels in bottleneck layer. out_channels: int, number of output channels. """ super(ResBlock3D, self).__init__() self.neck_channels = neck_channels self.out_channels = out_channels self.conv1 = layers.Conv3D(neck_channels, kernel_size=1, strides=1) self.conv2 = layers.Conv3D( neck_channels, kernel_size=3, strides=1, padding="same") self.conv3 = layers.Conv3D(out_channels, kernel_size=1, strides=1) self.bn1 = layers.BatchNormalization(axis=-1) self.bn2 = layers.BatchNormalization(axis=-1) self.bn3 = layers.BatchNormalization(axis=-1) self.shortcut = layers.Conv3D(out_channels, kernel_size=1, strides=1) def call(self, x, training=False): identity = x x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x = tf.nn.relu(x) x = self.conv3(x) x = self.bn3(x, training=training) x += self.shortcut(identity) x = tf.nn.relu(x) return x class GridEncoder(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoder, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels. self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1) ] # feat. in downward path self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = [layers.MaxPool3D((2, 2, 2)) for _ in nd[1:]] self.fc_out = layers.Dense(self.codelen) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv, pool in zip(self.down_conv, self.down_pool): x = conv(x, training=training) x = pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len] return x class GridEncoderVAE(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder_vae"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoderVAE, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers # feat. in downward path nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1)] self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = layers.MaxPool3D((2, 2, 2)) self.fc_out = layers.Dense(self.codelen * 2) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv in self.down_conv: x = conv(x, training=training) x = self.down_pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len*2] mu, logvar = x[:, :self.codelen], x[:, self.codelen:] noise = tf.random.normal(mu.shape) std = tf.exp(0.5 * logvar) x_out = mu + noise * std return x_out, mu, logvar
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Model for part autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow.compat.v1 as tf layers = tf.keras.layers class ResBlock3D(layers.Layer): """3D convolutional Residue Block. Maintains same resolution. """ def __init__(self, neck_channels, out_channels): """Initialization. Args: neck_channels: int, number of channels in bottleneck layer. out_channels: int, number of output channels. """ super(ResBlock3D, self).__init__() self.neck_channels = neck_channels self.out_channels = out_channels self.conv1 = layers.Conv3D(neck_channels, kernel_size=1, strides=1) self.conv2 = layers.Conv3D( neck_channels, kernel_size=3, strides=1, padding="same") self.conv3 = layers.Conv3D(out_channels, kernel_size=1, strides=1) self.bn1 = layers.BatchNormalization(axis=-1) self.bn2 = layers.BatchNormalization(axis=-1) self.bn3 = layers.BatchNormalization(axis=-1) self.shortcut = layers.Conv3D(out_channels, kernel_size=1, strides=1) def call(self, x, training=False): identity = x x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x = tf.nn.relu(x) x = self.conv3(x) x = self.bn3(x, training=training) x += self.shortcut(identity) x = tf.nn.relu(x) return x class GridEncoder(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoder, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels. self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1) ] # feat. in downward path self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = [layers.MaxPool3D((2, 2, 2)) for _ in nd[1:]] self.fc_out = layers.Dense(self.codelen) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv, pool in zip(self.down_conv, self.down_pool): x = conv(x, training=training) x = pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len] return x class GridEncoderVAE(layers.Layer): """Grid to vector model for part autoencoding.""" def __init__(self, in_grid_res=32, num_filters=32, codelen=128, name="grid_encoder_vae"): """Initialization. Args: in_grid_res: int, input grid resolution, must be powers of 2. num_filters: int, number of feature layers at smallest grid resolution. codelen: int, length of local latent codes. name: str, name of the layer. """ super(GridEncoderVAE, self).__init__(name=name) self.in_grid_res = in_grid_res self.num_filters = num_filters self.codelen = codelen # number of input levels self.num_in_level = int(math.log(self.in_grid_res, 2)) # create layers # feat. in downward path nd = [self.num_filters * (2**i) for i in range(self.num_in_level + 1)] self.conv_in = layers.Conv3D(filters=nd[0], kernel_size=1) self.down_conv = [ResBlock3D(int(n / 2), n) for n in nd[1:]] self.down_pool = layers.MaxPool3D((2, 2, 2)) self.fc_out = layers.Dense(self.codelen * 2) def call(self, x, training=False): """Forward method. Args: x: `[batch, in_grid_res, in_grid_res, in_grid_res, in_features]` tensor, input voxel grid. training: bool, flag indicating whether model is in training mode. Returns: `[batch, codelen]` tensor, output voxel grid. """ x = self.conv_in(x) x = tf.nn.relu(x) for conv in self.down_conv: x = conv(x, training=training) x = self.down_pool(x, training=training) # [batch, res, res, res, c] x = tf.squeeze(x, axis=(1, 2, 3)) # [batch, c] x = self.fc_out(x) # [batch, code_len*2] mu, logvar = x[:, :self.codelen], x[:, self.codelen:] noise = tf.random.normal(mu.shape) std = tf.exp(0.5 * logvar) x_out = mu + noise * std return x_out, mu, logvar
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/convolution/graph_pooling.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements various graph pooling ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api def pool(data, pool_map, sizes, algorithm='max', name=None): # pyformat: disable """Implements graph pooling. The features at each output vertex are computed by pooling over a subset of vertices in the input graph. This pooling window is specified by the input `pool_map`. The shorthands used below are `V1`: The number of vertices in the input data. `V2`: The number of vertices in the pooled output data. `C`: The number of channels in the data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V2, V1]`. The features for an output vertex `v2` will be computed by pooling over the corresponding input vertices specified by the entries in `pool_map[A1, ..., An, v2, :]`. sizes: An `int` tensor of shape `[A1, ..., An, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An, 0] <= V2` specifies the padding in the (pooled) output, and `sizes[A1, ..., An, 1] <= V1` specifies the padding in the input. algorithm: The pooling function, must be either 'max' or 'weighted'. Default is 'max'. For 'max' pooling, the output features are the maximum over the input vertices (in this case only the indices of the `SparseTensor` `pool_map` are used, the values are ignored). For 'weighted', the output features are a weighted sum of the input vertices, the weights specified by the values of `pool_map`. name: A name for this op. Defaults to 'graph_pooling_pool'. Returns: Tensor with shape `[A1, ..., An, V2, C]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. ValueError: if `algorithm` is invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_pool', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_pooling_input(data, pool_map, sizes) if sizes is not None: sizes_output, sizes_input = tf.split(sizes, 2, axis=-1) sizes_output = tf.squeeze(sizes_output, axis=-1) sizes_input = tf.squeeze(sizes_input, axis=-1) else: sizes_output = None sizes_input = None batched = data.shape.ndims > 2 if batched: x_flat, _ = utils.flatten_batch_to_2d(data, sizes_input) pool_map_block_diagonal = utils.convert_to_block_diag_2d(pool_map, sizes) else: x_flat = data pool_map_block_diagonal = pool_map if algorithm == 'weighted': pooled = tf.sparse.sparse_dense_matmul(pool_map_block_diagonal, x_flat) elif algorithm == 'max': pool_groups = tf.gather(x_flat, pool_map_block_diagonal.indices[:, 1]) pooled = tf.math.segment_max( data=pool_groups, segment_ids=pool_map_block_diagonal.indices[:, 0]) else: raise ValueError('The pooling method must be "weighted" or "max"') if batched: if sizes_output is not None: pooled = utils.unflatten_2d_to_batch(pooled, sizes_output) else: output_shape = tf.concat((tf.shape(input=pool_map)[:-1], (-1,)), axis=0) pooled = tf.reshape(pooled, output_shape) return pooled def unpool(data, pool_map, sizes, name=None): # pyformat: disable r"""Graph upsampling by inverting the pooling map. Upsamples a graph by applying a pooling map in reverse. The inputs `pool_map` and `sizes` are the same as used for pooling: >>> pooled = pool(data, pool_map, sizes) >>> upsampled = unpool(pooled, pool_map, sizes) The shorthands used below are `V1`: The number of vertices in the input data. `V2`: The number of vertices in the unpooled output data. `C`: The number of channels in the data. Note: In the following, A1 to A3 are optional batch dimensions. Only up to three batch dimensions are supported due to limitations with TensorFlow's dense-sparse multiplication. Please see the documentation for `graph_pooling.pool` for a detailed interpretation of the inputs `pool_map` and `sizes`. Args: data: A `float` tensor with shape `[A1, ..., A3, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., A3, V1, V2]`. The features for vertex `v1` are computed by pooling over the entries in `pool_map[A1, ..., A3, v1, :]`. This function applies this pooling map in reverse. sizes: An `int` tensor of shape `[A1, ..., A3, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding): `sizes[A1, ..., A3, 0] <= V1` and `sizes[A1, ..., A3, 1] <= V2`. name: A name for this op. Defaults to 'graph_pooling_unpool'. Returns: Tensor with shape `[A1, ..., A3, V2, C]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_unpool', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_unpooling_input(data, pool_map, sizes) # Reverse pool_map and sizes. pool_map_ndims = pool_map.shape.ndims permutation = tf.concat((tf.range(pool_map_ndims - 2), (pool_map_ndims - 1, pool_map_ndims - 2)), axis=0) pool_map_transpose = tf.sparse.transpose(pool_map, permutation) row_sum = tf.sparse.reduce_sum( tf.abs(pool_map_transpose), keepdims=True, axis=-1) normalize_weights = tf.compat.v1.where( tf.equal(row_sum, 0), row_sum, 1.0 / row_sum) pool_map_normalize = normalize_weights * pool_map_transpose if sizes is not None: sizes = tf.reverse(sizes, axis=(-1,)) return pool(data, pool_map_normalize, sizes) def upsample_transposed_convolution(data, pool_map, sizes, kernel_size, transposed_convolution_op, name=None): # pyformat: disable r"""Graph upsampling by transposed convolution. Upsamples a graph using a transposed convolution op. The map from input vertices to the upsampled graph is specified by the reverse of pool_map. The inputs `pool_map` and `sizes` are the same as used for pooling: >>> pooled = pool(data, pool_map, sizes) >>> upsampled = upsample_transposed_convolution(pooled, pool_map, sizes, ...) The shorthands used below are `V1`: The number of vertices in the inputs. `V2`: The number of vertices in the upsampled output. `C`: The number of channels in the inputs. Note: In the following, A1 to A3 are optional batch dimensions. Only up to three batch dimensions are supported due to limitations with TensorFlow's dense-sparse multiplication. Please see the documentation for `graph_pooling.pool` for a detailed interpretation of the inputs `pool_map` and `sizes`. Args: data: A `float` tensor with shape `[A1, ..., A3, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., A3, V1, V2]`. `pool_map` will be interpreted in the same way as the `pool_map` argument of `graph_pooling.pool`, namely `v_i_map = [..., v_i, :]` are the upsampled vertices corresponding to vertex `v_i`. Additionally, for transposed convolution a fixed number of entries in each `v_i_map` (equal to `kernel_size`) are expected: `|v_i_map| = kernel_size`. When this is not the case, the map is either truncated or the last element repeated. Furthermore, upsampled vertex indices should not be repeated across maps otherwise the output is nondeterministic. Specifically, to avoid nondeterminism we must have `intersect([a1, ..., an, v_i, :],[a1, ..., a3, v_j, :]) = {}, i != j`. sizes: An `int` tensor of shape `[A1, ..., A3, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding): `sizes[A1, ..., A3, 0] <= V1` and `sizes[A1, ..., A3, 1] <= V2`. kernel_size: The kernel size for transposed convolution. transposed_convolution_op: A callable transposed convolution op with the form `y = transposed_convolution_op(x)`, where `x` has shape `[1, 1, D1, C]` and `y` must have shape `[1, 1, kernel_size * D1, C]`. `transposed_convolution_op` maps each row of `x` to `kernel_size` rows in `y`. An example: `transposed_convolution_op = tf.keras.layers.Conv2DTranspose( filters=C, kernel_size=(1, kernel_size), strides=(1, kernel_size), padding='valid', ...) name: A name for this op. Defaults to 'graph_pooling_upsample_transposed_convolution'. Returns: Tensor with shape `[A1, ..., A3, V2, C]`. Raises: TypeError: if the input types are invalid. TypeError: if `transposed_convolution_op` is not a callable. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_upsample_transposed_convolution', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_unpooling_input(data, pool_map, sizes) if not callable(transposed_convolution_op): raise TypeError("'transposed_convolution_op' must be callable.") if sizes is not None: sizes_input, sizes_output = tf.split(sizes, 2, axis=-1) sizes_input = tf.squeeze(sizes_input, axis=-1) sizes_output = tf.squeeze(sizes_output, axis=-1) else: sizes_input = None sizes_output = None num_features = tf.compat.v1.dimension_value(data.shape[-1]) batched = data.shape.ndims > 2 if batched: x_flat, _ = utils.flatten_batch_to_2d(data, sizes_input) pool_map_block_diagonal = utils.convert_to_block_diag_2d(pool_map, sizes) else: x_flat = data pool_map_block_diagonal = pool_map x_flat = tf.expand_dims(tf.expand_dims(x_flat, 0), 0) x_upsample = transposed_convolution_op(x_flat) # Map each upsampled vertex into its correct position based on pool_map. # Select 'kernel_size' neighbors for each input vertex. Truncate or repeat # as necessary. ragged = tf.RaggedTensor.from_value_rowids( pool_map_block_diagonal.indices[:, 1], pool_map_block_diagonal.indices[:, 0]) # Take up to the first 'kernel_size' entries. ragged_k = ragged[:, :kernel_size] # Fill rows with less than 'kernel_size' entries by repeating the last # entry. last = ragged_k[:, -1:].flat_values num_repeat = kernel_size - ragged_k.row_lengths() sum_num_repeat = tf.reduce_sum(input_tensor=num_repeat) ones_ragged = tf.RaggedTensor.from_row_lengths( tf.ones((sum_num_repeat,), dtype=last.dtype), num_repeat) repeat = ones_ragged * tf.expand_dims(last, -1) padded = tf.concat([ragged_k, repeat], axis=1) pool_map_dense = tf.reshape(padded.flat_values, (-1, kernel_size)) # Map rows of 'x_upsample' to positions indicated by the # indices 'pool_map_dense'. up_scatter_indices = tf.expand_dims(tf.reshape(pool_map_dense, (-1,)), -1) up_row = tf.reshape(tf.cast(up_scatter_indices, tf.int64), (-1,)) up_column = tf.range(tf.shape(input=up_row, out_type=tf.dtypes.int64)[0]) scatter_indices = tf.concat( (tf.expand_dims(up_row, -1), tf.expand_dims(up_column, -1)), axis=1) scatter_values = tf.ones_like(up_row, dtype=x_upsample.dtype) scatter_shape = tf.reduce_max(input_tensor=scatter_indices, axis=0) + 1 scatter = tf.SparseTensor(scatter_indices, scatter_values, scatter_shape) scatter = tf.sparse.reorder(scatter) row_sum = tf.sparse.reduce_sum(tf.abs(scatter), keepdims=True, axis=-1) row_sum = tf.compat.v1.where(tf.equal(row_sum, 0.), row_sum, 1.0 / row_sum) scatter = row_sum * scatter x_upsample = tf.sparse.sparse_dense_matmul(scatter, x_upsample[0, 0, :, :]) if batched: if sizes_output is not None: x_upsample = utils.unflatten_2d_to_batch(x_upsample, sizes_output) else: output_shape = tf.concat((tf.shape(input=pool_map)[:-2], tf.shape(input=pool_map)[-1:], (num_features,)), axis=0) x_upsample = tf.reshape(x_upsample, output_shape) return x_upsample # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements various graph pooling ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.convolution import utils from tensorflow_graphics.util import export_api def pool(data, pool_map, sizes, algorithm='max', name=None): # pyformat: disable """Implements graph pooling. The features at each output vertex are computed by pooling over a subset of vertices in the input graph. This pooling window is specified by the input `pool_map`. The shorthands used below are `V1`: The number of vertices in the input data. `V2`: The number of vertices in the pooled output data. `C`: The number of channels in the data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V2, V1]`. The features for an output vertex `v2` will be computed by pooling over the corresponding input vertices specified by the entries in `pool_map[A1, ..., An, v2, :]`. sizes: An `int` tensor of shape `[A1, ..., An, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An, 0] <= V2` specifies the padding in the (pooled) output, and `sizes[A1, ..., An, 1] <= V1` specifies the padding in the input. algorithm: The pooling function, must be either 'max' or 'weighted'. Default is 'max'. For 'max' pooling, the output features are the maximum over the input vertices (in this case only the indices of the `SparseTensor` `pool_map` are used, the values are ignored). For 'weighted', the output features are a weighted sum of the input vertices, the weights specified by the values of `pool_map`. name: A name for this op. Defaults to 'graph_pooling_pool'. Returns: Tensor with shape `[A1, ..., An, V2, C]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. ValueError: if `algorithm` is invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_pool', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_pooling_input(data, pool_map, sizes) if sizes is not None: sizes_output, sizes_input = tf.split(sizes, 2, axis=-1) sizes_output = tf.squeeze(sizes_output, axis=-1) sizes_input = tf.squeeze(sizes_input, axis=-1) else: sizes_output = None sizes_input = None batched = data.shape.ndims > 2 if batched: x_flat, _ = utils.flatten_batch_to_2d(data, sizes_input) pool_map_block_diagonal = utils.convert_to_block_diag_2d(pool_map, sizes) else: x_flat = data pool_map_block_diagonal = pool_map if algorithm == 'weighted': pooled = tf.sparse.sparse_dense_matmul(pool_map_block_diagonal, x_flat) elif algorithm == 'max': pool_groups = tf.gather(x_flat, pool_map_block_diagonal.indices[:, 1]) pooled = tf.math.segment_max( data=pool_groups, segment_ids=pool_map_block_diagonal.indices[:, 0]) else: raise ValueError('The pooling method must be "weighted" or "max"') if batched: if sizes_output is not None: pooled = utils.unflatten_2d_to_batch(pooled, sizes_output) else: output_shape = tf.concat((tf.shape(input=pool_map)[:-1], (-1,)), axis=0) pooled = tf.reshape(pooled, output_shape) return pooled def unpool(data, pool_map, sizes, name=None): # pyformat: disable r"""Graph upsampling by inverting the pooling map. Upsamples a graph by applying a pooling map in reverse. The inputs `pool_map` and `sizes` are the same as used for pooling: >>> pooled = pool(data, pool_map, sizes) >>> upsampled = unpool(pooled, pool_map, sizes) The shorthands used below are `V1`: The number of vertices in the input data. `V2`: The number of vertices in the unpooled output data. `C`: The number of channels in the data. Note: In the following, A1 to A3 are optional batch dimensions. Only up to three batch dimensions are supported due to limitations with TensorFlow's dense-sparse multiplication. Please see the documentation for `graph_pooling.pool` for a detailed interpretation of the inputs `pool_map` and `sizes`. Args: data: A `float` tensor with shape `[A1, ..., A3, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., A3, V1, V2]`. The features for vertex `v1` are computed by pooling over the entries in `pool_map[A1, ..., A3, v1, :]`. This function applies this pooling map in reverse. sizes: An `int` tensor of shape `[A1, ..., A3, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding): `sizes[A1, ..., A3, 0] <= V1` and `sizes[A1, ..., A3, 1] <= V2`. name: A name for this op. Defaults to 'graph_pooling_unpool'. Returns: Tensor with shape `[A1, ..., A3, V2, C]`. Raises: TypeError: if the input types are invalid. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_unpool', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_unpooling_input(data, pool_map, sizes) # Reverse pool_map and sizes. pool_map_ndims = pool_map.shape.ndims permutation = tf.concat((tf.range(pool_map_ndims - 2), (pool_map_ndims - 1, pool_map_ndims - 2)), axis=0) pool_map_transpose = tf.sparse.transpose(pool_map, permutation) row_sum = tf.sparse.reduce_sum( tf.abs(pool_map_transpose), keepdims=True, axis=-1) normalize_weights = tf.compat.v1.where( tf.equal(row_sum, 0), row_sum, 1.0 / row_sum) pool_map_normalize = normalize_weights * pool_map_transpose if sizes is not None: sizes = tf.reverse(sizes, axis=(-1,)) return pool(data, pool_map_normalize, sizes) def upsample_transposed_convolution(data, pool_map, sizes, kernel_size, transposed_convolution_op, name=None): # pyformat: disable r"""Graph upsampling by transposed convolution. Upsamples a graph using a transposed convolution op. The map from input vertices to the upsampled graph is specified by the reverse of pool_map. The inputs `pool_map` and `sizes` are the same as used for pooling: >>> pooled = pool(data, pool_map, sizes) >>> upsampled = upsample_transposed_convolution(pooled, pool_map, sizes, ...) The shorthands used below are `V1`: The number of vertices in the inputs. `V2`: The number of vertices in the upsampled output. `C`: The number of channels in the inputs. Note: In the following, A1 to A3 are optional batch dimensions. Only up to three batch dimensions are supported due to limitations with TensorFlow's dense-sparse multiplication. Please see the documentation for `graph_pooling.pool` for a detailed interpretation of the inputs `pool_map` and `sizes`. Args: data: A `float` tensor with shape `[A1, ..., A3, V1, C]`. pool_map: A `SparseTensor` with the same type as `data` and with shape `[A1, ..., A3, V1, V2]`. `pool_map` will be interpreted in the same way as the `pool_map` argument of `graph_pooling.pool`, namely `v_i_map = [..., v_i, :]` are the upsampled vertices corresponding to vertex `v_i`. Additionally, for transposed convolution a fixed number of entries in each `v_i_map` (equal to `kernel_size`) are expected: `|v_i_map| = kernel_size`. When this is not the case, the map is either truncated or the last element repeated. Furthermore, upsampled vertex indices should not be repeated across maps otherwise the output is nondeterministic. Specifically, to avoid nondeterminism we must have `intersect([a1, ..., an, v_i, :],[a1, ..., a3, v_j, :]) = {}, i != j`. sizes: An `int` tensor of shape `[A1, ..., A3, 2]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding): `sizes[A1, ..., A3, 0] <= V1` and `sizes[A1, ..., A3, 1] <= V2`. kernel_size: The kernel size for transposed convolution. transposed_convolution_op: A callable transposed convolution op with the form `y = transposed_convolution_op(x)`, where `x` has shape `[1, 1, D1, C]` and `y` must have shape `[1, 1, kernel_size * D1, C]`. `transposed_convolution_op` maps each row of `x` to `kernel_size` rows in `y`. An example: `transposed_convolution_op = tf.keras.layers.Conv2DTranspose( filters=C, kernel_size=(1, kernel_size), strides=(1, kernel_size), padding='valid', ...) name: A name for this op. Defaults to 'graph_pooling_upsample_transposed_convolution'. Returns: Tensor with shape `[A1, ..., A3, V2, C]`. Raises: TypeError: if the input types are invalid. TypeError: if `transposed_convolution_op` is not a callable. ValueError: if the input dimensions are invalid. """ # pyformat: enable with tf.compat.v1.name_scope( name, 'graph_pooling_upsample_transposed_convolution', [data, pool_map, sizes]): data = tf.convert_to_tensor(value=data) pool_map = tf.compat.v1.convert_to_tensor_or_sparse_tensor(value=pool_map) if sizes is not None: sizes = tf.convert_to_tensor(value=sizes) utils.check_valid_graph_unpooling_input(data, pool_map, sizes) if not callable(transposed_convolution_op): raise TypeError("'transposed_convolution_op' must be callable.") if sizes is not None: sizes_input, sizes_output = tf.split(sizes, 2, axis=-1) sizes_input = tf.squeeze(sizes_input, axis=-1) sizes_output = tf.squeeze(sizes_output, axis=-1) else: sizes_input = None sizes_output = None num_features = tf.compat.v1.dimension_value(data.shape[-1]) batched = data.shape.ndims > 2 if batched: x_flat, _ = utils.flatten_batch_to_2d(data, sizes_input) pool_map_block_diagonal = utils.convert_to_block_diag_2d(pool_map, sizes) else: x_flat = data pool_map_block_diagonal = pool_map x_flat = tf.expand_dims(tf.expand_dims(x_flat, 0), 0) x_upsample = transposed_convolution_op(x_flat) # Map each upsampled vertex into its correct position based on pool_map. # Select 'kernel_size' neighbors for each input vertex. Truncate or repeat # as necessary. ragged = tf.RaggedTensor.from_value_rowids( pool_map_block_diagonal.indices[:, 1], pool_map_block_diagonal.indices[:, 0]) # Take up to the first 'kernel_size' entries. ragged_k = ragged[:, :kernel_size] # Fill rows with less than 'kernel_size' entries by repeating the last # entry. last = ragged_k[:, -1:].flat_values num_repeat = kernel_size - ragged_k.row_lengths() sum_num_repeat = tf.reduce_sum(input_tensor=num_repeat) ones_ragged = tf.RaggedTensor.from_row_lengths( tf.ones((sum_num_repeat,), dtype=last.dtype), num_repeat) repeat = ones_ragged * tf.expand_dims(last, -1) padded = tf.concat([ragged_k, repeat], axis=1) pool_map_dense = tf.reshape(padded.flat_values, (-1, kernel_size)) # Map rows of 'x_upsample' to positions indicated by the # indices 'pool_map_dense'. up_scatter_indices = tf.expand_dims(tf.reshape(pool_map_dense, (-1,)), -1) up_row = tf.reshape(tf.cast(up_scatter_indices, tf.int64), (-1,)) up_column = tf.range(tf.shape(input=up_row, out_type=tf.dtypes.int64)[0]) scatter_indices = tf.concat( (tf.expand_dims(up_row, -1), tf.expand_dims(up_column, -1)), axis=1) scatter_values = tf.ones_like(up_row, dtype=x_upsample.dtype) scatter_shape = tf.reduce_max(input_tensor=scatter_indices, axis=0) + 1 scatter = tf.SparseTensor(scatter_indices, scatter_values, scatter_shape) scatter = tf.sparse.reorder(scatter) row_sum = tf.sparse.reduce_sum(tf.abs(scatter), keepdims=True, axis=-1) row_sum = tf.compat.v1.where(tf.equal(row_sum, 0.), row_sum, 1.0 / row_sum) scatter = row_sum * scatter x_upsample = tf.sparse.sparse_dense_matmul(scatter, x_upsample[0, 0, :, :]) if batched: if sizes_output is not None: x_upsample = utils.unflatten_2d_to_batch(x_upsample, sizes_output) else: output_shape = tf.concat((tf.shape(input=pool_map)[:-2], tf.shape(input=pool_map)[-1:], (num_features,)), axis=0) x_upsample = tf.reshape(x_upsample, output_shape) return x_upsample # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./setup.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup for pip package. Usage: python setup.py sdist bdist_wheel [--nightly] Note: assumes setup.py file lives at the root of the project. """ import datetime import os import sys import setuptools # --- Name to use in PyPi if "--nightly" in sys.argv: sys.argv.remove("--nightly") NAME = "tfg-nightly" else: NAME = "tensorflow-graphics" # --- compute the version (for both nightly and normal) now = datetime.datetime.now() VERSION = "{}.{}.{}".format(now.year, now.month, now.day) curr_path = os.path.dirname(__file__) ini_file_path = os.path.join(curr_path, "tensorflow_graphics/__init__.py") ini_file_lines = list(open(ini_file_path)) with open(ini_file_path, "w") as f: for line in ini_file_lines: f.write(line.replace("__version__ = \"HEAD\"", "__version__ = \"{}\"".format(VERSION))) # --- Extract the dependencies REQS = [line.strip() for line in open("requirements.txt")] INSTALL_PACKAGES = [line for line in REQS if not line.startswith("#")] # --- Build the whl file setuptools.setup( name=NAME, version=VERSION, description=("A library that contains well defined, reusable and cleanly " "written graphics related ops and utility functions for " "TensorFlow."), long_description="", url="https://github.com/tensorflow/graphics", author="Google LLC", author_email="tf-graphics-eng@google.com", install_requires=INSTALL_PACKAGES, include_package_data=True, packages=setuptools.find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], license="Apache 2.0", keywords=[ "machine learning", "tensorflow", "graphics", "geometry", "3D", ], )
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Setup for pip package. Usage: python setup.py sdist bdist_wheel [--nightly] Note: assumes setup.py file lives at the root of the project. """ import datetime import os import sys import setuptools # --- Name to use in PyPi if "--nightly" in sys.argv: sys.argv.remove("--nightly") NAME = "tfg-nightly" else: NAME = "tensorflow-graphics" # --- compute the version (for both nightly and normal) now = datetime.datetime.now() VERSION = "{}.{}.{}".format(now.year, now.month, now.day) curr_path = os.path.dirname(__file__) ini_file_path = os.path.join(curr_path, "tensorflow_graphics/__init__.py") ini_file_lines = list(open(ini_file_path)) with open(ini_file_path, "w") as f: for line in ini_file_lines: f.write(line.replace("__version__ = \"HEAD\"", "__version__ = \"{}\"".format(VERSION))) # --- Extract the dependencies REQS = [line.strip() for line in open("requirements.txt")] INSTALL_PACKAGES = [line for line in REQS if not line.startswith("#")] # --- Build the whl file setuptools.setup( name=NAME, version=VERSION, description=("A library that contains well defined, reusable and cleanly " "written graphics related ops and utility functions for " "TensorFlow."), long_description="", url="https://github.com/tensorflow/graphics", author="Google LLC", author_email="tf-graphics-eng@google.com", install_requires=INSTALL_PACKAGES, include_package_data=True, packages=setuptools.find_packages(), classifiers=[ "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], license="Apache 2.0", keywords=[ "machine learning", "tensorflow", "graphics", "geometry", "3D", ], )
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/nn/layer/graph_convolution.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements graph convolutions layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow_graphics.geometry.convolution.graph_convolution as gc from tensorflow_graphics.util import export_api def feature_steered_convolution_layer( data, neighbors, sizes, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.1), name=None, var_name=None): # pyformat: disable """Wraps the function `feature_steered_convolution` as a TensorFlow layer. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A SparseTensor with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `i` and `j` are neighbors, `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1` and `V2` vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels = C`. initializer: An initializer for the trainable variables. name: A (name_scope) name for this op. Passed through to feature_steered_convolution(). var_name: A (var_scope) name for the variables. Defaults to `graph_convolution_feature_steered_convolution_weights`. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable with tf.compat.v1.variable_scope( var_name, default_name='graph_convolution_feature_steered_convolution_weights'): # Skips shape validation to avoid redundancy with # feature_steered_convolution(). data = tf.convert_to_tensor(value=data) in_channels = tf.compat.v1.dimension_value(data.shape[-1]) if num_output_channels is None: out_channels = in_channels else: out_channels = num_output_channels var_u = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='u') if translation_invariant: var_v = -var_u else: var_v = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='v') var_c = tf.compat.v1.get_variable( shape=(num_weight_matrices), dtype=data.dtype, initializer=initializer, name='c') var_w = tf.compat.v1.get_variable( shape=(num_weight_matrices, in_channels, out_channels), dtype=data.dtype, initializer=initializer, name='w') var_b = tf.compat.v1.get_variable( shape=(out_channels), dtype=data.dtype, initializer=initializer, name='b') return gc.feature_steered_convolution( data=data, neighbors=neighbors, sizes=sizes, var_u=var_u, var_v=var_v, var_c=var_c, var_w=var_w, var_b=var_b, name=name) class FeatureSteeredConvolutionKerasLayer(tf.keras.layers.Layer): """Wraps the function `feature_steered_convolution` as a Keras layer.""" def __init__(self, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=None, name=None, **kwargs): """Initializes FeatureSteeredConvolutionKerasLayer. Args: translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels` will be the same as the input dimensionality. initializer: An initializer for the trainable variables. If `None`, defaults to `tf.compat.v1.truncated_normal_initializer(stddev=0.1)`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(FeatureSteeredConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_weight_matrices = num_weight_matrices self._num_output_channels = num_output_channels self._translation_invariant = translation_invariant if initializer is None: self._initializer = tf.compat.v1.truncated_normal_initializer(stddev=0.1) else: self._initializer = initializer def build(self, input_shape): """Initializes the trainable weights.""" in_channels = tf.TensorShape(input_shape[0]).as_list()[-1] if self._num_output_channels is None: out_channels = in_channels else: out_channels = self._num_output_channels dtype = self.dtype num_weight_matrices = self._num_weight_matrices initializer = self._initializer self.var_u = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='u') if self._translation_invariant: self.var_v = -self.var_u else: self.var_v = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='v') self.var_c = self.add_weight( shape=(num_weight_matrices,), dtype=dtype, initializer=initializer, name='c') self.var_w = self.add_weight( shape=(num_weight_matrices, in_channels, out_channels), dtype=dtype, initializer=initializer, name='w', trainable=True) self.var_b = self.add_weight( shape=(out_channels,), dtype=dtype, initializer=initializer, name='b', trainable=True) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `j` is a neighbor of vertex `i`, and `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable sizes = kwargs.get('sizes', None) return gc.feature_steered_convolution( data=inputs[0], neighbors=inputs[1], sizes=sizes, var_u=self.var_u, var_v=self.var_v, var_c=self.var_c, var_w=self.var_w, var_b=self.var_b) class DynamicGraphConvolutionKerasLayer(tf.keras.layers.Layer): """A keras layer for dynamic graph convolutions. Dynamic GraphCNN for Learning on Point Clouds Yue Wang, Yongbin Sun, Ziwei Liu, Sanjay E. Sarma, Michael Bronstein, and Justin Solomon. https://arxiv.org/abs/1801.07829 This layer implements an instance of the graph convolutional operation described in the paper above, specifically a graph convolution block with a single edge filtering layer. This implementation is intended to demonstrate how `graph_convolution.edge_convolution_template` can be wrapped to implement a variety of edge convolutional methods. This implementation is slightly generalized version to what is described in the paper in that here variable sized neighborhoods are allowed rather than forcing a fixed size k-neighbors. Users must provide the neighborhoods as input. """ def __init__(self, num_output_channels, reduction, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name=None, **kwargs): """Initializes DynamicGraphConvolutionKerasLayer. Args: num_output_channels: An `int` specifying the number of output channels. reduction: Either 'weighted' or 'max'. Specifies the reduction over neighborhood edge features as described in the paper above. activation: The `activation` argument of `tf.keras.layers.Conv1D`. use_bias: The `use_bias` argument of `tf.keras.layers.Conv1D`. kernel_initializer: The `kernel_initializer` argument of `tf.keras.layers.Conv1D`. bias_initializer: The `bias_initializer` argument of `tf.keras.layers.Conv1D`. kernel_regularizer: The `kernel_regularizer` argument of `tf.keras.layers.Conv1D`. bias_regularizer: The `bias_regularizer` argument of `tf.keras.layers.Conv1D`. activity_regularizer: The `activity_regularizer` argument of `tf.keras.layers.Conv1D`. kernel_constraint: The `kernel_constraint` argument of `tf.keras.layers.Conv1D`. bias_constraint: The `bias_constraint` argument of `tf.keras.layers.Conv1D`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(DynamicGraphConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_output_channels = num_output_channels self._reduction = reduction self._activation = activation self._use_bias = use_bias self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._activity_regularizer = activity_regularizer self._kernel_constraint = kernel_constraint self._bias_constraint = bias_constraint def build(self, input_shape): # pylint: disable=unused-argument """Initializes the layer weights.""" self._conv1d_layer = tf.keras.layers.Conv1D( filters=self._num_output_channels, kernel_size=1, strides=1, padding='valid', activation=self._activation, use_bias=self._use_bias, kernel_initializer=self._kernel_initializer, bias_initializer=self._bias_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For `reduction='weighted'`, `neighbors` should be a row-normalized matrix: `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`, although this is not enforced in the implementation in case different neighbor weighting schemes are desired. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable def _edge_convolution(vertices, neighbors, conv1d_layer): r"""The edge filtering op passed to `edge_convolution_template`. This instance implements the edge function $$h_{\theta}(x, y) = MLP_{\theta}([x, y - x])$$ Args: vertices: A 2-D Tensor with shape `[D1, D2]`. neighbors: A 2-D Tensor with the same shape and type as `vertices`. conv1d_layer: A callable 1d convolution layer. Returns: A 2-D Tensor with shape `[D1, D3]`. """ concat_features = tf.concat( values=[vertices, neighbors - vertices], axis=-1) concat_features = tf.expand_dims(concat_features, 0) convolved_features = conv1d_layer(concat_features) convolved_features = tf.squeeze(input=convolved_features, axis=(0,)) return convolved_features sizes = kwargs.get('sizes', None) return gc.edge_convolution_template( data=inputs[0], neighbors=inputs[1], sizes=sizes, edge_function=_edge_convolution, reduction=self._reduction, edge_function_kwargs={'conv1d_layer': self._conv1d_layer}) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements graph convolutions layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import tensorflow_graphics.geometry.convolution.graph_convolution as gc from tensorflow_graphics.util import export_api def feature_steered_convolution_layer( data, neighbors, sizes, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=tf.compat.v1.truncated_normal_initializer(stddev=0.1), name=None, var_name=None): # pyformat: disable """Wraps the function `feature_steered_convolution` as a TensorFlow layer. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: data: A `float` tensor with shape `[A1, ..., An, V, C]`. neighbors: A SparseTensor with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `i` and `j` are neighbors, `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. sizes: An `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1` and `V2` vertices respectively. The padded input would have the following shapes: `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels = C`. initializer: An initializer for the trainable variables. name: A (name_scope) name for this op. Passed through to feature_steered_convolution(). var_name: A (var_scope) name for the variables. Defaults to `graph_convolution_feature_steered_convolution_weights`. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable with tf.compat.v1.variable_scope( var_name, default_name='graph_convolution_feature_steered_convolution_weights'): # Skips shape validation to avoid redundancy with # feature_steered_convolution(). data = tf.convert_to_tensor(value=data) in_channels = tf.compat.v1.dimension_value(data.shape[-1]) if num_output_channels is None: out_channels = in_channels else: out_channels = num_output_channels var_u = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='u') if translation_invariant: var_v = -var_u else: var_v = tf.compat.v1.get_variable( shape=(in_channels, num_weight_matrices), dtype=data.dtype, initializer=initializer, name='v') var_c = tf.compat.v1.get_variable( shape=(num_weight_matrices), dtype=data.dtype, initializer=initializer, name='c') var_w = tf.compat.v1.get_variable( shape=(num_weight_matrices, in_channels, out_channels), dtype=data.dtype, initializer=initializer, name='w') var_b = tf.compat.v1.get_variable( shape=(out_channels), dtype=data.dtype, initializer=initializer, name='b') return gc.feature_steered_convolution( data=data, neighbors=neighbors, sizes=sizes, var_u=var_u, var_v=var_v, var_c=var_c, var_w=var_w, var_b=var_b, name=name) class FeatureSteeredConvolutionKerasLayer(tf.keras.layers.Layer): """Wraps the function `feature_steered_convolution` as a Keras layer.""" def __init__(self, translation_invariant=True, num_weight_matrices=8, num_output_channels=None, initializer=None, name=None, **kwargs): """Initializes FeatureSteeredConvolutionKerasLayer. Args: translation_invariant: A `bool`. If `True` the assignment of features to weight matrices will be invariant to translation. num_weight_matrices: An `int` specifying the number of weight matrices used in the convolution. num_output_channels: An optional `int` specifying the number of channels in the output. If `None` then `num_output_channels` will be the same as the input dimensionality. initializer: An initializer for the trainable variables. If `None`, defaults to `tf.compat.v1.truncated_normal_initializer(stddev=0.1)`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(FeatureSteeredConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_weight_matrices = num_weight_matrices self._num_output_channels = num_output_channels self._translation_invariant = translation_invariant if initializer is None: self._initializer = tf.compat.v1.truncated_normal_initializer(stddev=0.1) else: self._initializer = initializer def build(self, input_shape): """Initializes the trainable weights.""" in_channels = tf.TensorShape(input_shape[0]).as_list()[-1] if self._num_output_channels is None: out_channels = in_channels else: out_channels = self._num_output_channels dtype = self.dtype num_weight_matrices = self._num_weight_matrices initializer = self._initializer self.var_u = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='u') if self._translation_invariant: self.var_v = -self.var_u else: self.var_v = self.add_weight( shape=(in_channels, num_weight_matrices), dtype=dtype, initializer=initializer, name='v') self.var_c = self.add_weight( shape=(num_weight_matrices,), dtype=dtype, initializer=initializer, name='c') self.var_w = self.add_weight( shape=(num_weight_matrices, in_channels, out_channels), dtype=dtype, initializer=initializer, name='w', trainable=True) self.var_b = self.add_weight( shape=(out_channels,), dtype=dtype, initializer=initializer, name='b', trainable=True) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For a faithful implementation of the FeaStNet paper, neighbors should be a row-normalized weight matrix corresponding to the graph adjacency matrix with self-edges: `neighbors[A1, ..., An, i, j] > 0` if vertex `j` is a neighbor of vertex `i`, and `neighbors[A1, ..., An, i, i] > 0` for all `i`, and `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`. These requirements are relaxed in this implementation. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable sizes = kwargs.get('sizes', None) return gc.feature_steered_convolution( data=inputs[0], neighbors=inputs[1], sizes=sizes, var_u=self.var_u, var_v=self.var_v, var_c=self.var_c, var_w=self.var_w, var_b=self.var_b) class DynamicGraphConvolutionKerasLayer(tf.keras.layers.Layer): """A keras layer for dynamic graph convolutions. Dynamic GraphCNN for Learning on Point Clouds Yue Wang, Yongbin Sun, Ziwei Liu, Sanjay E. Sarma, Michael Bronstein, and Justin Solomon. https://arxiv.org/abs/1801.07829 This layer implements an instance of the graph convolutional operation described in the paper above, specifically a graph convolution block with a single edge filtering layer. This implementation is intended to demonstrate how `graph_convolution.edge_convolution_template` can be wrapped to implement a variety of edge convolutional methods. This implementation is slightly generalized version to what is described in the paper in that here variable sized neighborhoods are allowed rather than forcing a fixed size k-neighbors. Users must provide the neighborhoods as input. """ def __init__(self, num_output_channels, reduction, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, name=None, **kwargs): """Initializes DynamicGraphConvolutionKerasLayer. Args: num_output_channels: An `int` specifying the number of output channels. reduction: Either 'weighted' or 'max'. Specifies the reduction over neighborhood edge features as described in the paper above. activation: The `activation` argument of `tf.keras.layers.Conv1D`. use_bias: The `use_bias` argument of `tf.keras.layers.Conv1D`. kernel_initializer: The `kernel_initializer` argument of `tf.keras.layers.Conv1D`. bias_initializer: The `bias_initializer` argument of `tf.keras.layers.Conv1D`. kernel_regularizer: The `kernel_regularizer` argument of `tf.keras.layers.Conv1D`. bias_regularizer: The `bias_regularizer` argument of `tf.keras.layers.Conv1D`. activity_regularizer: The `activity_regularizer` argument of `tf.keras.layers.Conv1D`. kernel_constraint: The `kernel_constraint` argument of `tf.keras.layers.Conv1D`. bias_constraint: The `bias_constraint` argument of `tf.keras.layers.Conv1D`. name: A name for this layer. **kwargs: Additional keyword arguments passed to the base layer. """ super(DynamicGraphConvolutionKerasLayer, self).__init__( name=name, **kwargs) self._num_output_channels = num_output_channels self._reduction = reduction self._activation = activation self._use_bias = use_bias self._kernel_initializer = kernel_initializer self._bias_initializer = bias_initializer self._kernel_regularizer = kernel_regularizer self._bias_regularizer = bias_regularizer self._activity_regularizer = activity_regularizer self._kernel_constraint = kernel_constraint self._bias_constraint = bias_constraint def build(self, input_shape): # pylint: disable=unused-argument """Initializes the layer weights.""" self._conv1d_layer = tf.keras.layers.Conv1D( filters=self._num_output_channels, kernel_size=1, strides=1, padding='valid', activation=self._activation, use_bias=self._use_bias, kernel_initializer=self._kernel_initializer, bias_initializer=self._bias_initializer, kernel_regularizer=self._kernel_regularizer, bias_regularizer=self._bias_regularizer, activity_regularizer=self._activity_regularizer, kernel_constraint=self._kernel_constraint, bias_constraint=self._bias_constraint) def call(self, inputs, **kwargs): # pyformat: disable """Executes the convolution. The shorthands used below are `V`: The number of vertices. `C`: The number of channels in the input data. Note: In the following, A1 to An are optional batch dimensions. Args: inputs: A list of two tensors `[data, neighbors]`. `data` is a `float` tensor with shape `[A1, ..., An, V, C]`. `neighbors` is a `SparseTensor` with the same type as `data` and with shape `[A1, ..., An, V, V]` representing vertex neighborhoods. The neighborhood of a vertex defines the support region for convolution. For a mesh, a common choice for the neighborhood of vertex `i` would be the vertices in the K-ring of `i` (including `i` itself). Each vertex must have at least one neighbor. For `reduction='weighted'`, `neighbors` should be a row-normalized matrix: `sum(neighbors, axis=-1)[A1, ..., An, i] == 1.0` for all `i`, although this is not enforced in the implementation in case different neighbor weighting schemes are desired. **kwargs: A dictionary containing the key `sizes`, which is an `int` tensor of shape `[A1, ..., An]` indicating the true input sizes in case of padding (`sizes=None` indicates no padding). `sizes[A1, ..., An] <= V`. If `data` and `neighbors` are 2-D, `sizes` will be ignored. As an example usage of `sizes`, consider an input consisting of three graphs `G0`, `G1`, and `G2` with `V0`, `V1`, and `V2` vertices respectively. The padded input would have the shapes `data.shape = [3, V, C]`, and `neighbors.shape = [3, V, V]`, where `V = max([V0, V1, V2])`. The true sizes of each graph will be specified by `sizes=[V0, V1, V2]`. `data[i, :Vi, :]` and `neighbors[i, :Vi, :Vi]` will be the vertex and neighborhood data of graph `Gi`. The `SparseTensor` `neighbors` should have no nonzero entries in the padded regions. Returns: Tensor with shape `[A1, ..., An, V, num_output_channels]`. """ # pyformat: enable def _edge_convolution(vertices, neighbors, conv1d_layer): r"""The edge filtering op passed to `edge_convolution_template`. This instance implements the edge function $$h_{\theta}(x, y) = MLP_{\theta}([x, y - x])$$ Args: vertices: A 2-D Tensor with shape `[D1, D2]`. neighbors: A 2-D Tensor with the same shape and type as `vertices`. conv1d_layer: A callable 1d convolution layer. Returns: A 2-D Tensor with shape `[D1, D3]`. """ concat_features = tf.concat( values=[vertices, neighbors - vertices], axis=-1) concat_features = tf.expand_dims(concat_features, 0) convolved_features = conv1d_layer(concat_features) convolved_features = tf.squeeze(input=convolved_features, axis=(0,)) return convolved_features sizes = kwargs.get('sizes', None) return gc.edge_convolution_template( data=inputs[0], neighbors=inputs[1], sizes=sizes, edge_function=_edge_convolution, reduction=self._reduction, edge_function_kwargs={'conv1d_layer': self._conv1d_layer}) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/nn/metric/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name="assert_rotation_matrix_normalized"): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.debugging.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name="rotation_matrix_3d_from_axis_angle"): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name="rotation_matrix_3d_from_euler"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_3d_from_euler_with_small_angles"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler_with_small_angles". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name="rotation_matrix_3d_from_quaternion"): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_3d_inverse"): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_3d_is_valid"): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_3d_rotate"): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name="assert_rotation_matrix_normalized"): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.debugging.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name="rotation_matrix_3d_from_axis_angle"): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name="rotation_matrix_3d_from_euler"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_3d_from_euler_with_small_angles"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler_with_small_angles". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name="rotation_matrix_3d_from_quaternion"): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_3d_inverse"): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_3d_is_valid"): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_3d_rotate"): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/reflectance/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reflectance module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.reflectance import blinn_phong from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.reflectance. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reflectance module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.rendering.reflectance import blinn_phong from tensorflow_graphics.rendering.reflectance import lambertian from tensorflow_graphics.rendering.reflectance import phong from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.rendering.reflectance. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/opengl/tests/rasterizer_op_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the opengl rasterizer op.""" from absl.testing import parameterized import numpy as np import six import tensorflow as tf from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.opengl import rasterization_backend from tensorflow_graphics.util import test_case # Empty vertex shader test_vertex_shader = """ #version 450 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. test_geometry_shader = """ #version 450 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec3 position; out layout(location = 1) vec3 normal; out layout(location = 2) vec2 bar_coord; out layout(location = 3) float tri_id; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int i) { int o = gl_PrimitiveIDIn * 9 + i * 3; return vec3(mesh_buffer[o + 0], mesh_buffer[o + 1], mesh_buffer[o + 2]); } bool is_back_facing(vec3 v0, vec3 v1, vec3 v2) { vec4 tv0 = view_projection_matrix * vec4(v0, 1.0); vec4 tv1 = view_projection_matrix * vec4(v1, 1.0); vec4 tv2 = view_projection_matrix * vec4(v2, 1.0); tv0 /= tv0.w; tv1 /= tv1.w; tv2 /= tv2.w; vec2 a = (tv1.xy - tv0.xy); vec2 b = (tv2.xy - tv0.xy); return (a.x * b.y - b.x * a.y) <= 0; } void main() { vec3 v0 = get_vertex_position(0); vec3 v1 = get_vertex_position(1); vec3 v2 = get_vertex_position(2); // Cull back-facing triangles. if (is_back_facing(v0, v1, v2)) { return; } normal = normalize(cross(v1 - v0, v2 - v0)); vec3 positions[3] = {v0, v1, v2}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable gl_Position = view_projection_matrix * vec4(positions[i], 1); bar_coord = vec2(i==0 ? 1 : 0, i==1 ? 1 : 0); tri_id = gl_PrimitiveIDIn; position = positions[i]; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, triangle index, and depth # map in a resulting vec4 per pixel. test_fragment_shader = """ #version 450 in layout(location = 0) vec3 position; in layout(location = 1) vec3 normal; in layout(location = 2) vec2 bar_coord; in layout(location = 3) float tri_id; out vec4 output_color; void main() { output_color = vec4(bar_coord, tri_id, position.z); } """ class RasterizerOPTest(test_case.TestCase): def test_rasterize(self): max_depth = 10 min_depth = 2 height = 480 width = 640 camera_origin = (0.0, 0.0, 0.0) camera_up = (0.0, 1.0, 0.0) look_at_point = (0.0, 0.0, 1.0) fov = (60.0 * np.math.pi / 180,) near_plane = (1.0,) far_plane = (10.0,) batch_shape = tf.convert_to_tensor( value=(2, (max_depth - min_depth) // 2), dtype=tf.int32) world_to_camera = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed( fov, (float(width) / float(height),), near_plane, far_plane) view_projection_matrix = tf.matmul(perspective_matrix, world_to_camera) view_projection_matrix = tf.squeeze(view_projection_matrix) # Generate triangles at different depths and associated ground truth. tris = np.zeros((max_depth - min_depth, 9), dtype=np.float32) gt = np.zeros((max_depth - min_depth, height, width, 2), dtype=np.float32) for idx in range(max_depth - min_depth): tris[idx, :] = (-100.0, 100.0, idx + min_depth, 100.0, 100.0, idx + min_depth, 0.0, -100.0, idx + min_depth) gt[idx, :, :, :] = (0, idx + min_depth) # Broadcast the variables. render_parameters = { "view_projection_matrix": ("mat", tf.broadcast_to( input=view_projection_matrix, shape=tf.concat( values=(batch_shape, tf.shape(input=view_projection_matrix)[-2:]), axis=0))), "triangular_mesh": ("buffer", tf.reshape( tris, shape=tf.concat(values=(batch_shape, (9,)), axis=0))) } # Reshape the ground truth. gt = tf.reshape( gt, shape=tf.concat(values=(batch_shape, (height, width, 2)), axis=0)) render_parameters = list(six.iteritems(render_parameters)) variable_names = [v[0] for v in render_parameters] variable_kinds = [v[1][0] for v in render_parameters] variable_values = [v[1][1] for v in render_parameters] def rasterize(): return rasterization_backend.render_ops.rasterize( num_points=3, variable_names=variable_names, variable_kinds=variable_kinds, variable_values=variable_values, output_resolution=(width, height), vertex_shader=test_vertex_shader, geometry_shader=test_geometry_shader, fragment_shader=test_fragment_shader, ) result = rasterize() self.assertAllClose(result[..., 2:4], gt) @tf.function def check_lazy_shape(): # Within @tf.function, the tensor shape is determined by SetShapeFn # callback. Ensure that the shape of non-batch axes matches that of of # the actual tensor evaluated in eager mode above. lazy_shape = rasterize().shape self.assertEqual(lazy_shape[-3:], list(result.shape)[-3:]) check_lazy_shape() @parameterized.parameters( ("The variable names, kinds, and values must have the same size.", ["var1"], ["buffer", "buffer"], [[1.0], [1.0]], tf.errors.InvalidArgumentError, ValueError), ("The variable names, kinds, and values must have the same size.", ["var1", "var2"], ["buffer"], [[1.0], [1.0]], tf.errors.InvalidArgumentError, ValueError), ("The variable names, kinds, and values must have the same size.", ["var1", "var2"], ["buffer", "buffer"], [[1.0]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid batch", ["var1", "var2"], ["buffer", "buffer"], [[1.0], [[1.0]]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid", ["var1"], ["mat"], [[1.0]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid", ["var1"], ["buffer"], [1.0], tf.errors.InvalidArgumentError, ValueError), ) def test_invalid_variable_inputs(self, error_msg, variable_names, variable_kinds, variable_values, error_eager, error_graph_mode): height = 1 width = 1 empty_shader_code = "#version 450\n void main() { }\n" if tf.executing_eagerly(): error = error_eager else: error = error_graph_mode with self.assertRaisesRegexp(error, error_msg): self.evaluate( rasterization_backend.render_ops.rasterize( num_points=0, variable_names=variable_names, variable_kinds=variable_kinds, variable_values=variable_values, output_resolution=(width, height), vertex_shader=empty_shader_code, geometry_shader=empty_shader_code, fragment_shader=empty_shader_code)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the opengl rasterizer op.""" from absl.testing import parameterized import numpy as np import six import tensorflow as tf from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.opengl import rasterization_backend from tensorflow_graphics.util import test_case # Empty vertex shader test_vertex_shader = """ #version 450 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. test_geometry_shader = """ #version 450 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec3 position; out layout(location = 1) vec3 normal; out layout(location = 2) vec2 bar_coord; out layout(location = 3) float tri_id; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int i) { int o = gl_PrimitiveIDIn * 9 + i * 3; return vec3(mesh_buffer[o + 0], mesh_buffer[o + 1], mesh_buffer[o + 2]); } bool is_back_facing(vec3 v0, vec3 v1, vec3 v2) { vec4 tv0 = view_projection_matrix * vec4(v0, 1.0); vec4 tv1 = view_projection_matrix * vec4(v1, 1.0); vec4 tv2 = view_projection_matrix * vec4(v2, 1.0); tv0 /= tv0.w; tv1 /= tv1.w; tv2 /= tv2.w; vec2 a = (tv1.xy - tv0.xy); vec2 b = (tv2.xy - tv0.xy); return (a.x * b.y - b.x * a.y) <= 0; } void main() { vec3 v0 = get_vertex_position(0); vec3 v1 = get_vertex_position(1); vec3 v2 = get_vertex_position(2); // Cull back-facing triangles. if (is_back_facing(v0, v1, v2)) { return; } normal = normalize(cross(v1 - v0, v2 - v0)); vec3 positions[3] = {v0, v1, v2}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable gl_Position = view_projection_matrix * vec4(positions[i], 1); bar_coord = vec2(i==0 ? 1 : 0, i==1 ? 1 : 0); tri_id = gl_PrimitiveIDIn; position = positions[i]; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, triangle index, and depth # map in a resulting vec4 per pixel. test_fragment_shader = """ #version 450 in layout(location = 0) vec3 position; in layout(location = 1) vec3 normal; in layout(location = 2) vec2 bar_coord; in layout(location = 3) float tri_id; out vec4 output_color; void main() { output_color = vec4(bar_coord, tri_id, position.z); } """ class RasterizerOPTest(test_case.TestCase): def test_rasterize(self): max_depth = 10 min_depth = 2 height = 480 width = 640 camera_origin = (0.0, 0.0, 0.0) camera_up = (0.0, 1.0, 0.0) look_at_point = (0.0, 0.0, 1.0) fov = (60.0 * np.math.pi / 180,) near_plane = (1.0,) far_plane = (10.0,) batch_shape = tf.convert_to_tensor( value=(2, (max_depth - min_depth) // 2), dtype=tf.int32) world_to_camera = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed( fov, (float(width) / float(height),), near_plane, far_plane) view_projection_matrix = tf.matmul(perspective_matrix, world_to_camera) view_projection_matrix = tf.squeeze(view_projection_matrix) # Generate triangles at different depths and associated ground truth. tris = np.zeros((max_depth - min_depth, 9), dtype=np.float32) gt = np.zeros((max_depth - min_depth, height, width, 2), dtype=np.float32) for idx in range(max_depth - min_depth): tris[idx, :] = (-100.0, 100.0, idx + min_depth, 100.0, 100.0, idx + min_depth, 0.0, -100.0, idx + min_depth) gt[idx, :, :, :] = (0, idx + min_depth) # Broadcast the variables. render_parameters = { "view_projection_matrix": ("mat", tf.broadcast_to( input=view_projection_matrix, shape=tf.concat( values=(batch_shape, tf.shape(input=view_projection_matrix)[-2:]), axis=0))), "triangular_mesh": ("buffer", tf.reshape( tris, shape=tf.concat(values=(batch_shape, (9,)), axis=0))) } # Reshape the ground truth. gt = tf.reshape( gt, shape=tf.concat(values=(batch_shape, (height, width, 2)), axis=0)) render_parameters = list(six.iteritems(render_parameters)) variable_names = [v[0] for v in render_parameters] variable_kinds = [v[1][0] for v in render_parameters] variable_values = [v[1][1] for v in render_parameters] def rasterize(): return rasterization_backend.render_ops.rasterize( num_points=3, variable_names=variable_names, variable_kinds=variable_kinds, variable_values=variable_values, output_resolution=(width, height), vertex_shader=test_vertex_shader, geometry_shader=test_geometry_shader, fragment_shader=test_fragment_shader, ) result = rasterize() self.assertAllClose(result[..., 2:4], gt) @tf.function def check_lazy_shape(): # Within @tf.function, the tensor shape is determined by SetShapeFn # callback. Ensure that the shape of non-batch axes matches that of of # the actual tensor evaluated in eager mode above. lazy_shape = rasterize().shape self.assertEqual(lazy_shape[-3:], list(result.shape)[-3:]) check_lazy_shape() @parameterized.parameters( ("The variable names, kinds, and values must have the same size.", ["var1"], ["buffer", "buffer"], [[1.0], [1.0]], tf.errors.InvalidArgumentError, ValueError), ("The variable names, kinds, and values must have the same size.", ["var1", "var2"], ["buffer"], [[1.0], [1.0]], tf.errors.InvalidArgumentError, ValueError), ("The variable names, kinds, and values must have the same size.", ["var1", "var2"], ["buffer", "buffer"], [[1.0]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid batch", ["var1", "var2"], ["buffer", "buffer"], [[1.0], [[1.0]]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid", ["var1"], ["mat"], [[1.0]], tf.errors.InvalidArgumentError, ValueError), ("has an invalid", ["var1"], ["buffer"], [1.0], tf.errors.InvalidArgumentError, ValueError), ) def test_invalid_variable_inputs(self, error_msg, variable_names, variable_kinds, variable_values, error_eager, error_graph_mode): height = 1 width = 1 empty_shader_code = "#version 450\n void main() { }\n" if tf.executing_eagerly(): error = error_eager else: error = error_graph_mode with self.assertRaisesRegexp(error, error_msg): self.evaluate( rasterization_backend.render_ops.rasterize( num_points=0, variable_names=variable_names, variable_kinds=variable_kinds, variable_values=variable_values, output_resolution=(width, height), vertex_shader=empty_shader_code, geometry_shader=empty_shader_code, fragment_shader=empty_shader_code)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/image/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Image module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.image import color_space from tensorflow_graphics.image import matting from tensorflow_graphics.image import pyramid from tensorflow_graphics.image import transformer from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.image. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Image module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.image import color_space from tensorflow_graphics.image import matting from tensorflow_graphics.image import pyramid from tensorflow_graphics.image import transformer from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.image. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/nn/metric/fscore.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the fscore metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.nn.metric import precision as precision_module from tensorflow_graphics.nn.metric import recall as recall_module from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def evaluate(ground_truth, prediction, precision_function=precision_module.evaluate, recall_function=recall_module.evaluate, name=None): """Computes the fscore metric for the given ground truth and predicted labels. The fscore is calculated as 2 * (precision * recall) / (precision + recall) where the precision and recall are evaluated by the given function parameters. The precision and recall functions default to their definition for boolean labels (see https://en.wikipedia.org/wiki/Precision_and_recall for more details). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth values. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predicted values. precision_function: The function to use for evaluating the precision. Defaults to the precision evaluation for binary ground-truth and predictions. recall_function: The function to use for evaluating the recall. Defaults to the recall evaluation for binary ground-truth and prediction. name: A name for this op. Defaults to "fscore_evaluate". Returns: A tensor of shape `[A1, ..., An]` that stores the fscore metric for the given ground truth labels and predictions. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "fscore_evaluate", [ground_truth, prediction]): ground_truth = tf.convert_to_tensor(value=ground_truth) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) recall = recall_function(ground_truth, prediction) precision = precision_function(ground_truth, prediction) return safe_ops.safe_signed_div(2 * precision * recall, precision + recall) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the fscore metric.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.nn.metric import precision as precision_module from tensorflow_graphics.nn.metric import recall as recall_module from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def evaluate(ground_truth, prediction, precision_function=precision_module.evaluate, recall_function=recall_module.evaluate, name=None): """Computes the fscore metric for the given ground truth and predicted labels. The fscore is calculated as 2 * (precision * recall) / (precision + recall) where the precision and recall are evaluated by the given function parameters. The precision and recall functions default to their definition for boolean labels (see https://en.wikipedia.org/wiki/Precision_and_recall for more details). Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: ground_truth: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the ground truth values. prediction: A tensor of shape `[A1, ..., An, N]`, where the last axis represents the predicted values. precision_function: The function to use for evaluating the precision. Defaults to the precision evaluation for binary ground-truth and predictions. recall_function: The function to use for evaluating the recall. Defaults to the recall evaluation for binary ground-truth and prediction. name: A name for this op. Defaults to "fscore_evaluate". Returns: A tensor of shape `[A1, ..., An]` that stores the fscore metric for the given ground truth labels and predictions. Raises: ValueError: if the shape of `ground_truth`, `prediction` is not supported. """ with tf.compat.v1.name_scope(name, "fscore_evaluate", [ground_truth, prediction]): ground_truth = tf.convert_to_tensor(value=ground_truth) prediction = tf.convert_to_tensor(value=prediction) shape.compare_batch_dimensions( tensors=(ground_truth, prediction), tensor_names=("ground_truth", "prediction"), last_axes=-1, broadcast_compatible=True) recall = recall_function(ground_truth, prediction) precision = precision_function(ground_truth, prediction) return safe_ops.safe_signed_div(2 * precision * recall, precision + recall) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/cvxnet/lib/datasets.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from os import path import tensorflow.compat.v1 as tf def get_dataset(data_name, split, args): return dataset_dict[data_name](split, args) def shapenet(split, args): """ShapeNet Dataset. Args: split: string, the split of the dataset, either "train" or "test". args: tf.app.flags.FLAGS, configurations. Returns: dataset: tf.data.Dataset, the shapenet dataset. """ total_points = 100000 data_dir = args.data_dir sample_bbx = args.sample_bbx if split != "train": sample_bbx = total_points sample_surf = args.sample_surf if split != "train": sample_surf = 0 image_h = args.image_h image_w = args.image_w image_d = args.image_d n_views = args.n_views depth_h = args.depth_h depth_w = args.depth_w depth_d = args.depth_d batch_size = args.batch_size if split == "train" else 1 dims = args.dims def _parser(example): fs = tf.parse_single_example( example, features={ "rgb": tf.FixedLenFeature([n_views * image_h * image_w * image_d], tf.float32), "depth": tf.FixedLenFeature([depth_d * depth_h * depth_w], tf.float32), "bbox_samples": tf.FixedLenFeature([total_points * (dims + 1)], tf.float32), "surf_samples": tf.FixedLenFeature([total_points * (dims + 1)], tf.float32), "name": tf.FixedLenFeature([], tf.string), }) fs["rgb"] = tf.reshape(fs["rgb"], [n_views, image_h, image_w, image_d]) fs["depth"] = tf.reshape(fs["depth"], [depth_d, depth_h, depth_w, 1]) fs["bbox_samples"] = tf.reshape(fs["bbox_samples"], [total_points, dims + 1]) fs["surf_samples"] = tf.reshape(fs["surf_samples"], [total_points, dims + 1]) return fs def _sampler(example): image = tf.gather( example["rgb"], tf.random.uniform((), minval=0, maxval=n_views if split == "train" else 1, dtype=tf.int32), axis=0) image = tf.image.resize_bilinear(tf.expand_dims(image, axis=0), [224, 224]) depth = example["depth"] / 1000. sample_points = [] sample_labels = [] if sample_bbx > 0: if split == "train": indices_bbx = tf.random.uniform([sample_bbx], minval=0, maxval=total_points, dtype=tf.int32) bbx_samples = tf.gather(example["bbox_samples"], indices_bbx, axis=0) else: bbx_samples = example["bbox_samples"] bbx_points, bbx_labels = tf.split(bbx_samples, [3, 1], axis=-1) sample_points.append(bbx_points) sample_labels.append(bbx_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=total_points, dtype=tf.int32) surf_samples = tf.gather(example["surf_samples"], indices_surf, axis=0) surf_points, surf_labels = tf.split(surf_samples, [3, 1], axis=-1) sample_points.append(surf_points) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.cast(tf.concat(sample_labels, axis=0) <= 0., tf.float32) image = tf.reshape(image, [224, 224, image_d]) depth = tf.reshape(depth, [depth_d, depth_h, depth_w]) depth = tf.transpose(depth, [1, 2, 0]) points = tf.reshape(points, [sample_bbx + sample_surf, 3]) point_labels = tf.reshape(point_labels, [sample_bbx + sample_surf, 1]) return { "image": image, "depth": depth, "point": points, "point_label": point_labels, "name": example["name"], } data_pattern = path.join(data_dir, "{}-{}-*".format(args.obj_class, split)) data_files = tf.gfile.Glob(data_pattern) if not data_files: raise ValueError("{} did not match any files".format(data_pattern)) file_count = len(data_files) filenames = tf.data.Dataset.list_files(data_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), cycle_length=file_count, num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map(_parser, num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map(_sampler, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == "train": data = data.shuffle(batch_size * 5).repeat(-1) return data.batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE) dataset_dict = { "shapenet": shapenet, }
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from os import path import tensorflow.compat.v1 as tf def get_dataset(data_name, split, args): return dataset_dict[data_name](split, args) def shapenet(split, args): """ShapeNet Dataset. Args: split: string, the split of the dataset, either "train" or "test". args: tf.app.flags.FLAGS, configurations. Returns: dataset: tf.data.Dataset, the shapenet dataset. """ total_points = 100000 data_dir = args.data_dir sample_bbx = args.sample_bbx if split != "train": sample_bbx = total_points sample_surf = args.sample_surf if split != "train": sample_surf = 0 image_h = args.image_h image_w = args.image_w image_d = args.image_d n_views = args.n_views depth_h = args.depth_h depth_w = args.depth_w depth_d = args.depth_d batch_size = args.batch_size if split == "train" else 1 dims = args.dims def _parser(example): fs = tf.parse_single_example( example, features={ "rgb": tf.FixedLenFeature([n_views * image_h * image_w * image_d], tf.float32), "depth": tf.FixedLenFeature([depth_d * depth_h * depth_w], tf.float32), "bbox_samples": tf.FixedLenFeature([total_points * (dims + 1)], tf.float32), "surf_samples": tf.FixedLenFeature([total_points * (dims + 1)], tf.float32), "name": tf.FixedLenFeature([], tf.string), }) fs["rgb"] = tf.reshape(fs["rgb"], [n_views, image_h, image_w, image_d]) fs["depth"] = tf.reshape(fs["depth"], [depth_d, depth_h, depth_w, 1]) fs["bbox_samples"] = tf.reshape(fs["bbox_samples"], [total_points, dims + 1]) fs["surf_samples"] = tf.reshape(fs["surf_samples"], [total_points, dims + 1]) return fs def _sampler(example): image = tf.gather( example["rgb"], tf.random.uniform((), minval=0, maxval=n_views if split == "train" else 1, dtype=tf.int32), axis=0) image = tf.image.resize_bilinear(tf.expand_dims(image, axis=0), [224, 224]) depth = example["depth"] / 1000. sample_points = [] sample_labels = [] if sample_bbx > 0: if split == "train": indices_bbx = tf.random.uniform([sample_bbx], minval=0, maxval=total_points, dtype=tf.int32) bbx_samples = tf.gather(example["bbox_samples"], indices_bbx, axis=0) else: bbx_samples = example["bbox_samples"] bbx_points, bbx_labels = tf.split(bbx_samples, [3, 1], axis=-1) sample_points.append(bbx_points) sample_labels.append(bbx_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=total_points, dtype=tf.int32) surf_samples = tf.gather(example["surf_samples"], indices_surf, axis=0) surf_points, surf_labels = tf.split(surf_samples, [3, 1], axis=-1) sample_points.append(surf_points) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.cast(tf.concat(sample_labels, axis=0) <= 0., tf.float32) image = tf.reshape(image, [224, 224, image_d]) depth = tf.reshape(depth, [depth_d, depth_h, depth_w]) depth = tf.transpose(depth, [1, 2, 0]) points = tf.reshape(points, [sample_bbx + sample_surf, 3]) point_labels = tf.reshape(point_labels, [sample_bbx + sample_surf, 1]) return { "image": image, "depth": depth, "point": points, "point_label": point_labels, "name": example["name"], } data_pattern = path.join(data_dir, "{}-{}-*".format(args.obj_class, split)) data_files = tf.gfile.Glob(data_pattern) if not data_files: raise ValueError("{} did not match any files".format(data_pattern)) file_count = len(data_files) filenames = tf.data.Dataset.list_files(data_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), cycle_length=file_count, num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map(_parser, num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map(_sampler, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == "train": data = data.shuffle(batch_size * 5).repeat(-1) return data.batch(batch_size).prefetch(tf.data.experimental.AUTOTUNE) dataset_dict = { "shapenet": shapenet, }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/mesh/utils.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements utility functions for meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def extract_unique_edges_from_triangular_mesh(faces, directed_edges=False): """Extracts all the unique edges using the faces of a mesh. Args: faces: A numpy.ndarray of shape [T, 3], where T is the number of triangular faces in the mesh. Each entry in this array describes the index of a vertex in the mesh. directed_edges: A boolean flag, whether to treat an edge as directed or undirected. If (i, j) is an edge in the mesh and directed_edges is True, then both (i, j) and (j, i) are returned in the list of edges. If (i, j) is an edge in the mesh and directed_edges is False, then one of (i, j) or (j, i) is returned. Returns: A numpy.ndarray of shape [E, 2], where E is the number of edges in the mesh. For eg: given faces = [[0, 1, 2], [0, 1, 3]], then for directed_edges = False, one valid output is [[0, 1], [0, 2], [0, 3], [1, 2], [3, 1]] for directed_edges = True, one valid output is [[0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [3, 0], [3, 1]] Raises: ValueError: If `faces` is not a numpy.ndarray or if its shape is not supported. """ if not isinstance(faces, np.ndarray): raise ValueError("'faces' must be a numpy.ndarray.") faces_shape = faces.shape faces_rank = len(faces_shape) if faces_rank != 2: raise ValueError( "'faces' must have a rank equal to 2, but it has rank {} and shape {}." .format(faces_rank, faces_shape)) if faces_shape[1] != 3: raise ValueError( "'faces' must have exactly 3 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(faces_shape[1], faces_shape)) edges = np.concatenate([faces[:, 0:2], faces[:, 1:3], faces[:, [2, 0]]], axis=0) if directed_edges: edges = np.concatenate([edges, np.flip(edges, axis=-1)]) unique_edges = np.unique(edges, axis=0) return unique_edges def get_degree_based_edge_weights(edges, dtype=np.float32): r"""Computes vertex degree based weights for edges of a mesh. The degree (valence) of a vertex is number of edges incident on the vertex. The weight for an edge $w_{ij}$ connecting vertex $v_i$ and vertex $v_j$ is defined as, $$ w_{ij} = 1.0 / degree(v_i) \sum_{j} w_{ij} = 1 $$ Args: edges: A numpy.ndarray of shape [E, 2], where E is the number of directed edges in the mesh. dtype: A numpy float data type. The output weights are of data type dtype. Returns: weights: A dtype numpy.ndarray of shape [E,] denoting edge weights. Raises: ValueError: If `edges` is not a numpy.ndarray or if its shape is not supported, or dtype is not a float type. """ if not isinstance(dtype(1), np.floating): raise ValueError("'dtype' must be a numpy float type.") if not isinstance(edges, np.ndarray): raise ValueError("'edges' must be a numpy.ndarray.") edges_shape = edges.shape edges_rank = len(edges_shape) if edges_rank != 2: raise ValueError( "'edges' must have a rank equal to 2, but it has rank {} and shape {}." .format(edges_rank, edges_shape)) if edges_shape[1] != 2: raise ValueError( "'edges' must have exactly 2 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(edges_shape[1], edges_shape)) degree = np.bincount(edges[:, 0]) rep_degree = degree[edges[:, 0]] weights = 1.0 / rep_degree.astype(dtype) return weights # API contains all public functions and classes. __all__ = []
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements utility functions for meshes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np def extract_unique_edges_from_triangular_mesh(faces, directed_edges=False): """Extracts all the unique edges using the faces of a mesh. Args: faces: A numpy.ndarray of shape [T, 3], where T is the number of triangular faces in the mesh. Each entry in this array describes the index of a vertex in the mesh. directed_edges: A boolean flag, whether to treat an edge as directed or undirected. If (i, j) is an edge in the mesh and directed_edges is True, then both (i, j) and (j, i) are returned in the list of edges. If (i, j) is an edge in the mesh and directed_edges is False, then one of (i, j) or (j, i) is returned. Returns: A numpy.ndarray of shape [E, 2], where E is the number of edges in the mesh. For eg: given faces = [[0, 1, 2], [0, 1, 3]], then for directed_edges = False, one valid output is [[0, 1], [0, 2], [0, 3], [1, 2], [3, 1]] for directed_edges = True, one valid output is [[0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [3, 0], [3, 1]] Raises: ValueError: If `faces` is not a numpy.ndarray or if its shape is not supported. """ if not isinstance(faces, np.ndarray): raise ValueError("'faces' must be a numpy.ndarray.") faces_shape = faces.shape faces_rank = len(faces_shape) if faces_rank != 2: raise ValueError( "'faces' must have a rank equal to 2, but it has rank {} and shape {}." .format(faces_rank, faces_shape)) if faces_shape[1] != 3: raise ValueError( "'faces' must have exactly 3 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(faces_shape[1], faces_shape)) edges = np.concatenate([faces[:, 0:2], faces[:, 1:3], faces[:, [2, 0]]], axis=0) if directed_edges: edges = np.concatenate([edges, np.flip(edges, axis=-1)]) unique_edges = np.unique(edges, axis=0) return unique_edges def get_degree_based_edge_weights(edges, dtype=np.float32): r"""Computes vertex degree based weights for edges of a mesh. The degree (valence) of a vertex is number of edges incident on the vertex. The weight for an edge $w_{ij}$ connecting vertex $v_i$ and vertex $v_j$ is defined as, $$ w_{ij} = 1.0 / degree(v_i) \sum_{j} w_{ij} = 1 $$ Args: edges: A numpy.ndarray of shape [E, 2], where E is the number of directed edges in the mesh. dtype: A numpy float data type. The output weights are of data type dtype. Returns: weights: A dtype numpy.ndarray of shape [E,] denoting edge weights. Raises: ValueError: If `edges` is not a numpy.ndarray or if its shape is not supported, or dtype is not a float type. """ if not isinstance(dtype(1), np.floating): raise ValueError("'dtype' must be a numpy float type.") if not isinstance(edges, np.ndarray): raise ValueError("'edges' must be a numpy.ndarray.") edges_shape = edges.shape edges_rank = len(edges_shape) if edges_rank != 2: raise ValueError( "'edges' must have a rank equal to 2, but it has rank {} and shape {}." .format(edges_rank, edges_shape)) if edges_shape[1] != 2: raise ValueError( "'edges' must have exactly 2 dimensions in the last axis, but it has {}" " dimensions and is of shape {}.".format(edges_shape[1], edges_shape)) degree = np.bincount(edges[:, 0]) rep_degree = degree[edges[:, 0]] weights = 1.0 / rep_degree.astype(dtype) return weights # API contains all public functions and classes. __all__ = []
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/nasa/eval.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reconstruction Evaluation.""" from os import path import numpy as np import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.nasa.lib import datasets from tensorflow_graphics.projects.nasa.lib import models from tensorflow_graphics.projects.nasa.lib import utils tf.disable_eager_execution() flags = tf.app.flags logging = tf.logging tf.logging.set_verbosity(tf.logging.INFO) utils.define_flags() FLAGS = flags.FLAGS def build_eval_graph(input_fn, model_fn, hparams): """Build the evaluation computation graph.""" dataset = input_fn(None) batch = dataset.make_one_shot_iterator().get_next() batch_holder = { "transform": tf.placeholder( tf.float32, [1, 1, hparams.n_parts, hparams.n_dims + 1, hparams.n_dims + 1]), "joint": tf.placeholder(tf.float32, [1, 1, hparams.n_parts, hparams.n_dims]), "point": tf.placeholder(tf.float32, [1, 1, None, hparams.n_dims]), "label": tf.placeholder(tf.float32, [1, 1, None, 1]), } latent_holder, latent, occ = model_fn(batch_holder, None, None, "gen_mesh") # Eval Summary iou_holder = tf.placeholder(tf.float32, []) best_holder = tf.placeholder(tf.float32, []) tf.summary.scalar("IoU", iou_holder) tf.summary.scalar("Best_IoU", best_holder) return { "batch_holder": batch_holder, "latent_holder": latent_holder, "latent": latent, "occ": occ, "batch": batch, "iou_holder": iou_holder, "best_holder": best_holder, "merged_summary": tf.summary.merge_all(), } def evaluate(hook_dict, ckpt, saver, best_iou, hparams): """Evaluate a checkpoint on the whole test set.""" batch = hook_dict["batch"] merged_summary = hook_dict["merged_summary"] iou_holder = hook_dict["iou_holder"] best_holder = hook_dict["best_holder"] batch_holder = hook_dict["batch_holder"] latent_holder = hook_dict["latent_holder"] latent = hook_dict["latent"] occ = hook_dict["occ"] global_step = utils.parse_global_step(ckpt) assignment_map = { "shape/": "shape/", } tf.train.init_from_checkpoint(ckpt, assignment_map) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) accum_iou = 0. example_cnt = 0 while True: try: batch_val = sess.run(batch) feed_dict = { batch_holder["transform"]: batch_val["transform"], batch_holder["joint"]: batch_val["joint"], } iou = utils.compute_iou(sess, feed_dict, latent_holder, batch_holder["point"], latent, occ[:, -1:], batch_val["points"], batch_val["labels"], hparams) accum_iou += iou example_cnt += 1 if hparams.gen_mesh_only > 0: # Generate meshes for evaluation unused_var = utils.save_mesh( sess, feed_dict, latent_holder, batch_holder["point"], latent, occ, batch_val, hparams, ) logging.info("Generated mesh No.{}".format(example_cnt)) except tf.errors.OutOfRangeError: accum_iou /= example_cnt if best_iou < accum_iou: best_iou = accum_iou saver.save(sess, path.join(hparams.train_dir, "best", "model.ckpt"), global_step) summary = sess.run( merged_summary, utils.make_summary_feed_dict( iou_holder, accum_iou, best_holder, best_iou, )) # If only generating meshes for the sequence, we can determinate the # evaluation after the first full loop over the test set. if hparams.gen_mesh_only: exit(0) break return summary, global_step def main(unused_argv): tf.random.set_random_seed(20200823) np.random.seed(20200823) input_fn = datasets.get_dataset("test", FLAGS) model_fn = models.get_model(FLAGS) best_iou = 0. with tf.summary.FileWriter(path.join(FLAGS.train_dir, "eval")) as eval_writer: hook_dict = build_eval_graph(input_fn, model_fn, FLAGS) saver = tf.train.Saver() for ckpt in tf.train.checkpoints_iterator(FLAGS.train_dir, timeout=1800): summary, global_step = evaluate(hook_dict, ckpt, saver, best_iou, FLAGS) eval_writer.add_summary(summary, global_step) eval_writer.flush() if __name__ == "__main__": tf.app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Reconstruction Evaluation.""" from os import path import numpy as np import tensorflow.compat.v1 as tf from tensorflow_graphics.projects.nasa.lib import datasets from tensorflow_graphics.projects.nasa.lib import models from tensorflow_graphics.projects.nasa.lib import utils tf.disable_eager_execution() flags = tf.app.flags logging = tf.logging tf.logging.set_verbosity(tf.logging.INFO) utils.define_flags() FLAGS = flags.FLAGS def build_eval_graph(input_fn, model_fn, hparams): """Build the evaluation computation graph.""" dataset = input_fn(None) batch = dataset.make_one_shot_iterator().get_next() batch_holder = { "transform": tf.placeholder( tf.float32, [1, 1, hparams.n_parts, hparams.n_dims + 1, hparams.n_dims + 1]), "joint": tf.placeholder(tf.float32, [1, 1, hparams.n_parts, hparams.n_dims]), "point": tf.placeholder(tf.float32, [1, 1, None, hparams.n_dims]), "label": tf.placeholder(tf.float32, [1, 1, None, 1]), } latent_holder, latent, occ = model_fn(batch_holder, None, None, "gen_mesh") # Eval Summary iou_holder = tf.placeholder(tf.float32, []) best_holder = tf.placeholder(tf.float32, []) tf.summary.scalar("IoU", iou_holder) tf.summary.scalar("Best_IoU", best_holder) return { "batch_holder": batch_holder, "latent_holder": latent_holder, "latent": latent, "occ": occ, "batch": batch, "iou_holder": iou_holder, "best_holder": best_holder, "merged_summary": tf.summary.merge_all(), } def evaluate(hook_dict, ckpt, saver, best_iou, hparams): """Evaluate a checkpoint on the whole test set.""" batch = hook_dict["batch"] merged_summary = hook_dict["merged_summary"] iou_holder = hook_dict["iou_holder"] best_holder = hook_dict["best_holder"] batch_holder = hook_dict["batch_holder"] latent_holder = hook_dict["latent_holder"] latent = hook_dict["latent"] occ = hook_dict["occ"] global_step = utils.parse_global_step(ckpt) assignment_map = { "shape/": "shape/", } tf.train.init_from_checkpoint(ckpt, assignment_map) init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) accum_iou = 0. example_cnt = 0 while True: try: batch_val = sess.run(batch) feed_dict = { batch_holder["transform"]: batch_val["transform"], batch_holder["joint"]: batch_val["joint"], } iou = utils.compute_iou(sess, feed_dict, latent_holder, batch_holder["point"], latent, occ[:, -1:], batch_val["points"], batch_val["labels"], hparams) accum_iou += iou example_cnt += 1 if hparams.gen_mesh_only > 0: # Generate meshes for evaluation unused_var = utils.save_mesh( sess, feed_dict, latent_holder, batch_holder["point"], latent, occ, batch_val, hparams, ) logging.info("Generated mesh No.{}".format(example_cnt)) except tf.errors.OutOfRangeError: accum_iou /= example_cnt if best_iou < accum_iou: best_iou = accum_iou saver.save(sess, path.join(hparams.train_dir, "best", "model.ckpt"), global_step) summary = sess.run( merged_summary, utils.make_summary_feed_dict( iou_holder, accum_iou, best_holder, best_iou, )) # If only generating meshes for the sequence, we can determinate the # evaluation after the first full loop over the test set. if hparams.gen_mesh_only: exit(0) break return summary, global_step def main(unused_argv): tf.random.set_random_seed(20200823) np.random.seed(20200823) input_fn = datasets.get_dataset("test", FLAGS) model_fn = models.get_model(FLAGS) best_iou = 0. with tf.summary.FileWriter(path.join(FLAGS.train_dir, "eval")) as eval_writer: hook_dict = build_eval_graph(input_fn, model_fn, FLAGS) saver = tf.train.Saver() for ckpt in tf.train.checkpoints_iterator(FLAGS.train_dir, timeout=1800): summary, global_step = evaluate(hook_dict, ckpt, saver, best_iou, FLAGS) eval_writer.add_summary(summary, global_step) eval_writer.flush() if __name__ == "__main__": tf.app.run(main)
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/math/optimizer/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/util/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Util module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape from tensorflow_graphics.util import test_case from tensorflow_graphics.util import tfg_flags # pylint: enable=g-import-not-at-top # The util modules are not exported. __all__ = []
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Util module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape from tensorflow_graphics.util import test_case from tensorflow_graphics.util import tfg_flags # pylint: enable=g-import-not-at-top # The util modules are not exported. __all__ = []
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/reflectance/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/axis_angle.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements axis-angle functionalities. The axis-angle representation is defined as $$\theta\mathbf{a}$$, where $$\mathbf{a}$$ is a unit vector indicating the direction of rotation and $$\theta$$ is a scalar controlling the angle of rotation. It is important to note that the axis-angle does not perform rotation by itself, but that it can be used to rotate any given vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}'$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ More details about the axis-angle formalism can be found on [this page.] (https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation) Note: Some of the functions defined in the module expect a normalized axis $$\mathbf{a} = [x, y, z]^T$$ as inputs where $$x^2 + y^2 + z^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion as quaternion_lib from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_euler(angles, name="axis_angle_from_euler"): r"""Converts Euler angles to an axis-angle representation. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler(angles) return from_quaternion(quaternion) def from_euler_with_small_angles_approximation( angles, name="axis_angle_from_euler_with_small_angles_approximation"): r"""Converts small Euler angles to an axis-angle representation. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler_with_small_angles_approximation". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler_with_small_angles_approximation( angles) return from_quaternion(quaternion) def from_quaternion(quaternion, name="axis_angle_from_quaternion"): """Converts a quaternion to an axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "axis_angle_from_quaternion". Returns: Tuple of two tensors of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) # This prevents zero norm xyz and zero w, and is differentiable. quaternion += asserts.select_eps_for_addition(quaternion.dtype) xyz, w = tf.split(quaternion, (3, 1), axis=-1) norm = tf.norm(tensor=xyz, axis=-1, keepdims=True) angle = 2.0 * tf.atan2(norm, tf.abs(w)) axis = safe_ops.safe_unsigned_div(safe_ops.nonzero_sign(w) * xyz, norm) return axis, angle def from_rotation_matrix(rotation_matrix, name="axis_angle_from_rotation_matrix"): """Converts a rotation matrix to an axis-angle representation. Note: In the current version the returned axis-angle representation is not unique for a given rotation matrix. Since a direct conversion would not really be faster, we first transform the rotation matrix to a quaternion, and finally perform the conversion from that quaternion to the corresponding axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "axis_angle_from_rotation_matrix". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) quaternion = quaternion_lib.from_rotation_matrix(rotation_matrix) return from_quaternion(quaternion) def inverse(axis, angle, name="axis_angle_inverse"): """Computes the axis-angle that is the inverse of the input axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_inverse". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) return axis, -angle def is_normalized(axis, angle, atol=1e-3, name="axis_angle_is_normalized"): """Determines if the axis-angle is normalized or not. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. atol: The absolute tolerance parameter. name: A name for this op that defaults to "axis_angle_is_normalized". Returns: A tensor of shape `[A1, ..., An, 1]`, where False indicates that the axis is not normalized. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) norms = tf.norm(tensor=axis, axis=-1, keepdims=True) return tf.abs(norms - 1.) < atol def rotate(point, axis, angle, name="axis_angle_rotate"): r"""Rotates a 3d point using an axis-angle by applying the Rodrigues' formula. Rotates a vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}' \in {\mathbb{R}^3}$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point to rotate. axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If `point`, `axis`, or `angle` are of different shape or if their respective shape is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(point, axis, angle), tensor_names=("point", "axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) cos_angle = tf.cos(angle) axis_dot_point = vector.dot(axis, point) return point * cos_angle + vector.cross( axis, point) * tf.sin(angle) + axis * axis_dot_point * (1.0 - cos_angle) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r"""This module implements axis-angle functionalities. The axis-angle representation is defined as $$\theta\mathbf{a}$$, where $$\mathbf{a}$$ is a unit vector indicating the direction of rotation and $$\theta$$ is a scalar controlling the angle of rotation. It is important to note that the axis-angle does not perform rotation by itself, but that it can be used to rotate any given vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}'$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ More details about the axis-angle formalism can be found on [this page.] (https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation) Note: Some of the functions defined in the module expect a normalized axis $$\mathbf{a} = [x, y, z]^T$$ as inputs where $$x^2 + y^2 + z^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import quaternion as quaternion_lib from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def from_euler(angles, name="axis_angle_from_euler"): r"""Converts Euler angles to an axis-angle representation. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler(angles) return from_quaternion(quaternion) def from_euler_with_small_angles_approximation( angles, name="axis_angle_from_euler_with_small_angles_approximation"): r"""Converts small Euler angles to an axis-angle representation. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: The conversion is performed by first converting to a quaternion representation, and then by converting the quaternion to an axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "axis_angle_from_euler_with_small_angles_approximation". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. """ with tf.name_scope(name): quaternion = quaternion_lib.from_euler_with_small_angles_approximation( angles) return from_quaternion(quaternion) def from_quaternion(quaternion, name="axis_angle_from_quaternion"): """Converts a quaternion to an axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "axis_angle_from_quaternion". Returns: Tuple of two tensors of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) # This prevents zero norm xyz and zero w, and is differentiable. quaternion += asserts.select_eps_for_addition(quaternion.dtype) xyz, w = tf.split(quaternion, (3, 1), axis=-1) norm = tf.norm(tensor=xyz, axis=-1, keepdims=True) angle = 2.0 * tf.atan2(norm, tf.abs(w)) axis = safe_ops.safe_unsigned_div(safe_ops.nonzero_sign(w) * xyz, norm) return axis, angle def from_rotation_matrix(rotation_matrix, name="axis_angle_from_rotation_matrix"): """Converts a rotation matrix to an axis-angle representation. Note: In the current version the returned axis-angle representation is not unique for a given rotation matrix. Since a direct conversion would not really be faster, we first transform the rotation matrix to a quaternion, and finally perform the conversion from that quaternion to the corresponding axis-angle representation. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "axis_angle_from_rotation_matrix". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) quaternion = quaternion_lib.from_rotation_matrix(rotation_matrix) return from_quaternion(quaternion) def inverse(axis, angle, name="axis_angle_inverse"): """Computes the axis-angle that is the inverse of the input axis-angle. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_inverse". Returns: A tuple of two tensors, respectively of shape `[A1, ..., An, 3]` and `[A1, ..., An, 1]`, where the first tensor represents the axis, and the second represents the angle. The resulting axis is a normalized vector. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) return axis, -angle def is_normalized(axis, angle, atol=1e-3, name="axis_angle_is_normalized"): """Determines if the axis-angle is normalized or not. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents an angle. atol: The absolute tolerance parameter. name: A name for this op that defaults to "axis_angle_is_normalized". Returns: A tensor of shape `[A1, ..., An, 1]`, where False indicates that the axis is not normalized. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) norms = tf.norm(tensor=axis, axis=-1, keepdims=True) return tf.abs(norms - 1.) < atol def rotate(point, axis, angle, name="axis_angle_rotate"): r"""Rotates a 3d point using an axis-angle by applying the Rodrigues' formula. Rotates a vector $$\mathbf{v} \in {\mathbb{R}^3}$$ into a vector $$\mathbf{v}' \in {\mathbb{R}^3}$$ using the Rodrigues' rotation formula: $$\mathbf{v}'=\mathbf{v}\cos(\theta)+(\mathbf{a}\times\mathbf{v})\sin(\theta) +\mathbf{a}(\mathbf{a}\cdot\mathbf{v})(1-\cos(\theta)).$$ Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point to rotate. axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "axis_angle_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If `point`, `axis`, or `angle` are of different shape or if their respective shape is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(point, axis, angle), tensor_names=("point", "axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) cos_angle = tf.cos(angle) axis_dot_point = vector.dot(axis, point) return point * cos_angle + vector.cross( axis, point) * tf.sin(angle) + axis * axis_dot_point * (1.0 - cos_angle) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Datasets module.""" # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.datasets import features from tensorflow_graphics.datasets import modelnet40 from tensorflow_graphics.datasets import shapenet from tensorflow_graphics.datasets import pix3d from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.image. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Datasets module.""" # pylint: disable=g-import-not-at-top from tensorflow_graphics.util.doc import _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.datasets import features from tensorflow_graphics.datasets import modelnet40 from tensorflow_graphics.datasets import shapenet from tensorflow_graphics.datasets import pix3d from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.image. __all__ = _export_api.get_modules() # pylint: enable=g-import-not-at-top
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/tests/rotation_matrix_3d_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for 3d rotation matrix.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class RotationMatrix3dTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_assert_rotation_matrix_normalized_passthrough(self): """Checks that the assert is a passthrough when the flag is False.""" angles = test_helpers.generate_preset_test_euler_angles() matrix_input = rotation_matrix_3d.from_euler(angles) matrix_output = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_input) self.assertTrue(matrix_input is matrix_output) # pylint: disable=g-generic-assert @parameterized.parameters((np.float32), (np.float64)) def test_assert_rotation_matrix_normalized_preset(self, dtype): """Checks that assert_normalized function works as expected.""" angles = test_helpers.generate_preset_test_euler_angles().astype(dtype) matrix = rotation_matrix_3d.from_euler(angles) matrix_rescaled = matrix * 1.01 matrix_normalized = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix) self.evaluate(matrix_normalized) with self.assertRaises(tf.errors.InvalidArgumentError): # pylint: disable=g-error-prone-assert-raises self.evaluate(rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_rescaled)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_assert_rotation_matrix_normalized_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_assert_rotation_matrix_normalized_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, error_msg, shapes) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((1, 3), (1, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_axis_angle, error_msg, shapes) def test_from_axis_angle_normalized_preset(self): """Tests that axis-angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) matrix_axis_angle = rotation_matrix_3d.from_axis_angle(axis, angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_axis_angle_normalized_random(self): """Tests that axis-angles can be converted to rotation matrices.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_45), (td.MAT_3D_X_45,)), ((td.AXIS_3D_Y, td.ANGLE_45), (td.MAT_3D_Y_45,)), ((td.AXIS_3D_Z, td.ANGLE_45), (td.MAT_3D_Z_45,)), ((td.AXIS_3D_X, td.ANGLE_90), (td.MAT_3D_X_90,)), ((td.AXIS_3D_Y, td.ANGLE_90), (td.MAT_3D_Y_90,)), ((td.AXIS_3D_Z, td.ANGLE_90), (td.MAT_3D_Z_90,)), ((td.AXIS_3D_X, td.ANGLE_180), (td.MAT_3D_X_180,)), ((td.AXIS_3D_Y, td.ANGLE_180), (td.MAT_3D_Y_180,)), ((td.AXIS_3D_Z, td.ANGLE_180), (td.MAT_3D_Z_180,)), ) def test_from_axis_angle_preset(self, test_inputs, test_outputs): """Tests that an axis-angle maps to correct matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_axis_angle, test_inputs, test_outputs) def test_from_axis_angle_random(self): """Tests conversion to matrix.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) matrix_quaternion = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllClose(matrix_axis_angle, matrix_quaternion, rtol=1e-3) # Checks that resulting rotation matrices are normalized. self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((td.AXIS_3D_X, -td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, -td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Z, -td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_from_axis_angle_rotate_vector_preset(self, test_inputs, test_outputs): """Tests the directionality of axis-angle rotations.""" def func(axis, angle, point): matrix = rotation_matrix_3d.from_axis_angle(axis, angle) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) def test_from_euler_normalized_preset(self): """Tests that euler angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_euler_normalized_random(self): """Tests that euler angles can be converted to rotation matrices.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(random_euler_angles.shape[0:-1] + (1,))) @parameterized.parameters( ((td.AXIS_3D_0,), (td.MAT_3D_ID,)), ((td.ANGLE_45 * td.AXIS_3D_X,), (td.MAT_3D_X_45,)), ((td.ANGLE_45 * td.AXIS_3D_Y,), (td.MAT_3D_Y_45,)), ((td.ANGLE_45 * td.AXIS_3D_Z,), (td.MAT_3D_Z_45,)), ((td.ANGLE_90 * td.AXIS_3D_X,), (td.MAT_3D_X_90,)), ((td.ANGLE_90 * td.AXIS_3D_Y,), (td.MAT_3D_Y_90,)), ((td.ANGLE_90 * td.AXIS_3D_Z,), (td.MAT_3D_Z_90,)), ((td.ANGLE_180 * td.AXIS_3D_X,), (td.MAT_3D_X_180,)), ((td.ANGLE_180 * td.AXIS_3D_Y,), (td.MAT_3D_Y_180,)), ((td.ANGLE_180 * td.AXIS_3D_Z,), (td.MAT_3D_Z_180,)), ) def test_from_euler_preset(self, test_inputs, test_outputs): """Tests that Euler angles create the expected matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_euler, test_inputs, test_outputs) def test_from_euler_random(self): """Tests that Euler angles produce the same result as axis-angle.""" angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(angles) tensor_tile = angles.shape[:-1] x_axis = np.tile(td.AXIS_3D_X, tensor_tile + (1,)) y_axis = np.tile(td.AXIS_3D_Y, tensor_tile + (1,)) z_axis = np.tile(td.AXIS_3D_Z, tensor_tile + (1,)) x_angle = np.expand_dims(angles[..., 0], axis=-1) y_angle = np.expand_dims(angles[..., 1], axis=-1) z_angle = np.expand_dims(angles[..., 2], axis=-1) x_rotation = rotation_matrix_3d.from_axis_angle(x_axis, x_angle) y_rotation = rotation_matrix_3d.from_axis_angle(y_axis, y_angle) z_rotation = rotation_matrix_3d.from_axis_angle(z_axis, z_angle) expected_matrix = tf.matmul(z_rotation, tf.matmul(y_rotation, x_rotation)) self.assertAllClose(expected_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_with_small_angles_approximation_jacobian_random(self): """Test the Jacobian of from_euler_with_small_angles_approximation.""" x_init = test_helpers.generate_random_test_euler_angles( min_angle=-0.17, max_angle=0.17) self.assert_jacobian_is_correct_fn( rotation_matrix_3d.from_euler_with_small_angles_approximation, [x_init]) def test_from_euler_with_small_angles_approximation_random(self): """Tests small_angles approximation by comparing to exact calculation.""" # Only generate small angles. For a test tolerance of 1e-3, 0.16 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.16, max_angle=0.16) exact_matrix = rotation_matrix_3d.from_euler(random_euler_angles) approximate_matrix = ( rotation_matrix_3d.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_matrix, approximate_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_quaternion, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_quaternion, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that quaternions can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) matrix_quat = rotation_matrix_3d.from_quaternion(quat) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_quat), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_quaternion_normalized_random(self): """Tests that random quaternions can be converted to rotation matrices.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_matrix = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllEqual( rotation_matrix_3d.is_valid(random_matrix), np.ones(tensor_shape + (1,))) def test_from_quaternion_preset(self): """Tests that a quaternion maps to correct matrix.""" preset_quaternions = test_helpers.generate_preset_test_quaternions() preset_matrices = test_helpers.generate_preset_test_rotation_matrices_3d() self.assertAllClose(preset_matrices, rotation_matrix_3d.from_quaternion(preset_quaternions)) def test_from_quaternion_random(self): """Tests conversion to matrix.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_rotation_matrices = rotation_matrix_3d.from_euler( random_euler_angles) self.assertAllClose(random_rotation_matrices, rotation_matrix_3d.from_quaternion(random_quaternions)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_inverse_exception_not_raised(self, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_not_raised(rotation_matrix_3d.inverse, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_inverse_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.inverse, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) def test_inverse_normalized_random(self): """Checks that inverted rotation matrices are valid rotations.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) self.assertAllEqual( rotation_matrix_3d.is_valid(predicted_invert_random_matrix), np.ones(tensor_tile + (1,))) def test_inverse_random(self): """Checks that inverting rotated points results in no transformation.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_point = np.random.normal(size=tensor_tile + (3,)) rotated_random_points = rotation_matrix_3d.rotate(random_point, random_matrix) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) predicted_invert_rotated_random_points = rotation_matrix_3d.rotate( rotated_random_points, predicted_invert_random_matrix) self.assertAllClose( random_point, predicted_invert_rotated_random_points, rtol=1e-6) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_is_valid_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.is_valid, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_3d.is_valid, error_msg, shape) def test_is_valid_random(self): """Tests that is_valid works as intended.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] rotation_matrix = rotation_matrix_3d.from_euler(random_euler_angle) pred_normalized = rotation_matrix_3d.is_valid(rotation_matrix) with self.subTest(name="all_normalized"): self.assertAllEqual(pred_normalized, np.ones(shape=tensor_tile + (1,), dtype=bool)) with self.subTest(name="non_orthonormal"): test_matrix = np.array([[2., 0., 0.], [0., 0.5, 0], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) with self.subTest(name="negative_orthonormal"): test_matrix = np.array([[1., 0., 0.], [0., -1., 0.], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) @parameterized.parameters( ((3,), (3, 3)), ((None, 3), (None, 3, 3)), ((1, 3), (1, 3, 3)), ((2, 3), (2, 3, 3)), ((3,), (1, 3, 3)), ((1, 3), (3, 3)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (3, 3)), ("must have a rank greater than 1", (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3, None)), ("must have exactly 3 dimensions in axis -2", (3,), (None, 3)), ) def test_rotate_exception_raised(self, error_msg, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_raised(rotation_matrix_3d.rotate, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_rotation_matrices_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_rotation_matrix_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @parameterized.parameters( ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((-td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_rotate_vector_preset(self, test_inputs, test_outputs): """Tests that the rotate function produces the expected results.""" def func(angles, point): matrix = rotation_matrix_3d.from_euler(angles) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) def test_rotate_vs_rotate_quaternion_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_quaternion = quaternion.from_rotation_matrix(random_matrix) random_point = np.random.normal(size=tensor_tile + (3,)) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = rotation_matrix_3d.rotate(random_point, random_matrix) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for 3d rotation matrix.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.transformation import axis_angle from tensorflow_graphics.geometry.transformation import quaternion from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.geometry.transformation.tests import test_data as td from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class RotationMatrix3dTest(test_case.TestCase): @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_assert_rotation_matrix_normalized_passthrough(self): """Checks that the assert is a passthrough when the flag is False.""" angles = test_helpers.generate_preset_test_euler_angles() matrix_input = rotation_matrix_3d.from_euler(angles) matrix_output = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_input) self.assertTrue(matrix_input is matrix_output) # pylint: disable=g-generic-assert @parameterized.parameters((np.float32), (np.float64)) def test_assert_rotation_matrix_normalized_preset(self, dtype): """Checks that assert_normalized function works as expected.""" angles = test_helpers.generate_preset_test_euler_angles().astype(dtype) matrix = rotation_matrix_3d.from_euler(angles) matrix_rescaled = matrix * 1.01 matrix_normalized = rotation_matrix_3d.assert_rotation_matrix_normalized( matrix) self.evaluate(matrix_normalized) with self.assertRaises(tf.errors.InvalidArgumentError): # pylint: disable=g-error-prone-assert-raises self.evaluate(rotation_matrix_3d.assert_rotation_matrix_normalized( matrix_rescaled)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ) def test_assert_rotation_matrix_normalized_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_assert_rotation_matrix_normalized_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised( rotation_matrix_3d.assert_rotation_matrix_normalized, error_msg, shapes) @parameterized.parameters( ((3,), (1,)), ((None, 3), (None, 1)), ((1, 3), (1, 1)), ((2, 3), (2, 1)), ((1, 3), (1,)), ((3,), (1, 1)), ) def test_from_axis_angle_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_axis_angle, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (1,)), ("must have exactly 1 dimensions in axis -1", (3,), (None,)), ) def test_from_axis_angle_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_axis_angle, error_msg, shapes) def test_from_axis_angle_normalized_preset(self): """Tests that axis-angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() axis, angle = axis_angle.from_euler(euler_angles) matrix_axis_angle = rotation_matrix_3d.from_axis_angle(axis, angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_axis_angle_normalized_random(self): """Tests that axis-angles can be converted to rotation matrices.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_45), (td.MAT_3D_X_45,)), ((td.AXIS_3D_Y, td.ANGLE_45), (td.MAT_3D_Y_45,)), ((td.AXIS_3D_Z, td.ANGLE_45), (td.MAT_3D_Z_45,)), ((td.AXIS_3D_X, td.ANGLE_90), (td.MAT_3D_X_90,)), ((td.AXIS_3D_Y, td.ANGLE_90), (td.MAT_3D_Y_90,)), ((td.AXIS_3D_Z, td.ANGLE_90), (td.MAT_3D_Z_90,)), ((td.AXIS_3D_X, td.ANGLE_180), (td.MAT_3D_X_180,)), ((td.AXIS_3D_Y, td.ANGLE_180), (td.MAT_3D_Y_180,)), ((td.AXIS_3D_Z, td.ANGLE_180), (td.MAT_3D_Z_180,)), ) def test_from_axis_angle_preset(self, test_inputs, test_outputs): """Tests that an axis-angle maps to correct matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_axis_angle, test_inputs, test_outputs) def test_from_axis_angle_random(self): """Tests conversion to matrix.""" tensor_shape = np.random.randint(1, 10, size=np.random.randint(3)).tolist() random_axis = np.random.normal(size=tensor_shape + [3]) random_axis /= np.linalg.norm(random_axis, axis=-1, keepdims=True) random_angle = np.random.normal(size=tensor_shape + [1]) matrix_axis_angle = rotation_matrix_3d.from_axis_angle( random_axis, random_angle) random_quaternion = quaternion.from_axis_angle(random_axis, random_angle) matrix_quaternion = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllClose(matrix_axis_angle, matrix_quaternion, rtol=1e-3) # Checks that resulting rotation matrices are normalized. self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_axis_angle), np.ones(tensor_shape + [1])) @parameterized.parameters( ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.AXIS_3D_X, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((td.AXIS_3D_X, -td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, -td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Y, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((td.AXIS_3D_Z, -td.ANGLE_90, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.AXIS_3D_Z, td.ANGLE_90, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_from_axis_angle_rotate_vector_preset(self, test_inputs, test_outputs): """Tests the directionality of axis-angle rotations.""" def func(axis, angle, point): matrix = rotation_matrix_3d.from_axis_angle(axis, angle) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) @parameterized.parameters( ((3,),), ((None, 3),), ((2, 3),), ) def test_from_euler_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_euler, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_euler, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_preset(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_preset_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_jacobian_random(self): """Test the Jacobian of the from_euler function.""" x_init = test_helpers.generate_random_test_euler_angles() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_euler, [x_init]) def test_from_euler_normalized_preset(self): """Tests that euler angles can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() matrix = rotation_matrix_3d.from_euler(euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_euler_normalized_random(self): """Tests that euler angles can be converted to rotation matrices.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(random_euler_angles) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix), np.ones(random_euler_angles.shape[0:-1] + (1,))) @parameterized.parameters( ((td.AXIS_3D_0,), (td.MAT_3D_ID,)), ((td.ANGLE_45 * td.AXIS_3D_X,), (td.MAT_3D_X_45,)), ((td.ANGLE_45 * td.AXIS_3D_Y,), (td.MAT_3D_Y_45,)), ((td.ANGLE_45 * td.AXIS_3D_Z,), (td.MAT_3D_Z_45,)), ((td.ANGLE_90 * td.AXIS_3D_X,), (td.MAT_3D_X_90,)), ((td.ANGLE_90 * td.AXIS_3D_Y,), (td.MAT_3D_Y_90,)), ((td.ANGLE_90 * td.AXIS_3D_Z,), (td.MAT_3D_Z_90,)), ((td.ANGLE_180 * td.AXIS_3D_X,), (td.MAT_3D_X_180,)), ((td.ANGLE_180 * td.AXIS_3D_Y,), (td.MAT_3D_Y_180,)), ((td.ANGLE_180 * td.AXIS_3D_Z,), (td.MAT_3D_Z_180,)), ) def test_from_euler_preset(self, test_inputs, test_outputs): """Tests that Euler angles create the expected matrix.""" self.assert_output_is_correct(rotation_matrix_3d.from_euler, test_inputs, test_outputs) def test_from_euler_random(self): """Tests that Euler angles produce the same result as axis-angle.""" angles = test_helpers.generate_random_test_euler_angles() matrix = rotation_matrix_3d.from_euler(angles) tensor_tile = angles.shape[:-1] x_axis = np.tile(td.AXIS_3D_X, tensor_tile + (1,)) y_axis = np.tile(td.AXIS_3D_Y, tensor_tile + (1,)) z_axis = np.tile(td.AXIS_3D_Z, tensor_tile + (1,)) x_angle = np.expand_dims(angles[..., 0], axis=-1) y_angle = np.expand_dims(angles[..., 1], axis=-1) z_angle = np.expand_dims(angles[..., 2], axis=-1) x_rotation = rotation_matrix_3d.from_axis_angle(x_axis, x_angle) y_rotation = rotation_matrix_3d.from_axis_angle(y_axis, y_angle) z_rotation = rotation_matrix_3d.from_axis_angle(z_axis, z_angle) expected_matrix = tf.matmul(z_rotation, tf.matmul(y_rotation, x_rotation)) self.assertAllClose(expected_matrix, matrix, rtol=1e-3) @parameterized.parameters( ((3,),), ((None, 3),), ) def test_from_euler_with_small_angles_approximation_exception_not_raised( self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,)),) def test_from_euler_with_small_angles_approximation_exception_raised( self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised( rotation_matrix_3d.from_euler_with_small_angles_approximation, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_euler_with_small_angles_approximation_jacobian_random(self): """Test the Jacobian of from_euler_with_small_angles_approximation.""" x_init = test_helpers.generate_random_test_euler_angles( min_angle=-0.17, max_angle=0.17) self.assert_jacobian_is_correct_fn( rotation_matrix_3d.from_euler_with_small_angles_approximation, [x_init]) def test_from_euler_with_small_angles_approximation_random(self): """Tests small_angles approximation by comparing to exact calculation.""" # Only generate small angles. For a test tolerance of 1e-3, 0.16 was found # empirically to be the range where the small angle approximation works. random_euler_angles = test_helpers.generate_random_test_euler_angles( min_angle=-0.16, max_angle=0.16) exact_matrix = rotation_matrix_3d.from_euler(random_euler_angles) approximate_matrix = ( rotation_matrix_3d.from_euler_with_small_angles_approximation( random_euler_angles)) self.assertAllClose(exact_matrix, approximate_matrix, atol=1e-3) @parameterized.parameters( ((4,),), ((None, 4),), ) def test_from_quaternion_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.from_quaternion, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (None,)),) def test_from_quaternion_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.from_quaternion, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_preset(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_preset_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_from_quaternion_jacobian_random(self): """Test the Jacobian of the from_quaternion function.""" x_init = test_helpers.generate_random_test_quaternions() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.from_quaternion, [x_init]) def test_from_quaternion_normalized_preset(self): """Tests that quaternions can be converted to rotation matrices.""" euler_angles = test_helpers.generate_preset_test_euler_angles() quat = quaternion.from_euler(euler_angles) matrix_quat = rotation_matrix_3d.from_quaternion(quat) self.assertAllEqual( rotation_matrix_3d.is_valid(matrix_quat), np.ones(euler_angles.shape[0:-1] + (1,))) def test_from_quaternion_normalized_random(self): """Tests that random quaternions can be converted to rotation matrices.""" random_quaternion = test_helpers.generate_random_test_quaternions() tensor_shape = random_quaternion.shape[:-1] random_matrix = rotation_matrix_3d.from_quaternion(random_quaternion) self.assertAllEqual( rotation_matrix_3d.is_valid(random_matrix), np.ones(tensor_shape + (1,))) def test_from_quaternion_preset(self): """Tests that a quaternion maps to correct matrix.""" preset_quaternions = test_helpers.generate_preset_test_quaternions() preset_matrices = test_helpers.generate_preset_test_rotation_matrices_3d() self.assertAllClose(preset_matrices, rotation_matrix_3d.from_quaternion(preset_quaternions)) def test_from_quaternion_random(self): """Tests conversion to matrix.""" random_euler_angles = test_helpers.generate_random_test_euler_angles() random_quaternions = quaternion.from_euler(random_euler_angles) random_rotation_matrices = rotation_matrix_3d.from_euler( random_euler_angles) self.assertAllClose(random_rotation_matrices, rotation_matrix_3d.from_quaternion(random_quaternions)) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_inverse_exception_not_raised(self, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_not_raised(rotation_matrix_3d.inverse, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_inverse_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(rotation_matrix_3d.inverse, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_preset(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_preset_test_rotation_matrices_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_inverse_jacobian_random(self): """Test the Jacobian of the inverse function.""" x_init = test_helpers.generate_random_test_rotation_matrix_3d() self.assert_jacobian_is_correct_fn(rotation_matrix_3d.inverse, [x_init]) def test_inverse_normalized_random(self): """Checks that inverted rotation matrices are valid rotations.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) self.assertAllEqual( rotation_matrix_3d.is_valid(predicted_invert_random_matrix), np.ones(tensor_tile + (1,))) def test_inverse_random(self): """Checks that inverting rotated points results in no transformation.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_point = np.random.normal(size=tensor_tile + (3,)) rotated_random_points = rotation_matrix_3d.rotate(random_point, random_matrix) predicted_invert_random_matrix = rotation_matrix_3d.inverse(random_matrix) predicted_invert_rotated_random_points = rotation_matrix_3d.rotate( rotated_random_points, predicted_invert_random_matrix) self.assertAllClose( random_point, predicted_invert_rotated_random_points, rtol=1e-6) @parameterized.parameters( ((3, 3),), ((None, 3, 3),), ((2, 3, 3),), ) def test_is_valid_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.is_valid, shapes) @parameterized.parameters( ("must have a rank greater than 1", (3,)), ("must have exactly 3 dimensions in axis -1", (3, None)), ("must have exactly 3 dimensions in axis -2", (None, 3)), ) def test_is_valid_exception_raised(self, error_msg, *shape): """Tests that the shape exceptions are raised.""" self.assert_exception_is_raised(rotation_matrix_3d.is_valid, error_msg, shape) def test_is_valid_random(self): """Tests that is_valid works as intended.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] rotation_matrix = rotation_matrix_3d.from_euler(random_euler_angle) pred_normalized = rotation_matrix_3d.is_valid(rotation_matrix) with self.subTest(name="all_normalized"): self.assertAllEqual(pred_normalized, np.ones(shape=tensor_tile + (1,), dtype=bool)) with self.subTest(name="non_orthonormal"): test_matrix = np.array([[2., 0., 0.], [0., 0.5, 0], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) with self.subTest(name="negative_orthonormal"): test_matrix = np.array([[1., 0., 0.], [0., -1., 0.], [0., 0., 1.]]) pred_normalized = rotation_matrix_3d.is_valid(test_matrix) self.assertAllEqual(pred_normalized, np.zeros(shape=(1,), dtype=bool)) @parameterized.parameters( ((3,), (3, 3)), ((None, 3), (None, 3, 3)), ((1, 3), (1, 3, 3)), ((2, 3), (2, 3, 3)), ((3,), (1, 3, 3)), ((1, 3), (3, 3)), ) def test_rotate_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(rotation_matrix_3d.rotate, shapes) @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (None,), (3, 3)), ("must have a rank greater than 1", (3,), (3,)), ("must have exactly 3 dimensions in axis -1", (3,), (3, None)), ("must have exactly 3 dimensions in axis -2", (3,), (None, 3)), ) def test_rotate_exception_raised(self, error_msg, *shapes): """Checks the inputs of the rotate function.""" self.assert_exception_is_raised(rotation_matrix_3d.rotate, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_preset(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_preset_test_rotation_matrices_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_rotate_jacobian_random(self): """Test the Jacobian of the rotate function.""" x_matrix_init = test_helpers.generate_random_test_rotation_matrix_3d() tensor_shape = x_matrix_init.shape[:-1] x_point_init = np.random.uniform(size=tensor_shape) self.assert_jacobian_is_correct_fn(rotation_matrix_3d.rotate, [x_point_init, x_matrix_init]) @parameterized.parameters( ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_X), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Y), (td.AXIS_3D_Z,)), ((-td.ANGLE_90 * td.AXIS_3D_X, td.AXIS_3D_Z), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_X), (td.AXIS_3D_Z,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Y), (td.AXIS_3D_Y,)), ((td.ANGLE_90 * td.AXIS_3D_Y, td.AXIS_3D_Z), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_X), (td.AXIS_3D_Y,)), ((-td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Y), (td.AXIS_3D_X,)), ((td.ANGLE_90 * td.AXIS_3D_Z, td.AXIS_3D_Z), (td.AXIS_3D_Z,)), ) def test_rotate_vector_preset(self, test_inputs, test_outputs): """Tests that the rotate function produces the expected results.""" def func(angles, point): matrix = rotation_matrix_3d.from_euler(angles) return rotation_matrix_3d.rotate(point, matrix) self.assert_output_is_correct(func, test_inputs, test_outputs) def test_rotate_vs_rotate_quaternion_random(self): """Tests that the rotate provide the same results as quaternion.rotate.""" random_euler_angle = test_helpers.generate_random_test_euler_angles() tensor_tile = random_euler_angle.shape[:-1] random_matrix = rotation_matrix_3d.from_euler(random_euler_angle) random_quaternion = quaternion.from_rotation_matrix(random_matrix) random_point = np.random.normal(size=tensor_tile + (3,)) ground_truth = quaternion.rotate(random_point, random_quaternion) prediction = rotation_matrix_3d.rotate(random_point, random_matrix) self.assertAllClose(ground_truth, prediction, rtol=1e-6) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/neural_voxel_renderer/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Neural voxel renderer module."""
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Neural voxel renderer module."""
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/mesh/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.geometry.representation.mesh import sampler from tensorflow_graphics.geometry.representation.mesh import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.geometry.representation.mesh import normals from tensorflow_graphics.geometry.representation.mesh import sampler from tensorflow_graphics.geometry.representation.mesh import utils from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/features/pose_feature_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.pose_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import pose_feature class PoseFeatureTest(tfds.testing.FeatureExpectationsTestCase): """Test Cases for Pose Feature Connector.""" def test_pose_feature(self): expected_rotation = np.eye(3) expected_translation = np.zeros(3) expected_pose = {'R': expected_rotation.astype(np.float32), 't': expected_translation.astype(np.float32)} raising_inputs = {'rotation': expected_rotation.astype(np.float32), 't': expected_translation.astype(np.float32)} self.assertFeature( feature=pose_feature.Pose(), shape={ 'R': (3, 3), 't': (3,) }, dtype={ 'R': tf.float32, 't': tf.float32 }, tests=[ # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_pose, expected=expected_pose, ), tfds.testing.FeatureExpectationItem( value=raising_inputs, raise_cls=ValueError, raise_msg='Missing keys in provided dictionary!', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.pose_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import pose_feature class PoseFeatureTest(tfds.testing.FeatureExpectationsTestCase): """Test Cases for Pose Feature Connector.""" def test_pose_feature(self): expected_rotation = np.eye(3) expected_translation = np.zeros(3) expected_pose = {'R': expected_rotation.astype(np.float32), 't': expected_translation.astype(np.float32)} raising_inputs = {'rotation': expected_rotation.astype(np.float32), 't': expected_translation.astype(np.float32)} self.assertFeature( feature=pose_feature.Pose(), shape={ 'R': (3, 3), 't': (3,) }, dtype={ 'R': tf.float32, 't': tf.float32 }, tests=[ # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_pose, expected=expected_pose, ), tfds.testing.FeatureExpectationItem( value=raising_inputs, raise_cls=ValueError, raise_msg='Missing keys in provided dictionary!', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/features/trimesh_feature_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.trimesh_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import trimesh_feature import trimesh _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class TrimeshFeatureTest(tfds.testing.FeatureExpectationsTestCase): def test_trimesh(self): obj_file_path = os.path.join(_TEST_DATA_DIR, 'cube.obj') obj_file = tf.io.gfile.GFile(obj_file_path) obj_mesh = trimesh.load(obj_file_path) expected_vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]) expected_faces = np.array( [[0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3], [2, 7, 6], [2, 3, 7], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]], dtype=np.uint64) expected_trimesh = {'vertices': expected_vertices, 'faces': expected_faces} # Create a scene with two cubes. scene = trimesh.Scene() scene.add_geometry(obj_mesh) scene.add_geometry(obj_mesh) # The expected TriangleFeature for the scene. expected_scene_feature = { 'vertices': np.tile(expected_vertices, [2, 1]).astype(np.float32), 'faces': np.concatenate( [expected_faces, expected_faces + len(expected_vertices)], axis=0) } self.assertFeature( feature=trimesh_feature.TriangleMesh(), shape={ 'vertices': (None, 3), 'faces': (None, 3) }, dtype={ 'vertices': tf.float32, 'faces': tf.uint64 }, tests=[ # File path tfds.testing.FeatureExpectationItem( value=obj_file_path, expected=expected_trimesh, ), # File object tfds.testing.FeatureExpectationItem( value=obj_file, expected=expected_trimesh, ), # Trimesh tfds.testing.FeatureExpectationItem( value=obj_mesh, expected=expected_trimesh, ), # Scene tfds.testing.FeatureExpectationItem( value=scene, expected=expected_scene_feature, ), # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_scene_feature, expected=expected_scene_feature, ), # Invalid type tfds.testing.FeatureExpectationItem( value=np.random.rand(80, 3), raise_cls=ValueError, raise_msg='obj should be either a Trimesh or a Scene', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.trimesh_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import trimesh_feature import trimesh _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class TrimeshFeatureTest(tfds.testing.FeatureExpectationsTestCase): def test_trimesh(self): obj_file_path = os.path.join(_TEST_DATA_DIR, 'cube.obj') obj_file = tf.io.gfile.GFile(obj_file_path) obj_mesh = trimesh.load(obj_file_path) expected_vertices = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]]) expected_faces = np.array( [[0, 6, 4], [0, 2, 6], [0, 3, 2], [0, 1, 3], [2, 7, 6], [2, 3, 7], [4, 6, 7], [4, 7, 5], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 3]], dtype=np.uint64) expected_trimesh = {'vertices': expected_vertices, 'faces': expected_faces} # Create a scene with two cubes. scene = trimesh.Scene() scene.add_geometry(obj_mesh) scene.add_geometry(obj_mesh) # The expected TriangleFeature for the scene. expected_scene_feature = { 'vertices': np.tile(expected_vertices, [2, 1]).astype(np.float32), 'faces': np.concatenate( [expected_faces, expected_faces + len(expected_vertices)], axis=0) } self.assertFeature( feature=trimesh_feature.TriangleMesh(), shape={ 'vertices': (None, 3), 'faces': (None, 3) }, dtype={ 'vertices': tf.float32, 'faces': tf.uint64 }, tests=[ # File path tfds.testing.FeatureExpectationItem( value=obj_file_path, expected=expected_trimesh, ), # File object tfds.testing.FeatureExpectationItem( value=obj_file, expected=expected_trimesh, ), # Trimesh tfds.testing.FeatureExpectationItem( value=obj_mesh, expected=expected_trimesh, ), # Scene tfds.testing.FeatureExpectationItem( value=scene, expected=expected_scene_feature, ), # FeaturesDict tfds.testing.FeatureExpectationItem( value=expected_scene_feature, expected=expected_scene_feature, ), # Invalid type tfds.testing.FeatureExpectationItem( value=np.random.rand(80, 3), raise_cls=ValueError, raise_msg='obj should be either a Trimesh or a Scene', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/local_implicit_grid/reconstruct_geometry.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Reconstruct scene using LIG. """ import os import warnings from absl import app from absl import flags import numpy as np from tensorflow.compat.v1.io import gfile from tensorflow_graphics.projects.local_implicit_grid.core import point_utils as pu from tensorflow_graphics.projects.local_implicit_grid.core import postprocess from tensorflow_graphics.projects.local_implicit_grid.core import reconstruction as rec import trimesh os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags.DEFINE_string('input_ply', '', 'Input point sample ply file.') flags.DEFINE_string('output_ply', '', 'Reconstructed scene ply file.') flags.DEFINE_integer('steps', 10000, 'Number of optimization steps.') flags.DEFINE_integer('npoints', 10000, 'Number of points to sample per iteration during optim.') flags.DEFINE_float('part_size', 0.25, 'Size of parts per cell (meters).') flags.DEFINE_float('init_std', 0.02, 'Initial std to draw random code from.') flags.DEFINE_integer('res_per_part', 0, 'Evaluation resolution per part. A higher value produces a' 'finer output mesh. 0 to use default value. ' 'Recommended value: 8, 16 or 32.') flags.DEFINE_boolean('overlap', True, 'Use overlapping latent grids.') flags.DEFINE_boolean('postprocess', True, 'Post process to remove backfaces.') flags.DEFINE_string('ckpt_dir', 'pretrained_ckpt', 'Checkpoint directory.') FLAGS = flags.FLAGS def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') if not FLAGS.input_ply: raise IOError('--input_ply must be specified.') if not FLAGS.output_ply: FLAGS.output_ply = FLAGS.input_ply.replace('.ply', '.reconstruct.ply') # load point cloud from ply file v, n = pu.read_point_ply(FLAGS.input_ply) # check if part size is too large min_bb = np.min(np.max(v, axis=0) - np.min(v, axis=0)) if FLAGS.part_size > 0.25 * min_bb: warnings.warn( 'WARNING: part_size seems too large. Recommend using a part_size < ' '{:.2f} for this shape.'.format(0.25 * min_bb), UserWarning) surface_points = np.concatenate([v, n], axis=1) near_surface_samples = rec.get_in_out_from_ray( surface_points, sample_factor=10, std=0.01) xmin = np.min(surface_points[:, :3], 0) xmax = np.max(surface_points[:, :3], 0) # add some extra slack to xmin and xmax xmin -= FLAGS.part_size xmax += FLAGS.part_size if FLAGS.res_per_part == 0: res_per_part = int(64*FLAGS.part_size) else: res_per_part = FLAGS.res_per_part npts = min(near_surface_samples.shape[0], FLAGS.npoints)-1 print('Performing latent grid optimization...') v, f, _, _ = rec.encode_decoder_one_scene( near_surface_samples, FLAGS.ckpt_dir, FLAGS.part_size, overlap=True, indep_pt_loss=True, init_std=FLAGS.init_std, xmin=xmin, xmax=xmax, res_per_part=res_per_part, npts=npts, steps=FLAGS.steps) out_dir = os.path.dirname(FLAGS.output_ply) if out_dir and not gfile.exists(out_dir): gfile.makedirs(out_dir) mesh = trimesh.Trimesh(v, f) if FLAGS.postprocess: print('Postprocessing generated mesh...') mesh = postprocess.remove_backface(mesh, surface_points) print('Writing reconstructed mesh to {}'.format(FLAGS.output_ply)) with gfile.GFile(FLAGS.output_ply, 'wb') as fh: mesh.export(fh, 'ply') if __name__ == '__main__': app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Reconstruct scene using LIG. """ import os import warnings from absl import app from absl import flags import numpy as np from tensorflow.compat.v1.io import gfile from tensorflow_graphics.projects.local_implicit_grid.core import point_utils as pu from tensorflow_graphics.projects.local_implicit_grid.core import postprocess from tensorflow_graphics.projects.local_implicit_grid.core import reconstruction as rec import trimesh os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags.DEFINE_string('input_ply', '', 'Input point sample ply file.') flags.DEFINE_string('output_ply', '', 'Reconstructed scene ply file.') flags.DEFINE_integer('steps', 10000, 'Number of optimization steps.') flags.DEFINE_integer('npoints', 10000, 'Number of points to sample per iteration during optim.') flags.DEFINE_float('part_size', 0.25, 'Size of parts per cell (meters).') flags.DEFINE_float('init_std', 0.02, 'Initial std to draw random code from.') flags.DEFINE_integer('res_per_part', 0, 'Evaluation resolution per part. A higher value produces a' 'finer output mesh. 0 to use default value. ' 'Recommended value: 8, 16 or 32.') flags.DEFINE_boolean('overlap', True, 'Use overlapping latent grids.') flags.DEFINE_boolean('postprocess', True, 'Post process to remove backfaces.') flags.DEFINE_string('ckpt_dir', 'pretrained_ckpt', 'Checkpoint directory.') FLAGS = flags.FLAGS def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') if not FLAGS.input_ply: raise IOError('--input_ply must be specified.') if not FLAGS.output_ply: FLAGS.output_ply = FLAGS.input_ply.replace('.ply', '.reconstruct.ply') # load point cloud from ply file v, n = pu.read_point_ply(FLAGS.input_ply) # check if part size is too large min_bb = np.min(np.max(v, axis=0) - np.min(v, axis=0)) if FLAGS.part_size > 0.25 * min_bb: warnings.warn( 'WARNING: part_size seems too large. Recommend using a part_size < ' '{:.2f} for this shape.'.format(0.25 * min_bb), UserWarning) surface_points = np.concatenate([v, n], axis=1) near_surface_samples = rec.get_in_out_from_ray( surface_points, sample_factor=10, std=0.01) xmin = np.min(surface_points[:, :3], 0) xmax = np.max(surface_points[:, :3], 0) # add some extra slack to xmin and xmax xmin -= FLAGS.part_size xmax += FLAGS.part_size if FLAGS.res_per_part == 0: res_per_part = int(64*FLAGS.part_size) else: res_per_part = FLAGS.res_per_part npts = min(near_surface_samples.shape[0], FLAGS.npoints)-1 print('Performing latent grid optimization...') v, f, _, _ = rec.encode_decoder_one_scene( near_surface_samples, FLAGS.ckpt_dir, FLAGS.part_size, overlap=True, indep_pt_loss=True, init_std=FLAGS.init_std, xmin=xmin, xmax=xmax, res_per_part=res_per_part, npts=npts, steps=FLAGS.steps) out_dir = os.path.dirname(FLAGS.output_ply) if out_dir and not gfile.exists(out_dir): gfile.makedirs(out_dir) mesh = trimesh.Trimesh(v, f) if FLAGS.postprocess: print('Postprocessing generated mesh...') mesh = postprocess.remove_backface(mesh, surface_points) print('Writing reconstructed mesh to {}'.format(FLAGS.output_ply)) with gfile.GFile(FLAGS.output_ply, 'wb') as fh: mesh.export(fh, 'ply') if __name__ == '__main__': app.run(main)
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/nn/layer/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Layer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.nn.layer import graph_convolution from tensorflow_graphics.nn.layer import pointnet from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Layer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.nn.layer import graph_convolution from tensorflow_graphics.nn.layer import pointnet from tensorflow_graphics.util import export_api as _export_api # API contains submodules of tensorflow_graphics.geometry. __all__ = _export_api.get_modules()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/features/voxel_feature_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.voxel_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import voxel_feature _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class VoxelGridFeatureTest(tfds.testing.FeatureExpectationsTestCase): """Test Cases for VoxelGrid FeatureConnector.""" def test_voxel(self): """Tests voxel I/O and encoding/decoding to DatasetFeature.""" mat_file_path = os.path.join(_TEST_DATA_DIR, 'cube.mat') expected_voxel = np.zeros((16, 16, 16), dtype=np.float32) expected_voxel[4:12, 4:12, 4:12] = 1. mat_dict = {'path': mat_file_path, 'key': 'voxels'} raising_inputs = {'path': mat_file_path, 'foo': 'voxels'} wrong_key = {'path': mat_file_path, 'key': 'foo'} wrong_path = {'path': '/somewhere/wrong', 'key': 'voxels'} wrong_dim = np.ones((1, 1, 1, 1)) self.assertFeature( feature=voxel_feature.VoxelGrid((16, 16, 16)), shape=(16, 16, 16), dtype=tf.float32, tests=[ # mat file tfds.testing.FeatureExpectationItem( value=mat_dict, expected=expected_voxel, ), # Voxel Grid tfds.testing.FeatureExpectationItem( value=expected_voxel, expected=expected_voxel, ), tfds.testing.FeatureExpectationItem( value=raising_inputs, raise_cls=ValueError, raise_msg='Missing keys in provided dictionary!', ), tfds.testing.FeatureExpectationItem( value=wrong_key, raise_cls=ValueError, raise_msg='Key `foo` not found in .mat file', ), tfds.testing.FeatureExpectationItem( value=wrong_path, raise_cls=FileNotFoundError, raise_msg='File `/somewhere/wrong` does not exist.', ), tfds.testing.FeatureExpectationItem( value=wrong_dim, raise_cls=ValueError, raise_msg='Only 3D Voxel Grids are supported.', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.datasets.features.voxel_feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from tensorflow_graphics.datasets.features import voxel_feature _TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test_data') class VoxelGridFeatureTest(tfds.testing.FeatureExpectationsTestCase): """Test Cases for VoxelGrid FeatureConnector.""" def test_voxel(self): """Tests voxel I/O and encoding/decoding to DatasetFeature.""" mat_file_path = os.path.join(_TEST_DATA_DIR, 'cube.mat') expected_voxel = np.zeros((16, 16, 16), dtype=np.float32) expected_voxel[4:12, 4:12, 4:12] = 1. mat_dict = {'path': mat_file_path, 'key': 'voxels'} raising_inputs = {'path': mat_file_path, 'foo': 'voxels'} wrong_key = {'path': mat_file_path, 'key': 'foo'} wrong_path = {'path': '/somewhere/wrong', 'key': 'voxels'} wrong_dim = np.ones((1, 1, 1, 1)) self.assertFeature( feature=voxel_feature.VoxelGrid((16, 16, 16)), shape=(16, 16, 16), dtype=tf.float32, tests=[ # mat file tfds.testing.FeatureExpectationItem( value=mat_dict, expected=expected_voxel, ), # Voxel Grid tfds.testing.FeatureExpectationItem( value=expected_voxel, expected=expected_voxel, ), tfds.testing.FeatureExpectationItem( value=raising_inputs, raise_cls=ValueError, raise_msg='Missing keys in provided dictionary!', ), tfds.testing.FeatureExpectationItem( value=wrong_key, raise_cls=ValueError, raise_msg='Key `foo` not found in .mat file', ), tfds.testing.FeatureExpectationItem( value=wrong_path, raise_cls=FileNotFoundError, raise_msg='File `/somewhere/wrong` does not exist.', ), tfds.testing.FeatureExpectationItem( value=wrong_dim, raise_cls=ValueError, raise_msg='Only 3D Voxel Grids are supported.', ), ], ) if __name__ == '__main__': tfds.testing.test_main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/math/interpolation/tests/slerp_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for slerp.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.math.interpolation import slerp from tensorflow_graphics.util import test_case _SQRT2_DIV2 = np.sqrt(2.0).astype(np.float32) * 0.5 class SlerpTest(test_case.TestCase): def _pick_random_quaternion(self): """Creates a random quaternion with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) def _quaternion_slerp_helper(self, q1, q2, p): """Calls interpolate function for quaternions.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.QUATERNION) def _vector_slerp_helper(self, q1, q2, p): """Calls interpolate function for vectors.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.VECTOR) def test_interpolate_raises_exceptions(self): """Tests if unknown methods raise exceptions.""" vector1 = self._pick_random_quaternion() self.assert_exception_is_raised( slerp.interpolate, error_msg="Unknown interpolation type supplied.", shapes=[], vector1=vector1, vector2=-vector1, percent=0.1, method=2) def test_interpolate_with_weights_quaternion_preset(self): """Compares interpolate to quaternion_weights + interpolate_with_weights.""" q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) q1 = tf.nn.l2_normalize(q1, axis=-1) q2 = tf.nn.l2_normalize(q2, axis=-1) weight1, weight2 = slerp.quaternion_weights(q1, q2, 0.25) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate( q1, q2, 0.25, method=slerp.InterpolationType.QUATERNION) self.assertAllClose(qf, qi, atol=1e-9) def test_interpolate_with_weights_vector_preset(self): """Compares interpolate to vector_weights + interpolate_with_weights.""" # Any quaternion is a valid vector q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) weight1, weight2 = slerp.vector_weights(q1, q2, 0.75) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate(q1, q2, 0.75, method=slerp.InterpolationType.VECTOR) self.assertAllClose(qf, qi, atol=1e-9) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((0.408248290463863, -0.408248290463863, 0.816496580927726, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((-0.408248290463863, -0.408248290463863, -0.816496580927726, 0.0),)), ) def test_quaternion_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of qslerp against numpy-quaternion values.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._quaternion_slerp_helper, test_inputs, test_outputs, tile=False) def test_unnormalized_quaternion_weights_exception_raised(self): """Tests if quaternion_weights raise exceptions for unnormalized input.""" q1 = self._pick_random_quaternion() q2 = tf.nn.l2_normalize(q1, axis=-1) p = tf.constant((0.5), dtype=q1.dtype) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(slerp.quaternion_weights(q1, q2, p)) @parameterized.parameters( ((4,), (4,), (1,)), ((None, 4), (None, 4), (None, 1)), ((None, 4), (None, 4), (None, 4)), ) def test_quaternion_weights_exception_not_raised(self, *shapes): """Tests that valid input shapes do not raise exceptions for qslerp.""" self.assert_exception_is_not_raised(slerp.quaternion_weights, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (3,), (4,), (1,)), ("must have exactly 4 dimensions in axis -1", (4,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 4), (3, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 4), (3, 4), (2,)), ) def test_quaternion_weights_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for qslerp.""" self.assert_exception_is_raised(slerp.quaternion_weights, error_msg, shapes) @parameterized.parameters( # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ( (0.25,), (0.75,), )), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ( (-0.8,), (0.2,), )), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ( (-0.2,), (0.8,), )), ) def test_quaternion_weights_preset(self, test_inputs, test_outputs): """Tests the accuracy of quaternion_weights for problem cases.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(slerp.quaternion_weights, test_inputs, test_outputs, tile=False) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 4), (None, 4), (None, 1)), ) def test_vector_weights_exception_not_raised(self, *shapes): """Tests that valid inputs do not raise exceptions for vector_weights.""" self.assert_exception_is_not_raised(slerp.vector_weights, shapes) @parameterized.parameters( ("must have the same number of dimensions in axes", (None, 3), (None, 4), (1,)), ("must have the same number of dimensions in axes", (2, 3), (2, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (3, 3), (2,)), ) def test_vector_weights_exception_raised(self, error_msg, *shapes): """Tests that shape exceptions are properly raised for vector_weights.""" self.assert_exception_is_raised(slerp.vector_weights, error_msg, shapes) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same vectors (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - equal weights (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.5,)), ((0.0, 0.0, 0.0, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.25,)), ((0.5, 0.0, 0.5, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-1.0,)), ((0.0, -_SQRT2_DIV2, _SQRT2_DIV2, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (1.5,)), ((-_SQRT2_DIV2, -0.0, -_SQRT2_DIV2, 0.0),)), # Unnormalized vectors (((4.0, 0.0), (0.0, 1.0), (0.5,)), ((2.82842712, _SQRT2_DIV2),)), ) def test_vector_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of vector slerp results.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._vector_slerp_helper, test_inputs, test_outputs, tile=False) def test_vector_weights_reduce_to_lerp_preset(self): """Tests if vector slerp reduces to lerp for identical vectors as input.""" q1 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) q2 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) p = tf.constant((0.75,), dtype=q1.dtype) w1, w2 = slerp.vector_weights(q1, q2, p) self.assertAllClose(w1, (0.25,), rtol=1e-6) self.assertAllClose(w2, (0.75,), rtol=1e-6) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for slerp.""" from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.math.interpolation import slerp from tensorflow_graphics.util import test_case _SQRT2_DIV2 = np.sqrt(2.0).astype(np.float32) * 0.5 class SlerpTest(test_case.TestCase): def _pick_random_quaternion(self): """Creates a random quaternion with random shape.""" tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() return np.random.normal(size=tensor_shape + [4]) def _quaternion_slerp_helper(self, q1, q2, p): """Calls interpolate function for quaternions.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.QUATERNION) def _vector_slerp_helper(self, q1, q2, p): """Calls interpolate function for vectors.""" return slerp.interpolate(q1, q2, p, slerp.InterpolationType.VECTOR) def test_interpolate_raises_exceptions(self): """Tests if unknown methods raise exceptions.""" vector1 = self._pick_random_quaternion() self.assert_exception_is_raised( slerp.interpolate, error_msg="Unknown interpolation type supplied.", shapes=[], vector1=vector1, vector2=-vector1, percent=0.1, method=2) def test_interpolate_with_weights_quaternion_preset(self): """Compares interpolate to quaternion_weights + interpolate_with_weights.""" q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) q1 = tf.nn.l2_normalize(q1, axis=-1) q2 = tf.nn.l2_normalize(q2, axis=-1) weight1, weight2 = slerp.quaternion_weights(q1, q2, 0.25) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate( q1, q2, 0.25, method=slerp.InterpolationType.QUATERNION) self.assertAllClose(qf, qi, atol=1e-9) def test_interpolate_with_weights_vector_preset(self): """Compares interpolate to vector_weights + interpolate_with_weights.""" # Any quaternion is a valid vector q1 = self._pick_random_quaternion() q2 = q1 + tf.ones_like(q1) weight1, weight2 = slerp.vector_weights(q1, q2, 0.75) qf = slerp.interpolate_with_weights(q1, q2, weight1, weight2) qi = slerp.interpolate(q1, q2, 0.75, method=slerp.InterpolationType.VECTOR) self.assertAllClose(qf, qi, atol=1e-9) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ((-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((0.408248290463863, -0.408248290463863, 0.816496580927726, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-0.5,)), ((-0.408248290463863, -0.408248290463863, -0.816496580927726, 0.0),)), ) def test_quaternion_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of qslerp against numpy-quaternion values.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._quaternion_slerp_helper, test_inputs, test_outputs, tile=False) def test_unnormalized_quaternion_weights_exception_raised(self): """Tests if quaternion_weights raise exceptions for unnormalized input.""" q1 = self._pick_random_quaternion() q2 = tf.nn.l2_normalize(q1, axis=-1) p = tf.constant((0.5), dtype=q1.dtype) with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(slerp.quaternion_weights(q1, q2, p)) @parameterized.parameters( ((4,), (4,), (1,)), ((None, 4), (None, 4), (None, 1)), ((None, 4), (None, 4), (None, 4)), ) def test_quaternion_weights_exception_not_raised(self, *shapes): """Tests that valid input shapes do not raise exceptions for qslerp.""" self.assert_exception_is_not_raised(slerp.quaternion_weights, shapes) @parameterized.parameters( ("must have exactly 4 dimensions in axis -1", (3,), (4,), (1,)), ("must have exactly 4 dimensions in axis -1", (4,), (3,), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 4), (3, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 4), (3, 4), (2,)), ) def test_quaternion_weights_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised for qslerp.""" self.assert_exception_is_raised(slerp.quaternion_weights, error_msg, shapes) @parameterized.parameters( # Same quaternions (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ( (0.25,), (0.75,), )), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.2,)), ( (-0.8,), (0.2,), )), # Anti-polar - large percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.8,)), ( (-0.2,), (0.8,), )), ) def test_quaternion_weights_preset(self, test_inputs, test_outputs): """Tests the accuracy of quaternion_weights for problem cases.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(slerp.quaternion_weights, test_inputs, test_outputs, tile=False) @parameterized.parameters( ((3,), (3,), (1,)), ((None, 4), (None, 4), (None, 1)), ) def test_vector_weights_exception_not_raised(self, *shapes): """Tests that valid inputs do not raise exceptions for vector_weights.""" self.assert_exception_is_not_raised(slerp.vector_weights, shapes) @parameterized.parameters( ("must have the same number of dimensions in axes", (None, 3), (None, 4), (1,)), ("must have the same number of dimensions in axes", (2, 3), (2, 4), (1,)), ("Not all batch dimensions are broadcast-compatible.", (2, 3), (3, 3), (1,)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (3, 3), (2,)), ) def test_vector_weights_exception_raised(self, error_msg, *shapes): """Tests that shape exceptions are properly raised for vector_weights.""" self.assert_exception_is_raised(slerp.vector_weights, error_msg, shapes) @parameterized.parameters( # Orthogonal, same hemisphere (((1.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0), (0.5,)), ((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0),)), (((_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.5, 0.5, 0.5, 0.5),)), # Same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.0, 0.0, _SQRT2_DIV2, _SQRT2_DIV2), (0.5,)), ((0.408248290463863, 0.0, 0.816496580927726, 0.408248290463863),)), # Same vectors (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (0.75,)), ((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0),)), # Anti-polar - equal weights (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.5,)), ((0.0, 0.0, 0.0, 0.0),)), # Anti-polar - small percent (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, 0.0, -_SQRT2_DIV2, 0.0), (0.25,)), ((0.5, 0.0, 0.5, 0.0),)), # Extrapolation - same hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (-1.0,)), ((0.0, -_SQRT2_DIV2, _SQRT2_DIV2, 0.0),)), # Extrapolation - opposite hemisphere (((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0), (-_SQRT2_DIV2, _SQRT2_DIV2, 0.0, 0.0), (1.5,)), ((-_SQRT2_DIV2, -0.0, -_SQRT2_DIV2, 0.0),)), # Unnormalized vectors (((4.0, 0.0), (0.0, 1.0), (0.5,)), ((2.82842712, _SQRT2_DIV2),)), ) def test_vector_slerp_preset(self, test_inputs, test_outputs): """Tests the accuracy of vector slerp results.""" test_inputs = [np.array(test_input).astype(np.float32) for test_input in test_inputs] self.assert_output_is_correct(self._vector_slerp_helper, test_inputs, test_outputs, tile=False) def test_vector_weights_reduce_to_lerp_preset(self): """Tests if vector slerp reduces to lerp for identical vectors as input.""" q1 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) q2 = tf.constant((_SQRT2_DIV2, 0.0, _SQRT2_DIV2, 0.0)) p = tf.constant((0.75,), dtype=q1.dtype) w1, w2 = slerp.vector_weights(q1, q2, p) self.assertAllClose(w1, (0.25,), rtol=1e-6) self.assertAllClose(w2, (0.75,), rtol=1e-6) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/nasa/lib/datasets.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from os import path import tensorflow.compat.v1 as tf tf.disable_eager_execution() def get_dataset(split, hparams): return dataset_dict[hparams.dataset](split, hparams) def amass(split, hparams): """Construct an AMASS data loader.""" def _input_fn(params): # pylint: disable=unused-argument # Dataset constants. n_bbox = 100000 n_surf = 100000 n_points = n_bbox + n_surf n_vert = 6890 n_frames = 1 # Parse parameters for global configurations. n_dims = hparams.n_dims data_dir = hparams.data_dir sample_bbox = hparams.sample_bbox sample_surf = hparams.sample_surf batch_size = hparams.batch_size subject = hparams.subject motion = hparams.motion n_parts = hparams.n_parts def _parse_tfrecord(serialized_example): fs = tf.parse_single_example( serialized_example, features={ 'point': tf.FixedLenFeature([n_frames * n_points * n_dims], tf.float32), 'label': tf.FixedLenFeature([n_frames * n_points * 1], tf.float32), 'vert': tf.FixedLenFeature([n_frames * n_vert * n_dims], tf.float32), 'weight': tf.FixedLenFeature([n_frames * n_vert * n_parts], tf.float32), 'transform': tf.FixedLenFeature( [n_frames * n_parts * (n_dims + 1) * (n_dims + 1)], tf.float32), 'joint': tf.FixedLenFeature([n_frames * n_parts * n_dims], tf.float32), 'name': tf.FixedLenFeature([], tf.string), }) fs['point'] = tf.reshape(fs['point'], [n_frames, n_points, n_dims]) fs['label'] = tf.reshape(fs['label'], [n_frames, n_points, 1]) fs['vert'] = tf.reshape(fs['vert'], [n_frames, n_vert, n_dims]) fs['weight'] = tf.reshape(fs['weight'], [n_frames, n_vert, n_parts]) fs['transform'] = tf.reshape(fs['transform'], [n_frames, n_parts, n_dims + 1, n_dims + 1]) fs['joint'] = tf.reshape(fs['joint'], [n_frames, n_parts, n_dims]) return fs def _sample_frame_points(fs): feature = {} for k, v in fs.items(): feature[k] = v points = feature['point'][0] labels = feature['label'][0] sample_points = [] sample_labels = [] if sample_bbox > 0: indices_bbox = tf.random.uniform([sample_bbox], minval=0, maxval=n_bbox, dtype=tf.int32) bbox_samples = tf.gather(points[:n_bbox], indices_bbox, axis=0) bbox_labels = tf.gather(labels[:n_bbox], indices_bbox, axis=0) sample_points.append(bbox_samples) sample_labels.append(bbox_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=n_surf, dtype=tf.int32) surf_samples = tf.gather( points[n_bbox:n_bbox + n_surf], indices_surf, axis=0) surf_labels = tf.gather( labels[n_bbox:n_bbox + n_surf], indices_surf, axis=0) sample_points.append(surf_samples) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.concat(sample_labels, axis=0) feature['point'] = tf.expand_dims(points, axis=0) feature['label'] = tf.expand_dims(point_labels, axis=0) return feature def _sample_eval_points(fs): feature = {} feature['transform'] = fs['transform'] feature['points'] = fs['point'][:, :n_bbox] feature['labels'] = fs['label'][:, :n_bbox] feature['name'] = fs['name'] feature['vert'] = fs['vert'] feature['weight'] = fs['weight'] feature['joint'] = fs['joint'] return feature data_split = 'train' all_motions = list(x for x in range(10)) if split == 'train': file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, x)) for x in all_motions if x != motion ] else: file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, motion)) ] data_files = tf.gfile.Glob(file_pattern) if not data_files: raise IOError('{} did not match any files'.format(file_pattern)) filenames = tf.data.Dataset.list_files(file_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map( _parse_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache() if split == 'train': data = data.map( _sample_frame_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) else: data = data.map( _sample_eval_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == 'train': data = data.shuffle(int(batch_size * 2.5)).repeat(-1) else: batch_size = 1 return data.batch( batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE) return _input_fn dataset_dict = { 'amass': amass, }
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from os import path import tensorflow.compat.v1 as tf tf.disable_eager_execution() def get_dataset(split, hparams): return dataset_dict[hparams.dataset](split, hparams) def amass(split, hparams): """Construct an AMASS data loader.""" def _input_fn(params): # pylint: disable=unused-argument # Dataset constants. n_bbox = 100000 n_surf = 100000 n_points = n_bbox + n_surf n_vert = 6890 n_frames = 1 # Parse parameters for global configurations. n_dims = hparams.n_dims data_dir = hparams.data_dir sample_bbox = hparams.sample_bbox sample_surf = hparams.sample_surf batch_size = hparams.batch_size subject = hparams.subject motion = hparams.motion n_parts = hparams.n_parts def _parse_tfrecord(serialized_example): fs = tf.parse_single_example( serialized_example, features={ 'point': tf.FixedLenFeature([n_frames * n_points * n_dims], tf.float32), 'label': tf.FixedLenFeature([n_frames * n_points * 1], tf.float32), 'vert': tf.FixedLenFeature([n_frames * n_vert * n_dims], tf.float32), 'weight': tf.FixedLenFeature([n_frames * n_vert * n_parts], tf.float32), 'transform': tf.FixedLenFeature( [n_frames * n_parts * (n_dims + 1) * (n_dims + 1)], tf.float32), 'joint': tf.FixedLenFeature([n_frames * n_parts * n_dims], tf.float32), 'name': tf.FixedLenFeature([], tf.string), }) fs['point'] = tf.reshape(fs['point'], [n_frames, n_points, n_dims]) fs['label'] = tf.reshape(fs['label'], [n_frames, n_points, 1]) fs['vert'] = tf.reshape(fs['vert'], [n_frames, n_vert, n_dims]) fs['weight'] = tf.reshape(fs['weight'], [n_frames, n_vert, n_parts]) fs['transform'] = tf.reshape(fs['transform'], [n_frames, n_parts, n_dims + 1, n_dims + 1]) fs['joint'] = tf.reshape(fs['joint'], [n_frames, n_parts, n_dims]) return fs def _sample_frame_points(fs): feature = {} for k, v in fs.items(): feature[k] = v points = feature['point'][0] labels = feature['label'][0] sample_points = [] sample_labels = [] if sample_bbox > 0: indices_bbox = tf.random.uniform([sample_bbox], minval=0, maxval=n_bbox, dtype=tf.int32) bbox_samples = tf.gather(points[:n_bbox], indices_bbox, axis=0) bbox_labels = tf.gather(labels[:n_bbox], indices_bbox, axis=0) sample_points.append(bbox_samples) sample_labels.append(bbox_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=n_surf, dtype=tf.int32) surf_samples = tf.gather( points[n_bbox:n_bbox + n_surf], indices_surf, axis=0) surf_labels = tf.gather( labels[n_bbox:n_bbox + n_surf], indices_surf, axis=0) sample_points.append(surf_samples) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.concat(sample_labels, axis=0) feature['point'] = tf.expand_dims(points, axis=0) feature['label'] = tf.expand_dims(point_labels, axis=0) return feature def _sample_eval_points(fs): feature = {} feature['transform'] = fs['transform'] feature['points'] = fs['point'][:, :n_bbox] feature['labels'] = fs['label'][:, :n_bbox] feature['name'] = fs['name'] feature['vert'] = fs['vert'] feature['weight'] = fs['weight'] feature['joint'] = fs['joint'] return feature data_split = 'train' all_motions = list(x for x in range(10)) if split == 'train': file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, x)) for x in all_motions if x != motion ] else: file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, motion)) ] data_files = tf.gfile.Glob(file_pattern) if not data_files: raise IOError('{} did not match any files'.format(file_pattern)) filenames = tf.data.Dataset.list_files(file_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map( _parse_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache() if split == 'train': data = data.map( _sample_frame_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) else: data = data.map( _sample_eval_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == 'train': data = data.shuffle(int(batch_size * 2.5)).repeat(-1) else: batch_size = 1 return data.batch( batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE) return _input_fn dataset_dict = { 'amass': amass, }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/math/interpolation/tests/bspline_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for bspline.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.math.interpolation import bspline from tensorflow_graphics.util import test_case class BSplineTest(test_case.TestCase): @parameterized.parameters((0.0, (1.0,)), (1.0, (1.0,))) def test_constant_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 0 return expected values.""" self.assertAllClose(bspline._constant(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (1.0, 0.0)), (1.0, (0.0, 1.0))) def test_linear_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 1 return expected values.""" self.assertAllClose(bspline._linear(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (0.5, 0.5, 0.0)), (1.0, (0.0, 0.5, 0.5))) def test_quadratic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 2 return expected values.""" self.assertAllClose(bspline._quadratic(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0, 0.0)), (1.0, (0.0, 1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0))) def test_cubic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 3 return expected values.""" self.assertAllClose(bspline._cubic(position), weights) # pylint: disable=protected-access @parameterized.parameters( (0.0, (1.0 / 24.0, 11.0 / 24.0, 11.0 / 24.0, 1.0 / 24.0, 0.0)), (1.0, (0.0, 1.0 / 24.0, 11.0 / 24.0, 11.0 / 24.0, 1.0 / 24.0))) def test_quartic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 4 return expected values.""" self.assertAllClose(bspline._quartic(position), weights) # pylint: disable=protected-access @parameterized.parameters( (((0.5,), (1.5,), (2.5,)), (((0.5, 0.5),), ((0.5, 0.5),), ((0.5, 0.5),)), (((0,), (1,), (2,))), 1, True), ((0.0, 1.0), ((0.5, 0.5, 0.0), (0.0, 0.5, 0.5)), (0, 0), 2, False), ) def test_knot_weights_sparse_mode_preset(self, positions, gt_weights, gt_shifts, degree, cyclical): """Tests that sparse mode returns correct results.""" weights, shifts = bspline.knot_weights( positions, num_knots=3, degree=degree, cyclical=cyclical, sparse_mode=True) self.assertAllClose(weights, gt_weights) self.assertAllClose(shifts, gt_shifts) @parameterized.parameters( (((0.5,),), (((0.5, 0.5, 0.0),),), 1), (((1.5,),), (((0.0, 0.5, 0.5),),), 1), (((2.5,),), (((0.5, 0.0, 0.5),),), 1), (((0.5,), (1.5,), (2.5,)), (((1.0 / 8.0, 0.75, 1.0 / 8.0),), ((1.0 / 8.0, 1.0 / 8.0, 0.75),), ((0.75, 1.0 / 8.0, 1.0 / 8.0),)), 2), ) def test_knot_weights_preset(self, position, weights, degree): """Tests that knot weights are correct when degree < num_knots - 1.""" self.assertAllClose( bspline.knot_weights( position, num_knots=3, degree=degree, cyclical=True), weights) @parameterized.parameters((((0.0,), (0.25,), (0.5,), (0.75,)),)) def test_full_degree_non_cyclical_knot_weights(self, positions): """Tests that noncyclical weights are correct when using max degree.""" cyclical_weights = bspline.knot_weights( positions=positions, num_knots=3, degree=2, cyclical=True) noncyclical_weights = bspline.knot_weights( positions=positions, num_knots=3, degree=2, cyclical=False) self.assertAllClose(cyclical_weights, noncyclical_weights) @parameterized.parameters( ("must have the same number of dimensions", ((None, 2), (None, 3, 3))), ("must have the same number of dimensions", ((2,), (3,))), ) def test_interpolate_with_weights_exception_is_raised(self, error_msg, shapes): """Tests that exception is raised when wrong number of knots is given.""" self.assert_exception_is_raised( bspline.interpolate_with_weights, error_msg, shapes=shapes) @parameterized.parameters( (((0.5,), (0.0,), (0.9,)), (((0.5, 1.5), (1.5, 1.5), (2.5, 3.5)),))) def test_interpolate_with_weights_preset(self, positions, knots): """Tests that interpolate_with_weights works correctly.""" degree = 1 cyclical = False interp1 = bspline.interpolate(knots, positions, degree, cyclical) weights = bspline.knot_weights(positions, 2, degree, cyclical) interp2 = bspline.interpolate_with_weights(knots, weights) self.assertAllClose(interp1, interp2) @parameterized.parameters( (1, 2), (1, None), (2, 2), (2, None), (3, 2), (3, None), (4, 2), (4, None), ) def test_knot_weights_exception_is_not_raised(self, positions_rank, dims): shapes = ([dims] * positions_rank,) self.assert_exception_is_not_raised( bspline.knot_weights, shapes=shapes, num_knots=3, degree=2, cyclical=True) @parameterized.parameters( ("Degree should be between 0 and 4.", 6, -1), ("Degree should be between 0 and 4.", 6, 5), ("Degree cannot be >= number of knots.", 2, 2), ("Degree cannot be >= number of knots.", 2, 3), ) def test_knot_weights_exception_is_raised(self, error_msg, num_knots, degree): self.assert_exception_is_raised( bspline.knot_weights, error_msg, shapes=((10, 1),), num_knots=num_knots, degree=degree, cyclical=True) @parameterized.parameters( (1, 0, True), (1, 0, False), (2, 1, True), (2, 1, False), (3, 1, True), (3, 1, False), (3, 2, True), (3, 2, False), (4, 1, True), (4, 1, False), (4, 3, True), (4, 3, False), (5, 1, True), (5, 1, False), (5, 4, True), (5, 4, False), ) def test_knot_weights_jacobian_is_correct(self, num_knots, degree, cyclical): """Tests that Jacobian is correct.""" positions_init = np.random.random_sample((10, 1)) scale = num_knots if cyclical else num_knots - degree positions_init *= scale def dense_mode_fn(positions): return bspline.knot_weights( positions=positions, num_knots=num_knots, degree=degree, cyclical=cyclical, sparse_mode=False) def sparse_mode_fn(positions): return bspline.knot_weights( positions=positions, num_knots=num_knots, degree=degree, cyclical=cyclical, sparse_mode=True)[0] with self.subTest(name="dense_mode"): self.assert_jacobian_is_correct_fn(dense_mode_fn, [positions_init]) with self.subTest(name="sparse_mode"): self.assert_jacobian_is_correct_fn(sparse_mode_fn, [positions_init]) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for bspline.""" from absl.testing import parameterized import numpy as np from tensorflow_graphics.math.interpolation import bspline from tensorflow_graphics.util import test_case class BSplineTest(test_case.TestCase): @parameterized.parameters((0.0, (1.0,)), (1.0, (1.0,))) def test_constant_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 0 return expected values.""" self.assertAllClose(bspline._constant(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (1.0, 0.0)), (1.0, (0.0, 1.0))) def test_linear_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 1 return expected values.""" self.assertAllClose(bspline._linear(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (0.5, 0.5, 0.0)), (1.0, (0.0, 0.5, 0.5))) def test_quadratic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 2 return expected values.""" self.assertAllClose(bspline._quadratic(position), weights) # pylint: disable=protected-access @parameterized.parameters((0.0, (1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0, 0.0)), (1.0, (0.0, 1.0 / 6.0, 2.0 / 3.0, 1.0 / 6.0))) def test_cubic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 3 return expected values.""" self.assertAllClose(bspline._cubic(position), weights) # pylint: disable=protected-access @parameterized.parameters( (0.0, (1.0 / 24.0, 11.0 / 24.0, 11.0 / 24.0, 1.0 / 24.0, 0.0)), (1.0, (0.0, 1.0 / 24.0, 11.0 / 24.0, 11.0 / 24.0, 1.0 / 24.0))) def test_quartic_basis_boundary_values(self, position, weights): """Tests that basis functions of degree 4 return expected values.""" self.assertAllClose(bspline._quartic(position), weights) # pylint: disable=protected-access @parameterized.parameters( (((0.5,), (1.5,), (2.5,)), (((0.5, 0.5),), ((0.5, 0.5),), ((0.5, 0.5),)), (((0,), (1,), (2,))), 1, True), ((0.0, 1.0), ((0.5, 0.5, 0.0), (0.0, 0.5, 0.5)), (0, 0), 2, False), ) def test_knot_weights_sparse_mode_preset(self, positions, gt_weights, gt_shifts, degree, cyclical): """Tests that sparse mode returns correct results.""" weights, shifts = bspline.knot_weights( positions, num_knots=3, degree=degree, cyclical=cyclical, sparse_mode=True) self.assertAllClose(weights, gt_weights) self.assertAllClose(shifts, gt_shifts) @parameterized.parameters( (((0.5,),), (((0.5, 0.5, 0.0),),), 1), (((1.5,),), (((0.0, 0.5, 0.5),),), 1), (((2.5,),), (((0.5, 0.0, 0.5),),), 1), (((0.5,), (1.5,), (2.5,)), (((1.0 / 8.0, 0.75, 1.0 / 8.0),), ((1.0 / 8.0, 1.0 / 8.0, 0.75),), ((0.75, 1.0 / 8.0, 1.0 / 8.0),)), 2), ) def test_knot_weights_preset(self, position, weights, degree): """Tests that knot weights are correct when degree < num_knots - 1.""" self.assertAllClose( bspline.knot_weights( position, num_knots=3, degree=degree, cyclical=True), weights) @parameterized.parameters((((0.0,), (0.25,), (0.5,), (0.75,)),)) def test_full_degree_non_cyclical_knot_weights(self, positions): """Tests that noncyclical weights are correct when using max degree.""" cyclical_weights = bspline.knot_weights( positions=positions, num_knots=3, degree=2, cyclical=True) noncyclical_weights = bspline.knot_weights( positions=positions, num_knots=3, degree=2, cyclical=False) self.assertAllClose(cyclical_weights, noncyclical_weights) @parameterized.parameters( ("must have the same number of dimensions", ((None, 2), (None, 3, 3))), ("must have the same number of dimensions", ((2,), (3,))), ) def test_interpolate_with_weights_exception_is_raised(self, error_msg, shapes): """Tests that exception is raised when wrong number of knots is given.""" self.assert_exception_is_raised( bspline.interpolate_with_weights, error_msg, shapes=shapes) @parameterized.parameters( (((0.5,), (0.0,), (0.9,)), (((0.5, 1.5), (1.5, 1.5), (2.5, 3.5)),))) def test_interpolate_with_weights_preset(self, positions, knots): """Tests that interpolate_with_weights works correctly.""" degree = 1 cyclical = False interp1 = bspline.interpolate(knots, positions, degree, cyclical) weights = bspline.knot_weights(positions, 2, degree, cyclical) interp2 = bspline.interpolate_with_weights(knots, weights) self.assertAllClose(interp1, interp2) @parameterized.parameters( (1, 2), (1, None), (2, 2), (2, None), (3, 2), (3, None), (4, 2), (4, None), ) def test_knot_weights_exception_is_not_raised(self, positions_rank, dims): shapes = ([dims] * positions_rank,) self.assert_exception_is_not_raised( bspline.knot_weights, shapes=shapes, num_knots=3, degree=2, cyclical=True) @parameterized.parameters( ("Degree should be between 0 and 4.", 6, -1), ("Degree should be between 0 and 4.", 6, 5), ("Degree cannot be >= number of knots.", 2, 2), ("Degree cannot be >= number of knots.", 2, 3), ) def test_knot_weights_exception_is_raised(self, error_msg, num_knots, degree): self.assert_exception_is_raised( bspline.knot_weights, error_msg, shapes=((10, 1),), num_knots=num_knots, degree=degree, cyclical=True) @parameterized.parameters( (1, 0, True), (1, 0, False), (2, 1, True), (2, 1, False), (3, 1, True), (3, 1, False), (3, 2, True), (3, 2, False), (4, 1, True), (4, 1, False), (4, 3, True), (4, 3, False), (5, 1, True), (5, 1, False), (5, 4, True), (5, 4, False), ) def test_knot_weights_jacobian_is_correct(self, num_knots, degree, cyclical): """Tests that Jacobian is correct.""" positions_init = np.random.random_sample((10, 1)) scale = num_knots if cyclical else num_knots - degree positions_init *= scale def dense_mode_fn(positions): return bspline.knot_weights( positions=positions, num_knots=num_knots, degree=degree, cyclical=cyclical, sparse_mode=False) def sparse_mode_fn(positions): return bspline.knot_weights( positions=positions, num_knots=num_knots, degree=degree, cyclical=cyclical, sparse_mode=True)[0] with self.subTest(name="dense_mode"): self.assert_jacobian_is_correct_fn(dense_mode_fn, [positions_init]) with self.subTest(name="sparse_mode"): self.assert_jacobian_is_correct_fn(sparse_mode_fn, [positions_init]) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/pix3d/pix3d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """pix3d dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import numpy as np import tensorflow as tf from tensorflow_datasets import features as tfds_features import tensorflow_datasets.public_api as tfds from tensorflow_graphics.datasets import features as tfg_features _CITATION = ''' @inproceedings{pix3d, title={Pix3D: Dataset and Methods for Single-Image 3D Shape Modeling}, author={Sun, Xingyuan and Wu, Jiajun and Zhang, Xiuming and Zhang, Zhoutong and Zhang, Chengkai and Xue, Tianfan and Tenenbaum, Joshua B and Freeman, William T}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2018} } ''' _DESCRIPTION = ''' Pix3D is a large-scale dataset of diverse image-shape pairs with pixel-level 2D-3D alignment. It has wide applications in shape-related tasks including reconstruction, retrieval, viewpoint estimation, etc. Pix3D contains 10,069 2D-3D pairs of 395 distinct 3D shapes, categorised into nine object categories. Each sample comprises of an image, 3D shape represented as (non-watertight) triangle mesh and voxel grid, bounding-box, segmentation mask, intrinsic and extrinsic camera parameters and 2D and 3D key points. Notes: * The object and camera poses are provided with respect to the scene, whereas the camera is placed at the origin. Pix3D also provides the features `camera/position_with_respect_to_object` and `camera/inplane_rotation`. Those values are defined in object coordinates and will reproduce an image that is equivalent to the original image under a homography transformation. They are defined for viewer-centered algorithms whose predictions need to be rotated back to the canonical view for evaluations against ground truth shapes. This is necessary as most algorithms assume that the camera is looking at the object's center, the raw input images are usually cropped or transformed before sending into their pipeline. * There are two wrong segmentation masks in the annotations of the original Pix3D dataset (See https://github.com/xingyuansun/pix3d/issues/18 for details). We ignore those samples in this version of the dataset. However, if you want to use them, we provide own rendered segmentation masks in `tensorflow_graphics/datasets/pix3d/fixed_masks/`. Feel free to copy those two masks to your local Pix3D directory in `<PIX3D_HOME>/mask/table/`. Additionally, you need to add the indices of these samples to the split files located at `<TF Graphics Repository>/tensorflow_graphics/datasets/pix3d/splits`. The index `7953` needs to be appended to the train index and `9657` belongs to the test index. Train/Test split: Pix3D does not provide a standard train/test split. Therefore, this implementation adopts the S2 split from Mesh R-CNN (https://arxiv.org/abs/1906.02739, Sec. 4.2). This split ensures that the 3D models appearing in the train and test sets are disjoint. ''' class Pix3d(tfds.core.GeneratorBasedBuilder): """Pix3D is a large-scale dataset of diverse image-shape pairs with pixel-level 2D-3D alignment.""" VERSION = tfds.core.Version('0.1.0') TRAIN_SPLIT_IDX = os.path.join(os.path.dirname(__file__), 'splits/pix3d_train.npy') TEST_SPLIT_IDX = os.path.join(os.path.dirname(__file__), 'splits/pix3d_test.npy') CLASS_INDEX = ['background', 'bed', 'bookcase', 'chair', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] def _info(self): return tfds.core.DatasetInfo( builder=self, # This is the description that will appear on the datasets page. description=_DESCRIPTION, # tfds.features.FeatureConnectors features=tfds.features.FeaturesDict({ 'image': tfds_features.Image(shape=(None, None, 3), dtype=tf.uint8), 'image/filename': tfds_features.Text(), 'image/source': tfds_features.Text(), '2d_keypoints': tfds_features.FeaturesDict({ 'num_annotators': tf.uint8, 'num_keypoints': tf.uint8, 'keypoints': tfds_features.Tensor(shape=(None,), dtype=tf.float32), }), 'mask': tfds_features.Image(shape=(None, None, 1), dtype=tf.uint8), 'model': tfg_features.TriangleMesh(), 'model/source': tfds_features.Text(), '3d_keypoints': tfds_features.Tensor(shape=(None, 3), dtype=tf.float32), 'voxel': tfg_features.VoxelGrid(shape=(128, 128, 128)), 'pose': tfg_features.Pose(), # pose of object w.r.t to world. 'camera': tfds_features.FeaturesDict({ 'parameters': tfg_features.Camera(), 'position_with_respect_to_object': tfds_features.Tensor( shape=(3,), dtype=tf.float32 ), 'inplane_rotation': tf.float32, }), 'category': tfds_features.ClassLabel( num_classes=len(self.CLASS_INDEX) ), 'bbox': tfds_features.BBoxFeature(), 'truncated': tf.bool, 'occluded': tf.bool, 'slightly_occluded': tf.bool, }), # If there's a common (input, target) tuple from the features, # specify them here. They'll be used if as_supervised=True in # builder.as_dataset. supervised_keys=None, # Homepage of the dataset for documentation homepage='http://pix3d.csail.mit.edu/', citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" pix3d_dir = dl_manager.download_and_extract( 'http://pix3d.csail.mit.edu/data/pix3d.zip') return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ 'samples_directory': pix3d_dir, 'split_file': self.TRAIN_SPLIT_IDX }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ 'samples_directory': pix3d_dir, 'split_file': self.TEST_SPLIT_IDX }, ), ] def _generate_examples(self, samples_directory, split_file): """Yields examples. As Pix3D does not come with a predefined train/test split, we adopt one from Mesh R-CNN. The split ensures that the 3D models appearing in the train and test sets are disjoint. Args: samples_directory: `str`, path to the directory where Pix3D is stored. split_file: `str`, path to .npy file containing the indices of the current split. """ with tf.io.gfile.GFile(os.path.join(samples_directory, 'pix3d.json'), mode='r') as pix3d_index: pix3d = json.load(pix3d_index) split_samples = map(pix3d.__getitem__, np.load(split_file)) def _build_bbox(box, img_size): """Create a BBox with correct order of coordinates. Args: box: Bounding box of the object as provided by Pix3d img_size: size of the image, in the format of [width, height] Returns: tfds.features.BBox. """ xmin, ymin, xmax, ymax = box width, height = img_size return tfds_features.BBox(ymin=ymin / height, xmin=xmin / width, ymax=ymax / height, xmax=xmax / width) def _build_camera(f, img_size): """Prepare features for `Camera` FeatureConnector. The pose originates from the official Pix3D GitHub repository and describes the cameras position with respect to the scene. The focal length is originally provided in mm, but will be converted to pixel here using the fixed sensor with of 32 mm, which also originates from the Pix3D GitHub repository. Link to the official Pix3D repository: https://github.com/xingyuansun/pix3d. Args: f: float, denoting the focal length in mm. img_size: tuple of two floats, denoting the image height and width. Returns: Dictionary with all Camera Parameters. """ sensor_width = 32. return { 'pose': { 'R': np.array([[-1., 0., 0.], [0., -1., 0.], [0., 0., 1.]], dtype=np.float32), 't': np.zeros(3, dtype=np.float32) }, 'optical_center': (img_size[0] / 2, img_size[1] / 2), 'f': (f / sensor_width * img_size[0]) } def _build_2d_keypoints(keypoints): """Wraps keypoint feature in dict, because TFDS does not allow more than sone unknown dimensions. Args: keypoints: Array of dimension `[N, M, 2]`, where N denotes the number of annotators and M is the number of 2D keypoints. Keypoints are stored as (origin: top left corner; +x: rightward; +y: downward); [-1.0, -1.0] if an annotator marked this keypoint hard to label. Returns: Dictionary containing shape and flattened keypoints. """ if keypoints.ndim != 3 or keypoints.shape[-1] != 2: raise ValueError('2D keypoints should be in shape (N, M, 2).') return { 'num_annotators': keypoints.shape[0], 'num_keypoints': keypoints.shape[1], 'keypoints': keypoints.ravel() } for sample in split_samples: example = { 'image': os.path.join(samples_directory, sample['img']), 'image/filename': sample['img'], 'image/source': sample['img_source'], '2d_keypoints': _build_2d_keypoints( np.asarray(sample['2d_keypoints'], dtype=np.float32)), 'mask': os.path.join(samples_directory, sample['mask']), 'model': os.path.join(samples_directory, sample['model']), 'model/source': sample['model_source'], '3d_keypoints': np.loadtxt( os.path.join(samples_directory, sample['3d_keypoints']), dtype=np.float32), 'voxel': { 'path': os.path.join(samples_directory, sample['voxel']), 'key': 'voxel' }, 'pose': { 'R': sample['rot_mat'], 't': sample['trans_mat'] }, 'camera': { 'parameters': _build_camera( sample['focal_length'], sample['img_size'], ), 'position_with_respect_to_object': sample['cam_position'], 'inplane_rotation': sample['inplane_rotation'], }, 'category': self.CLASS_INDEX.index(sample['category']), 'bbox': _build_bbox(sample['bbox'], sample['img_size']), 'truncated': sample['truncated'], 'occluded': sample['occluded'], 'slightly_occluded': sample['slightly_occluded'] } yield sample['img'], example
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """pix3d dataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import numpy as np import tensorflow as tf from tensorflow_datasets import features as tfds_features import tensorflow_datasets.public_api as tfds from tensorflow_graphics.datasets import features as tfg_features _CITATION = ''' @inproceedings{pix3d, title={Pix3D: Dataset and Methods for Single-Image 3D Shape Modeling}, author={Sun, Xingyuan and Wu, Jiajun and Zhang, Xiuming and Zhang, Zhoutong and Zhang, Chengkai and Xue, Tianfan and Tenenbaum, Joshua B and Freeman, William T}, booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2018} } ''' _DESCRIPTION = ''' Pix3D is a large-scale dataset of diverse image-shape pairs with pixel-level 2D-3D alignment. It has wide applications in shape-related tasks including reconstruction, retrieval, viewpoint estimation, etc. Pix3D contains 10,069 2D-3D pairs of 395 distinct 3D shapes, categorised into nine object categories. Each sample comprises of an image, 3D shape represented as (non-watertight) triangle mesh and voxel grid, bounding-box, segmentation mask, intrinsic and extrinsic camera parameters and 2D and 3D key points. Notes: * The object and camera poses are provided with respect to the scene, whereas the camera is placed at the origin. Pix3D also provides the features `camera/position_with_respect_to_object` and `camera/inplane_rotation`. Those values are defined in object coordinates and will reproduce an image that is equivalent to the original image under a homography transformation. They are defined for viewer-centered algorithms whose predictions need to be rotated back to the canonical view for evaluations against ground truth shapes. This is necessary as most algorithms assume that the camera is looking at the object's center, the raw input images are usually cropped or transformed before sending into their pipeline. * There are two wrong segmentation masks in the annotations of the original Pix3D dataset (See https://github.com/xingyuansun/pix3d/issues/18 for details). We ignore those samples in this version of the dataset. However, if you want to use them, we provide own rendered segmentation masks in `tensorflow_graphics/datasets/pix3d/fixed_masks/`. Feel free to copy those two masks to your local Pix3D directory in `<PIX3D_HOME>/mask/table/`. Additionally, you need to add the indices of these samples to the split files located at `<TF Graphics Repository>/tensorflow_graphics/datasets/pix3d/splits`. The index `7953` needs to be appended to the train index and `9657` belongs to the test index. Train/Test split: Pix3D does not provide a standard train/test split. Therefore, this implementation adopts the S2 split from Mesh R-CNN (https://arxiv.org/abs/1906.02739, Sec. 4.2). This split ensures that the 3D models appearing in the train and test sets are disjoint. ''' class Pix3d(tfds.core.GeneratorBasedBuilder): """Pix3D is a large-scale dataset of diverse image-shape pairs with pixel-level 2D-3D alignment.""" VERSION = tfds.core.Version('0.1.0') TRAIN_SPLIT_IDX = os.path.join(os.path.dirname(__file__), 'splits/pix3d_train.npy') TEST_SPLIT_IDX = os.path.join(os.path.dirname(__file__), 'splits/pix3d_test.npy') CLASS_INDEX = ['background', 'bed', 'bookcase', 'chair', 'desk', 'misc', 'sofa', 'table', 'tool', 'wardrobe'] def _info(self): return tfds.core.DatasetInfo( builder=self, # This is the description that will appear on the datasets page. description=_DESCRIPTION, # tfds.features.FeatureConnectors features=tfds.features.FeaturesDict({ 'image': tfds_features.Image(shape=(None, None, 3), dtype=tf.uint8), 'image/filename': tfds_features.Text(), 'image/source': tfds_features.Text(), '2d_keypoints': tfds_features.FeaturesDict({ 'num_annotators': tf.uint8, 'num_keypoints': tf.uint8, 'keypoints': tfds_features.Tensor(shape=(None,), dtype=tf.float32), }), 'mask': tfds_features.Image(shape=(None, None, 1), dtype=tf.uint8), 'model': tfg_features.TriangleMesh(), 'model/source': tfds_features.Text(), '3d_keypoints': tfds_features.Tensor(shape=(None, 3), dtype=tf.float32), 'voxel': tfg_features.VoxelGrid(shape=(128, 128, 128)), 'pose': tfg_features.Pose(), # pose of object w.r.t to world. 'camera': tfds_features.FeaturesDict({ 'parameters': tfg_features.Camera(), 'position_with_respect_to_object': tfds_features.Tensor( shape=(3,), dtype=tf.float32 ), 'inplane_rotation': tf.float32, }), 'category': tfds_features.ClassLabel( num_classes=len(self.CLASS_INDEX) ), 'bbox': tfds_features.BBoxFeature(), 'truncated': tf.bool, 'occluded': tf.bool, 'slightly_occluded': tf.bool, }), # If there's a common (input, target) tuple from the features, # specify them here. They'll be used if as_supervised=True in # builder.as_dataset. supervised_keys=None, # Homepage of the dataset for documentation homepage='http://pix3d.csail.mit.edu/', citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" pix3d_dir = dl_manager.download_and_extract( 'http://pix3d.csail.mit.edu/data/pix3d.zip') return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, gen_kwargs={ 'samples_directory': pix3d_dir, 'split_file': self.TRAIN_SPLIT_IDX }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, gen_kwargs={ 'samples_directory': pix3d_dir, 'split_file': self.TEST_SPLIT_IDX }, ), ] def _generate_examples(self, samples_directory, split_file): """Yields examples. As Pix3D does not come with a predefined train/test split, we adopt one from Mesh R-CNN. The split ensures that the 3D models appearing in the train and test sets are disjoint. Args: samples_directory: `str`, path to the directory where Pix3D is stored. split_file: `str`, path to .npy file containing the indices of the current split. """ with tf.io.gfile.GFile(os.path.join(samples_directory, 'pix3d.json'), mode='r') as pix3d_index: pix3d = json.load(pix3d_index) split_samples = map(pix3d.__getitem__, np.load(split_file)) def _build_bbox(box, img_size): """Create a BBox with correct order of coordinates. Args: box: Bounding box of the object as provided by Pix3d img_size: size of the image, in the format of [width, height] Returns: tfds.features.BBox. """ xmin, ymin, xmax, ymax = box width, height = img_size return tfds_features.BBox(ymin=ymin / height, xmin=xmin / width, ymax=ymax / height, xmax=xmax / width) def _build_camera(f, img_size): """Prepare features for `Camera` FeatureConnector. The pose originates from the official Pix3D GitHub repository and describes the cameras position with respect to the scene. The focal length is originally provided in mm, but will be converted to pixel here using the fixed sensor with of 32 mm, which also originates from the Pix3D GitHub repository. Link to the official Pix3D repository: https://github.com/xingyuansun/pix3d. Args: f: float, denoting the focal length in mm. img_size: tuple of two floats, denoting the image height and width. Returns: Dictionary with all Camera Parameters. """ sensor_width = 32. return { 'pose': { 'R': np.array([[-1., 0., 0.], [0., -1., 0.], [0., 0., 1.]], dtype=np.float32), 't': np.zeros(3, dtype=np.float32) }, 'optical_center': (img_size[0] / 2, img_size[1] / 2), 'f': (f / sensor_width * img_size[0]) } def _build_2d_keypoints(keypoints): """Wraps keypoint feature in dict, because TFDS does not allow more than sone unknown dimensions. Args: keypoints: Array of dimension `[N, M, 2]`, where N denotes the number of annotators and M is the number of 2D keypoints. Keypoints are stored as (origin: top left corner; +x: rightward; +y: downward); [-1.0, -1.0] if an annotator marked this keypoint hard to label. Returns: Dictionary containing shape and flattened keypoints. """ if keypoints.ndim != 3 or keypoints.shape[-1] != 2: raise ValueError('2D keypoints should be in shape (N, M, 2).') return { 'num_annotators': keypoints.shape[0], 'num_keypoints': keypoints.shape[1], 'keypoints': keypoints.ravel() } for sample in split_samples: example = { 'image': os.path.join(samples_directory, sample['img']), 'image/filename': sample['img'], 'image/source': sample['img_source'], '2d_keypoints': _build_2d_keypoints( np.asarray(sample['2d_keypoints'], dtype=np.float32)), 'mask': os.path.join(samples_directory, sample['mask']), 'model': os.path.join(samples_directory, sample['model']), 'model/source': sample['model_source'], '3d_keypoints': np.loadtxt( os.path.join(samples_directory, sample['3d_keypoints']), dtype=np.float32), 'voxel': { 'path': os.path.join(samples_directory, sample['voxel']), 'key': 'voxel' }, 'pose': { 'R': sample['rot_mat'], 't': sample['trans_mat'] }, 'camera': { 'parameters': _build_camera( sample['focal_length'], sample['img_size'], ), 'position_with_respect_to_object': sample['cam_position'], 'inplane_rotation': sample['inplane_rotation'], }, 'category': self.CLASS_INDEX.index(sample['category']), 'bbox': _build_bbox(sample['bbox'], sample['img_size']), 'truncated': sample['truncated'], 'occluded': sample['occluded'], 'slightly_occluded': sample['slightly_occluded'] } yield sample['img'], example
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/util/doc.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Query environment variable for documentation building.""" import os def _import_tfg_docs(): """Checks if __init__.py imports should be executed (for buildling docs).""" return os.getenv("TFG_DOC_IMPORTS", "0") == "1" def enable_tfg_doc_imports(): """Re-enables the imports in the __init__.py so that docs can be built.""" os.environ["TFG_DOC_IMPORTS"] = "1"
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Query environment variable for documentation building.""" import os def _import_tfg_docs(): """Checks if __init__.py imports should be executed (for buildling docs).""" return os.getenv("TFG_DOC_IMPORTS", "0") == "1" def enable_tfg_doc_imports(): """Re-enables the imports in the __init__.py so that docs can be built.""" os.environ["TFG_DOC_IMPORTS"] = "1"
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/nn/layer/tests/graph_convolution_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the graph convolution layers.""" from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_graphics.nn.layer.graph_convolution as gc_layer from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Convert a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) def _dummy_data(batch_size, num_vertices, num_channels): """Create inputs for feature_steered_convolution.""" if batch_size > 0: data = np.zeros( shape=(batch_size, num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse( np.tile(np.eye(num_vertices, dtype=np.float32), (batch_size, 1, 1))) else: data = np.zeros(shape=(num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse(np.eye(num_vertices, dtype=np.float32)) return data, neighbors class GraphConvolutionTestFeatureSteeredConvolutionLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, 1, False), (4, 2, 3, None, 5, False), (1, 2, 3, 4, 5, True), ) def test_feature_steered_convolution_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, num_weight_matrices, translation_invariant): """Check if the convolution parameters and output have correct shapes.""" data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) name_scope = "test" if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=name_scope) def _run_convolution(): """Run the appropriate feature steered convolution layer.""" if tf.executing_eagerly(): try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) else: try: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=None, var_name=name_scope) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) return output output = _run_convolution() output_shape = output.shape.as_list() out_channels = in_channels if out_channels is None else out_channels self.assertEqual(output_shape[-1], out_channels) self.assertAllEqual(output_shape[:-1], data.shape[:-1]) def _get_var_shape(var_name): """Get the shape of a variable by name.""" if tf.executing_eagerly(): trainable_variables = layer.trainable_variables for tv in trainable_variables: if tv.name == name_scope + "/" + var_name + ":0": return tv.shape.as_list() raise ValueError("Variable not found.") else: with tf.compat.v1.variable_scope(name_scope, reuse=True): variable = tf.compat.v1.get_variable( var_name, initializer=tf.constant(0)) return variable.shape.as_list() self.assertAllEqual(_get_var_shape("u"), [in_channels, num_weight_matrices]) self.assertAllEqual(_get_var_shape("c"), [num_weight_matrices]) self.assertAllEqual(_get_var_shape("b"), [out_channels]) self.assertAllEqual( _get_var_shape("w"), [num_weight_matrices, in_channels, out_channels]) if not translation_invariant: self.assertAllEqual( _get_var_shape("v"), [in_channels, num_weight_matrices]) def test_feature_steered_convolution_layer_initializer(self): """Tests a custom variable initializer.""" data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) initializer = tf.compat.v1.keras.initializers.zeros() if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, initializer=initializer) output = layer(inputs=[data, neighbors], sizes=None) else: out = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, initializer=initializer) self.evaluate(tf.compat.v1.global_variables_initializer()) output = self.evaluate(out) # All zeros initializer should result in all zeros output. self.assertAllEqual(output, np.zeros_like(data)) def test_feature_steered_convolution_layer_training(self): """Test a simple training loop.""" # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 if tf.executing_eagerly(): with tf.GradientTape(persistent=True) as tape: layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, num_weight_matrices=1, num_output_channels=1) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) else: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, num_weight_matrices=1, num_output_channels=1) train_op = tf.compat.v1.train.GradientDescentOptimizer(1e-4).minimize( tf.nn.l2_loss(output - labels)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.initialize_all_variables()) for _ in range(num_training_iterations): sess.run(train_op) class GraphConvolutionTestDynamicGraphConvolutionKerasLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Check if the convolution parameters and output have correct shapes.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction) try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) self.assertAllEqual((batch_size, num_vertices, out_channels), output.shape) @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_zero_kernel( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Tests convolution with an all-zeros kernel.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) data = np.random.uniform(size=data.shape).astype(np.float32) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction, use_bias=False, kernel_initializer=tf.compat.v1.keras.initializers.zeros()) output = layer(inputs=[data, neighbors], sizes=None) self.assertAllEqual( output, np.zeros(shape=(batch_size, num_vertices, out_channels), dtype=np.float32)) @parameterized.parameters((1, 1, 1), (2, 3, 12), (2, 3, 4)) def test_dynamic_graph_convolution_keras_layer_duplicate_features( self, num_vertices, in_channels, out_channels): """Tests convolution when all vertex features are identical.""" if not tf.executing_eagerly(): return data = np.random.uniform(size=(1, in_channels)) data = np.tile(data, (num_vertices, 1)) # Results should be independent of 'neighbors'. neighbors = np.maximum(np.random.randint( 0, 2, size=(num_vertices, num_vertices)), np.eye(num_vertices)) neighbors = _dense_to_sparse(neighbors) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction="max") output = layer(inputs=[data, neighbors], sizes=None) output_tile = tf.tile(output[:1, :], (num_vertices, 1)) self.assertAllEqual(output, output_tile) @parameterized.parameters("weighted", "max") def test_dynamic_graph_convolution_keras_layer_training(self, reduction): """Test a simple training loop.""" if not tf.executing_eagerly(): return # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 with tf.GradientTape(persistent=True) as tape: layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=2, reduction=reduction) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the graph convolution layers.""" from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_graphics.nn.layer.graph_convolution as gc_layer from tensorflow_graphics.util import test_case def _dense_to_sparse(data): """Convert a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape) def _dummy_data(batch_size, num_vertices, num_channels): """Create inputs for feature_steered_convolution.""" if batch_size > 0: data = np.zeros( shape=(batch_size, num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse( np.tile(np.eye(num_vertices, dtype=np.float32), (batch_size, 1, 1))) else: data = np.zeros(shape=(num_vertices, num_channels), dtype=np.float32) neighbors = _dense_to_sparse(np.eye(num_vertices, dtype=np.float32)) return data, neighbors class GraphConvolutionTestFeatureSteeredConvolutionLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, 1, False), (4, 2, 3, None, 5, False), (1, 2, 3, 4, 5, True), ) def test_feature_steered_convolution_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, num_weight_matrices, translation_invariant): """Check if the convolution parameters and output have correct shapes.""" data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) name_scope = "test" if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=name_scope) def _run_convolution(): """Run the appropriate feature steered convolution layer.""" if tf.executing_eagerly(): try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) else: try: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=translation_invariant, num_weight_matrices=num_weight_matrices, num_output_channels=out_channels, name=None, var_name=name_scope) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) return output output = _run_convolution() output_shape = output.shape.as_list() out_channels = in_channels if out_channels is None else out_channels self.assertEqual(output_shape[-1], out_channels) self.assertAllEqual(output_shape[:-1], data.shape[:-1]) def _get_var_shape(var_name): """Get the shape of a variable by name.""" if tf.executing_eagerly(): trainable_variables = layer.trainable_variables for tv in trainable_variables: if tv.name == name_scope + "/" + var_name + ":0": return tv.shape.as_list() raise ValueError("Variable not found.") else: with tf.compat.v1.variable_scope(name_scope, reuse=True): variable = tf.compat.v1.get_variable( var_name, initializer=tf.constant(0)) return variable.shape.as_list() self.assertAllEqual(_get_var_shape("u"), [in_channels, num_weight_matrices]) self.assertAllEqual(_get_var_shape("c"), [num_weight_matrices]) self.assertAllEqual(_get_var_shape("b"), [out_channels]) self.assertAllEqual( _get_var_shape("w"), [num_weight_matrices, in_channels, out_channels]) if not translation_invariant: self.assertAllEqual( _get_var_shape("v"), [in_channels, num_weight_matrices]) def test_feature_steered_convolution_layer_initializer(self): """Tests a custom variable initializer.""" data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) initializer = tf.compat.v1.keras.initializers.zeros() if tf.executing_eagerly(): layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, initializer=initializer) output = layer(inputs=[data, neighbors], sizes=None) else: out = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, initializer=initializer) self.evaluate(tf.compat.v1.global_variables_initializer()) output = self.evaluate(out) # All zeros initializer should result in all zeros output. self.assertAllEqual(output, np.zeros_like(data)) def test_feature_steered_convolution_layer_training(self): """Test a simple training loop.""" # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 if tf.executing_eagerly(): with tf.GradientTape(persistent=True) as tape: layer = gc_layer.FeatureSteeredConvolutionKerasLayer( translation_invariant=False, num_weight_matrices=1, num_output_channels=1) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) else: output = gc_layer.feature_steered_convolution_layer( data=data, neighbors=neighbors, sizes=None, translation_invariant=False, num_weight_matrices=1, num_output_channels=1) train_op = tf.compat.v1.train.GradientDescentOptimizer(1e-4).minimize( tf.nn.l2_loss(output - labels)) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.initialize_all_variables()) for _ in range(num_training_iterations): sess.run(train_op) class GraphConvolutionTestDynamicGraphConvolutionKerasLayerTests( test_case.TestCase): @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_exception_not_raised_shapes( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Check if the convolution parameters and output have correct shapes.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction) try: output = layer(inputs=[data, neighbors], sizes=None) except Exception as e: # pylint: disable=broad-except self.fail("Exception raised: %s" % str(e)) self.assertAllEqual((batch_size, num_vertices, out_channels), output.shape) @parameterized.parameters( (1, 1, 1, 1, "weighted"), (4, 2, 3, 12, "max"), (1, 2, 3, 4, "max"), ) def test_dynamic_graph_convolution_keras_layer_zero_kernel( self, batch_size, num_vertices, in_channels, out_channels, reduction): """Tests convolution with an all-zeros kernel.""" if not tf.executing_eagerly(): return data, neighbors = _dummy_data(batch_size, num_vertices, in_channels) data = np.random.uniform(size=data.shape).astype(np.float32) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction=reduction, use_bias=False, kernel_initializer=tf.compat.v1.keras.initializers.zeros()) output = layer(inputs=[data, neighbors], sizes=None) self.assertAllEqual( output, np.zeros(shape=(batch_size, num_vertices, out_channels), dtype=np.float32)) @parameterized.parameters((1, 1, 1), (2, 3, 12), (2, 3, 4)) def test_dynamic_graph_convolution_keras_layer_duplicate_features( self, num_vertices, in_channels, out_channels): """Tests convolution when all vertex features are identical.""" if not tf.executing_eagerly(): return data = np.random.uniform(size=(1, in_channels)) data = np.tile(data, (num_vertices, 1)) # Results should be independent of 'neighbors'. neighbors = np.maximum(np.random.randint( 0, 2, size=(num_vertices, num_vertices)), np.eye(num_vertices)) neighbors = _dense_to_sparse(neighbors) layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=out_channels, reduction="max") output = layer(inputs=[data, neighbors], sizes=None) output_tile = tf.tile(output[:1, :], (num_vertices, 1)) self.assertAllEqual(output, output_tile) @parameterized.parameters("weighted", "max") def test_dynamic_graph_convolution_keras_layer_training(self, reduction): """Test a simple training loop.""" if not tf.executing_eagerly(): return # Generate a small valid input for a simple training task. # Four corners of a square. data = np.array(((1.0, 1.0), (-1.0, 1.0), (-1.0, -1.0), (1.0, -1.0))) neighbors_indices = np.array(((0, 0), (0, 1), (0, 3), (1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 0), (3, 2), (3, 3))) neighbors = tf.SparseTensor( neighbors_indices, np.ones(shape=(12,)) / 3.0, dense_shape=(4, 4)) # Desired output is arbitrary. labels = np.reshape([-1.0, -0.5, 0.5, 1.0], (-1, 1)) num_training_iterations = 5 with tf.GradientTape(persistent=True) as tape: layer = gc_layer.DynamicGraphConvolutionKerasLayer( num_output_channels=2, reduction=reduction) output = layer(inputs=[data, neighbors], sizes=None) loss = tf.nn.l2_loss(output - labels) trainable_variables = layer.trainable_variables for _ in range(num_training_iterations): grads = tape.gradient(loss, trainable_variables) tf.compat.v1.train.GradientDescentOptimizer(1e-4).apply_gradients( zip(grads, trainable_variables)) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/notebooks/resources/tfg_simplified_logo.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh of the simplified tensorflow-graphics logo.""" import numpy as np vertices = ( (1, -1, -2), (1, -2, -2), (1, -2, 2), (1, -1, 2), (1, -1, 1), (1, 1, 1), (1, 1, 2), (1, 2, 2), (1, 2, -1), (1, 1, -1), (2, -1, -2), (2, -2, -2), (2, -2, 2), (2, -1, 2), (2, -1, 1), (2, 1, 1), (2, 1, 2), (2, 2, 2), (2, 2, -1), (2, 1, -1), (-1, -2, -2), (-1, -2, -1), (-1, 2, -1), (-1, 2, -2), (-1, 1, -1), (-1, 1, 2), (-1, 2, 2), (-2, -2, -2), (-2, -2, -1), (-2, 2, -1), (-2, 2, -2), (-2, 1, -1), (-2, 1, 2), (-2, 2, 2), (-1, -1, -2), (-1, -1, -1), (1, -1, -1), (1, -2, -1), ) vertices = np.array(vertices) vertices[:, 2] = -vertices[:, 2] faces = ( # Right piece (2, 1, 0), (3, 2, 0), (3, 4, 6), (5, 6, 4), (7, 6, 8), (9, 8, 6), (10, 11, 12), (12, 13, 10), (14, 13, 16), (16, 15, 14), (16, 17, 18), (18, 19, 16), (0, 1, 10), (1, 11, 10), (0, 14, 4), (14, 0, 10), (1, 2, 12), (1, 12, 11), (4, 14, 5), (5, 14, 15), (5, 19, 9), (19, 5, 15), (9, 19, 18), (18, 8, 9), (8, 18, 17), (17, 7, 8), (7, 12, 2), (12, 7, 17), # Left piece (20, 21, 22), (22, 23, 20), (22, 24, 25), (26, 22, 25), (28, 27, 29), (30, 29, 27), (31, 29, 32), (29, 33, 32), (20, 28, 21), (28, 20, 27), (20, 30, 27), (20, 23, 30), (23, 33, 30), (33, 23, 26), (26, 25, 33), (25, 32, 33), (25, 24, 32), (24, 31, 32), (24, 21, 31), (21, 28, 31), # central piece (1, 0, 20), (20, 0, 34), (0, 35, 34), (36, 35, 0), (36, 37, 21), (35, 36, 21), (1, 21, 37), (20, 21, 1), ) faces = np.array(faces) mesh = {'vertices': vertices, 'faces': faces}
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Mesh of the simplified tensorflow-graphics logo.""" import numpy as np vertices = ( (1, -1, -2), (1, -2, -2), (1, -2, 2), (1, -1, 2), (1, -1, 1), (1, 1, 1), (1, 1, 2), (1, 2, 2), (1, 2, -1), (1, 1, -1), (2, -1, -2), (2, -2, -2), (2, -2, 2), (2, -1, 2), (2, -1, 1), (2, 1, 1), (2, 1, 2), (2, 2, 2), (2, 2, -1), (2, 1, -1), (-1, -2, -2), (-1, -2, -1), (-1, 2, -1), (-1, 2, -2), (-1, 1, -1), (-1, 1, 2), (-1, 2, 2), (-2, -2, -2), (-2, -2, -1), (-2, 2, -1), (-2, 2, -2), (-2, 1, -1), (-2, 1, 2), (-2, 2, 2), (-1, -1, -2), (-1, -1, -1), (1, -1, -1), (1, -2, -1), ) vertices = np.array(vertices) vertices[:, 2] = -vertices[:, 2] faces = ( # Right piece (2, 1, 0), (3, 2, 0), (3, 4, 6), (5, 6, 4), (7, 6, 8), (9, 8, 6), (10, 11, 12), (12, 13, 10), (14, 13, 16), (16, 15, 14), (16, 17, 18), (18, 19, 16), (0, 1, 10), (1, 11, 10), (0, 14, 4), (14, 0, 10), (1, 2, 12), (1, 12, 11), (4, 14, 5), (5, 14, 15), (5, 19, 9), (19, 5, 15), (9, 19, 18), (18, 8, 9), (8, 18, 17), (17, 7, 8), (7, 12, 2), (12, 7, 17), # Left piece (20, 21, 22), (22, 23, 20), (22, 24, 25), (26, 22, 25), (28, 27, 29), (30, 29, 27), (31, 29, 32), (29, 33, 32), (20, 28, 21), (28, 20, 27), (20, 30, 27), (20, 23, 30), (23, 33, 30), (33, 23, 26), (26, 25, 33), (25, 32, 33), (25, 24, 32), (24, 31, 32), (24, 21, 31), (21, 28, 31), # central piece (1, 0, 20), (20, 0, 34), (0, 35, 34), (36, 35, 0), (36, 37, 21), (35, 36, 21), (1, 21, 37), (20, 21, 1), ) faces = np.array(faces) mesh = {'vertices': vertices, 'faces': faces}
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./requirements.txt
tensorflow >= 2.2.0 tensorflow-addons >= 0.10.0 tensorflow-datasets >= 2.0.0 absl-py >= 0.6.1 h5py >= 2.10.0 matplotlib >= 2.2.5 numpy >= 1.15.4 psutil >= 5.7.0 scipy >= 1.1.0 tqdm >= 4.45.0 OpenEXR >= 1.3.2 termcolor >= 1.1.0 trimesh >= 2.37.22 # Required by trimesh. networkx
tensorflow >= 2.2.0 tensorflow-addons >= 0.10.0 tensorflow-datasets >= 2.0.0 absl-py >= 0.6.1 h5py >= 2.10.0 matplotlib >= 2.2.5 numpy >= 1.15.4 psutil >= 5.7.0 scipy >= 1.1.0 tqdm >= 4.45.0 OpenEXR >= 1.3.2 termcolor >= 1.1.0 trimesh >= 2.37.22 # Required by trimesh. networkx
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/voxels/tests/emission_absorption_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for emission absorption voxel rendering.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.voxels import emission_absorption from tensorflow_graphics.rendering.voxels.tests import test_helpers from tensorflow_graphics.util import test_case class EmissionAbsorptionTest(test_case.TestCase): @parameterized.parameters( (0, (8, 16, 6, 1)), (1, (12, 8, 16, 6, 3)), ) def test_render_shape_exception_not_raised(self, axis, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(emission_absorption.render, shape, axis=axis) @parameterized.parameters( ("must have a rank greater than 3", 2, (3,)), ("must have a rank greater than 3", 2, (16, 6, 3)), ("'axis' needs to be 0, 1 or 2", 5, (8, 16, 6, 1)), ) def test_render_shape_exception_raised(self, error_msg, axis, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(emission_absorption.render, error_msg, shape, axis=axis) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_render_jacobian_random(self): """Tests the Jacobian of render.""" voxels_init = test_helpers.generate_random_test_voxels_render() absorption_factor_init = np.float64(np.random.uniform(low=0.1, high=2.0)) cell_size_init = np.float64(np.random.uniform(low=0.1, high=2.0)) self.assert_jacobian_is_correct_fn( emission_absorption.render, [voxels_init, absorption_factor_init, cell_size_init], atol=1e-4) def test_render_preset(self): """Checks that render returns the expected value.""" x_voxels_init, y_images_init = test_helpers.generate_preset_test_voxels_emission_absorption_render( ) voxels = tf.convert_to_tensor(value=x_voxels_init) y_images = tf.convert_to_tensor(value=y_images_init) y = emission_absorption.render(voxels, absorption_factor=0.1, cell_size=0.1) self.assertAllClose(y_images, y) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for emission absorption voxel rendering.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.voxels import emission_absorption from tensorflow_graphics.rendering.voxels.tests import test_helpers from tensorflow_graphics.util import test_case class EmissionAbsorptionTest(test_case.TestCase): @parameterized.parameters( (0, (8, 16, 6, 1)), (1, (12, 8, 16, 6, 3)), ) def test_render_shape_exception_not_raised(self, axis, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(emission_absorption.render, shape, axis=axis) @parameterized.parameters( ("must have a rank greater than 3", 2, (3,)), ("must have a rank greater than 3", 2, (16, 6, 3)), ("'axis' needs to be 0, 1 or 2", 5, (8, 16, 6, 1)), ) def test_render_shape_exception_raised(self, error_msg, axis, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(emission_absorption.render, error_msg, shape, axis=axis) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_render_jacobian_random(self): """Tests the Jacobian of render.""" voxels_init = test_helpers.generate_random_test_voxels_render() absorption_factor_init = np.float64(np.random.uniform(low=0.1, high=2.0)) cell_size_init = np.float64(np.random.uniform(low=0.1, high=2.0)) self.assert_jacobian_is_correct_fn( emission_absorption.render, [voxels_init, absorption_factor_init, cell_size_init], atol=1e-4) def test_render_preset(self): """Checks that render returns the expected value.""" x_voxels_init, y_images_init = test_helpers.generate_preset_test_voxels_emission_absorption_render( ) voxels = tf.convert_to_tensor(value=x_voxels_init) y_images = tf.convert_to_tensor(value=y_images_init) y = emission_absorption.render(voxels, absorption_factor=0.1, cell_size=0.1) self.assertAllClose(y_images, y) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/neural_voxel_renderer/prepare_tfrecords/data.proto
syntax = "proto2"; package giotto_blender; message BlenderSample { optional string name = 1; optional bytes image_data = 2; optional int32 height = 3; optional int32 width = 4; optional string obj = 5; optional float rotation = 6; repeated float translation = 7; repeated float obj_color = 8; repeated float floor_color = 9; repeated float light = 10; optional string envmap = 11; optional float elevation = 12; repeated float rt = 13; repeated float k = 14; } message VoxelSample { optional string name = 1; optional bytes voxel_data = 2; repeated int32 size = 3; repeated float obj_bbox = 5; } message NeuralVoxelPlusSample { optional string name = 1; repeated bytes voxel_data = 2; repeated bytes rerendering_data = 3; repeated bytes image_data = 4; repeated float light_position = 5; }
syntax = "proto2"; package giotto_blender; message BlenderSample { optional string name = 1; optional bytes image_data = 2; optional int32 height = 3; optional int32 width = 4; optional string obj = 5; optional float rotation = 6; repeated float translation = 7; repeated float obj_color = 8; repeated float floor_color = 9; repeated float light = 10; optional string envmap = 11; optional float elevation = 12; repeated float rt = 13; repeated float k = 14; } message VoxelSample { optional string name = 1; optional bytes voxel_data = 2; repeated int32 size = 3; repeated float obj_bbox = 5; } message NeuralVoxelPlusSample { optional string name = 1; repeated bytes voxel_data = 2; repeated bytes rerendering_data = 3; repeated bytes image_data = 4; repeated float light_position = 5; }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/testing/metadata/model_net40/1.0.0/dataset_info.json
{ "citation": "\n@inproceedings{qi2017pointnet,\n title={Pointnet: Deep learning on point sets for 3d classification and segmentation},\n author={Qi, Charles R and Su, Hao and Mo, Kaichun and Guibas, Leonidas J},\n booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},\n pages={652--660},\n year={2017}\n}\n", "description": "\nThe dataset contains point clouds sampling CAD models from 40 different categories.\nThe files have been retrieved from https://modelnet.cs.princeton.edu\n\nTo generate each example, the authors first uniformly sampled a modelnet40 mesh\nwith 10000 uniform samples, and then employed furthest point sampling to downsample\nto 2048 points. The procedure is explained [here](https://github.com/charlesq34/pointnet2/blob/master/tf_ops/sampling/tf_sampling.py)\n", "location": { "urls": [ "https://modelnet.cs.princeton.edu" ] }, "name": "model_net40", "schema": { "feature": [ { "name": "label", "type": "INT" }, { "name": "points", "shape": { "dim": [ { "size": "2048" }, { "size": "3" } ] }, "type": "FLOAT" } ] }, "sizeInBytes": "435212151", "splits": [ { "name": "test", "numShards": "1", "shardLengths": [ "2468" ], "statistics": { "features": [ { "name": "label", "numStats": { "commonStats": { "numNonMissing": "2468" }, "max": 39.0 } }, { "name": "points", "numStats": { "commonStats": { "numNonMissing": "2468" }, "max": 0.9999974370002747, "min": -0.9999753832817078 }, "type": "FLOAT" } ], "numExamples": "2468" } }, { "name": "train", "numShards": "1", "shardLengths": [ "4920", "4920" ], "statistics": { "features": [ { "name": "label", "numStats": { "commonStats": { "numNonMissing": "9840" }, "max": 39.0 } }, { "name": "points", "numStats": { "commonStats": { "numNonMissing": "9840" }, "max": 0.9999983310699463, "min": -0.9999980926513672 }, "type": "FLOAT" } ], "numExamples": "9840" } } ], "supervisedKeys": { "input": "points", "output": "label" }, "version": "1.0.0" }
{ "citation": "\n@inproceedings{qi2017pointnet,\n title={Pointnet: Deep learning on point sets for 3d classification and segmentation},\n author={Qi, Charles R and Su, Hao and Mo, Kaichun and Guibas, Leonidas J},\n booktitle={Proceedings of the IEEE conference on computer vision and pattern recognition},\n pages={652--660},\n year={2017}\n}\n", "description": "\nThe dataset contains point clouds sampling CAD models from 40 different categories.\nThe files have been retrieved from https://modelnet.cs.princeton.edu\n\nTo generate each example, the authors first uniformly sampled a modelnet40 mesh\nwith 10000 uniform samples, and then employed furthest point sampling to downsample\nto 2048 points. The procedure is explained [here](https://github.com/charlesq34/pointnet2/blob/master/tf_ops/sampling/tf_sampling.py)\n", "location": { "urls": [ "https://modelnet.cs.princeton.edu" ] }, "name": "model_net40", "schema": { "feature": [ { "name": "label", "type": "INT" }, { "name": "points", "shape": { "dim": [ { "size": "2048" }, { "size": "3" } ] }, "type": "FLOAT" } ] }, "sizeInBytes": "435212151", "splits": [ { "name": "test", "numShards": "1", "shardLengths": [ "2468" ], "statistics": { "features": [ { "name": "label", "numStats": { "commonStats": { "numNonMissing": "2468" }, "max": 39.0 } }, { "name": "points", "numStats": { "commonStats": { "numNonMissing": "2468" }, "max": 0.9999974370002747, "min": -0.9999753832817078 }, "type": "FLOAT" } ], "numExamples": "2468" } }, { "name": "train", "numShards": "1", "shardLengths": [ "4920", "4920" ], "statistics": { "features": [ { "name": "label", "numStats": { "commonStats": { "numNonMissing": "9840" }, "max": 39.0 } }, { "name": "points", "numStats": { "commonStats": { "numNonMissing": "9840" }, "max": 0.9999983310699463, "min": -0.9999980926513672 }, "type": "FLOAT" } ], "numExamples": "9840" } } ], "supervisedKeys": { "input": "points", "output": "label" }, "version": "1.0.0" }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/neural_voxel_renderer/prepare_tfrecords/download_colored_voxels.sh
#!/bin/bash for i in {0..99} do fname=$(printf "%05d" $i) wget -P $1 https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/colored_voxels/test-$fname-of-00100.tfrecord done
#!/bin/bash for i in {0..99} do fname=$(printf "%05d" $i) wget -P $1 https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/colored_voxels/test-$fname-of-00100.tfrecord done
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/kernels/rasterize_triangles_impl.cc
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "py/tensorflow_graphics/rendering/kernels/rasterize_triangles_impl.h" #include <algorithm> #include <cmath> namespace { using fixed_t = int64; // Converts to fixed point with 16 fractional bits and 48 integer bits. // TODO(fcole): fixed-point depth may be too shallow. // The algorithm requires multiplying two of the xyzw clip-space coordinates // together, summing, and then multiplying by an NDC pixel coordinate (three // total multiplies). After three multiplications, the fractional part will be // 48 bits, leaving 16 bits for the integer part. The NDC pixel coordinates // are in (-1,1) so they need only 1 integer bit, so as long as the values of // the inverse matrix are < 2^15, the fixed-point math should not overflow. This // seems a bit dicey but so far all the tests I've tried pass. constexpr int kFractionalBits = 16; constexpr fixed_t ShiftPointLeft(fixed_t x) { return x << kFractionalBits; } constexpr fixed_t ToFixedPoint(float f) { return static_cast<fixed_t>(f * ShiftPointLeft(1)); } // Takes the minimum of a and b, rounds down, and converts to an integer in // the range [low, high]. inline int ClampedIntegerMin(float a, float b, int low, int high) { const float value = std::floor(std::min(a, b)); return static_cast<int>( std::clamp(value, static_cast<float>(low), static_cast<float>(high))); } // Takes the maximum of a and b, rounds up, and converts to an integer in the // range [low, high]. inline int ClampedIntegerMax(float a, float b, int low, int high) { const float value = std::ceil(std::max(a, b)); return static_cast<int>( std::clamp(value, static_cast<float>(low), static_cast<float>(high))); } // Return true if the near plane is between the eye and the clip-space point // with the provided z and w. inline bool IsClipPointVisible(float z, float w) { return w > 0 && z >= -w; } // Computes the screen-space bounding box of the given clip-space triangle and // stores it into [left, right, bottom, top], where left and bottom limits are // inclusive while right and top are not. // Returns true if the bounding box includes any screen pixels. bool ComputeTriangleBoundingBox(float v0x, float v0y, float v0z, float v0w, float v1x, float v1y, float v1z, float v1w, float v2x, float v2y, float v2z, float v2w, int image_width, int image_height, int* left, int* right, int* bottom, int* top) { // If the triangle is entirely visible, project the vertices to pixel // coordinates and find the triangle bounding box enlarged to the nearest // integer and clamped to the image boundaries. If the triangle is not // entirely visible, intersect the edges that cross the near plane with the // near plane and use those to compute screen bounds instead. *left = image_width; *right = 0; *bottom = image_height; *top = 0; auto add_point = [&](float x, float y, float w) { const float px = 0.5f * (x / w + 1) * image_width; const float py = 0.5f * (y / w + 1) * image_height; *left = ClampedIntegerMin(*left, px, 0, image_width); *right = ClampedIntegerMax(*right, px, 0, image_width); *bottom = ClampedIntegerMin(*bottom, py, 0, image_height); *top = ClampedIntegerMax(*top, py, 0, image_height); }; auto add_near_point = [&](float x0, float y0, float z0, float w0, float x1, float y1, float z1, float w1) { const float denom = z0 - z1 + w0 - w1; if (denom != 0) { // Interpolate to near plane, where z/w == -1. const float t = (z0 + w0) / denom; const float x = x0 + t * (x1 - x0); const float y = y0 + t * (y1 - y0); const float w = w0 + t * (w1 - w0); add_point(x, y, w); } }; const bool visible_v0 = IsClipPointVisible(v0z, v0w); const bool visible_v1 = IsClipPointVisible(v1z, v1w); const bool visible_v2 = IsClipPointVisible(v2z, v2w); if (visible_v0) { add_point(v0x, v0y, v0w); if (!visible_v1) add_near_point(v0x, v0y, v0z, v0w, v1x, v1y, v1z, v1w); if (!visible_v2) add_near_point(v0x, v0y, v0z, v0w, v2x, v2y, v2z, v2w); } if (visible_v1) { add_point(v1x, v1y, v1w); if (!visible_v2) add_near_point(v1x, v1y, v1z, v1w, v2x, v2y, v2z, v2w); if (!visible_v0) add_near_point(v1x, v1y, v1z, v1w, v0x, v0y, v0z, v0w); } if (visible_v2) { add_point(v2x, v2y, v2w); if (!visible_v0) add_near_point(v2x, v2y, v2z, v2w, v0x, v0y, v0z, v0w); if (!visible_v1) add_near_point(v2x, v2y, v2z, v2w, v1x, v1y, v1z, v1w); } const bool is_valid = (*right > *left) && (*top > *bottom); return is_valid; } // Computes a 3x3 matrix inverse without dividing by the determinant. // Instead, makes an unnormalized matrix inverse with the correct sign // by flipping the sign of the matrix if the determinant is negative. // By leaving out determinant division, the rows of M^-1 only depend on two out // of three of the columns of M; i.e., the first row of M^-1 only depends on the // second and third columns of M, the second only depends on the first and // third, etc. This means we can compute edge functions for two neighboring // triangles independently and produce exactly the same numerical result up to // the sign. // See http://mathworld.wolfram.com/MatrixInverse.html // Culling is accomplished by inspecting the sign of the determinant as in: // "Incremental and Hierarchical Hilbert Order Edge Equation Polygon // Rasterization," McCool, et al., 2001 void ComputeUnnormalizedMatrixInverse( const fixed_t a11, const fixed_t a12, const fixed_t a13, const fixed_t a21, const fixed_t a22, const fixed_t a23, const fixed_t a31, const fixed_t a32, const fixed_t a33, const FaceCullingMode culling_mode, fixed_t m_inv[9]) { m_inv[0] = a22 * a33 - a32 * a23; m_inv[1] = a13 * a32 - a33 * a12; m_inv[2] = a12 * a23 - a22 * a13; m_inv[3] = a23 * a31 - a33 * a21; m_inv[4] = a11 * a33 - a31 * a13; m_inv[5] = a13 * a21 - a23 * a11; m_inv[6] = a21 * a32 - a31 * a22; m_inv[7] = a12 * a31 - a32 * a11; m_inv[8] = a11 * a22 - a21 * a12; // If the culling mode is kBack, leave the sign of the matrix unchanged. // Transfer the sign of the determinant if mode is kNone. If mode is kFront, // just invert the matrix. if (culling_mode == FaceCullingMode::kNone || culling_mode == FaceCullingMode::kFront) { // The first column of the unnormalized M^-1 contains intermediate values // for det(M). const float det = a11 * m_inv[0] + a12 * m_inv[3] + a13 * m_inv[6]; const float multiplier = (culling_mode == FaceCullingMode::kNone) ? std::copysign(1.0, det) : -1.0; for (int i = 0; i < 9; ++i) { m_inv[i] *= multiplier; } } } // Computes the edge functions from M^-1 as described by Olano and Greer, // "Triangle Scan Conversion using 2D Homogeneous Coordinates." // // This function combines equations (3) and (4). It first computes // [a b c] = u_i * M^-1, where u_0 = [1 0 0], u_1 = [0 1 0], etc., // then computes edge_i = aX + bY + c void ComputeEdgeFunctions(const float px, const float py, const fixed_t m_inv[9], fixed_t values[3]) { const fixed_t px_i = ToFixedPoint(px); const fixed_t py_i = ToFixedPoint(py); for (int i = 0; i < 3; ++i) { const fixed_t a = m_inv[3 * i + 0]; const fixed_t b = m_inv[3 * i + 1]; const fixed_t c = m_inv[3 * i + 2]; // Before summing, shift the point of c to align with the products of // multiplication. values[i] = a * px_i + b * py_i + ShiftPointLeft(c); } } // Determines whether the point p lies inside a triangle. Counts pixels exactly // on an edge as inside the triangle, as long as the triangle is not degenerate. // Degenerate (zero-area) triangles always fail the inside test. bool PixelIsInsideTriangle(const fixed_t edge_values[3]) { // Check that the edge values are all non-negative and that at least one is // positive (triangle is non-degenerate). return (edge_values[0] >= 0 && edge_values[1] >= 0 && edge_values[2] >= 0) && (edge_values[0] > 0 || edge_values[1] > 0 || edge_values[2] > 0); } } // namespace void RasterizeTrianglesImpl(const float* vertices, const int32* triangles, int32 triangle_count, int32 image_width, int32 image_height, int32 num_layers, FaceCullingMode face_culling_mode, int32* triangle_ids, float* z_buffer, float* barycentric_coordinates) { const float half_image_width = 0.5f * image_width; const float half_image_height = 0.5f * image_height; fixed_t unnormalized_matrix_inverse[9]; fixed_t b_over_w[3]; int left, right, bottom, top; for (int32 triangle_id = 0; triangle_id < triangle_count; ++triangle_id) { const int32 v0_x_id = 4 * triangles[3 * triangle_id]; const int32 v1_x_id = 4 * triangles[3 * triangle_id + 1]; const int32 v2_x_id = 4 * triangles[3 * triangle_id + 2]; const float v0x = vertices[v0_x_id]; const float v0y = vertices[v0_x_id + 1]; const float v0z = vertices[v0_x_id + 2]; const float v0w = vertices[v0_x_id + 3]; const float v1x = vertices[v1_x_id]; const float v1y = vertices[v1_x_id + 1]; const float v1z = vertices[v1_x_id + 2]; const float v1w = vertices[v1_x_id + 3]; const float v2x = vertices[v2_x_id]; const float v2y = vertices[v2_x_id + 1]; const float v2z = vertices[v2_x_id + 2]; const float v2w = vertices[v2_x_id + 3]; const bool is_valid = ComputeTriangleBoundingBox( v0x, v0y, v0z, v0w, v1x, v1y, v1z, v1w, v2x, v2y, v2z, v2w, image_width, image_height, &left, &right, &bottom, &top); // Ignore triangles that do not overlap with any screen pixels. if (!is_valid) continue; ComputeUnnormalizedMatrixInverse( ToFixedPoint(v0x), ToFixedPoint(v1x), ToFixedPoint(v2x), ToFixedPoint(v0y), ToFixedPoint(v1y), ToFixedPoint(v2y), ToFixedPoint(v0w), ToFixedPoint(v1w), ToFixedPoint(v2w), face_culling_mode, unnormalized_matrix_inverse); // Iterate over each pixel in the bounding box. for (int iy = bottom; iy < top; ++iy) { for (int ix = left; ix < right; ++ix) { const float px = ((ix + 0.5f) / half_image_width) - 1.0f; const float py = ((iy + 0.5f) / half_image_height) - 1.0f; ComputeEdgeFunctions(px, py, unnormalized_matrix_inverse, b_over_w); if (!PixelIsInsideTriangle(b_over_w)) { continue; } const float one_over_w = b_over_w[0] + b_over_w[1] + b_over_w[2]; const float b0 = b_over_w[0] / one_over_w; const float b1 = b_over_w[1] / one_over_w; const float b2 = b_over_w[2] / one_over_w; // Since we computed an unnormalized w above, we need to recompute // a properly scaled clip-space w value and then divide clip-space z // by that. const float clip_z = b0 * v0z + b1 * v1z + b2 * v2z; const float clip_w = b0 * v0w + b1 * v1w + b2 * v2w; const float z = clip_z / clip_w; // Skip the pixel if it is beyond the near or far clipping plane. if (z < -1.0f || z > 1.0f) continue; // Insert into appropriate depth layer with insertion sort. float z_next = z; int32 id_next = triangle_id; float b0_next = b0; float b1_next = b1; float b2_next = b2; const int pixel_idx0 = iy * image_width + ix; for (int layer = 0; layer < num_layers; ++layer) { const int pixel_idx = pixel_idx0 + image_height * image_width * layer; if (z_next < z_buffer[pixel_idx]) { std::swap(z_next, z_buffer[pixel_idx]); std::swap(id_next, triangle_ids[pixel_idx]); if (barycentric_coordinates != nullptr) { std::swap(b0_next, barycentric_coordinates[3 * pixel_idx + 0]); std::swap(b1_next, barycentric_coordinates[3 * pixel_idx + 1]); std::swap(b2_next, barycentric_coordinates[3 * pixel_idx + 2]); } } // Exit the loop early if the clear depth (z == 1) is reached. if (z_next == 1) break; } } } } }
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "py/tensorflow_graphics/rendering/kernels/rasterize_triangles_impl.h" #include <algorithm> #include <cmath> namespace { using fixed_t = int64; // Converts to fixed point with 16 fractional bits and 48 integer bits. // TODO(fcole): fixed-point depth may be too shallow. // The algorithm requires multiplying two of the xyzw clip-space coordinates // together, summing, and then multiplying by an NDC pixel coordinate (three // total multiplies). After three multiplications, the fractional part will be // 48 bits, leaving 16 bits for the integer part. The NDC pixel coordinates // are in (-1,1) so they need only 1 integer bit, so as long as the values of // the inverse matrix are < 2^15, the fixed-point math should not overflow. This // seems a bit dicey but so far all the tests I've tried pass. constexpr int kFractionalBits = 16; constexpr fixed_t ShiftPointLeft(fixed_t x) { return x << kFractionalBits; } constexpr fixed_t ToFixedPoint(float f) { return static_cast<fixed_t>(f * ShiftPointLeft(1)); } // Takes the minimum of a and b, rounds down, and converts to an integer in // the range [low, high]. inline int ClampedIntegerMin(float a, float b, int low, int high) { const float value = std::floor(std::min(a, b)); return static_cast<int>( std::clamp(value, static_cast<float>(low), static_cast<float>(high))); } // Takes the maximum of a and b, rounds up, and converts to an integer in the // range [low, high]. inline int ClampedIntegerMax(float a, float b, int low, int high) { const float value = std::ceil(std::max(a, b)); return static_cast<int>( std::clamp(value, static_cast<float>(low), static_cast<float>(high))); } // Return true if the near plane is between the eye and the clip-space point // with the provided z and w. inline bool IsClipPointVisible(float z, float w) { return w > 0 && z >= -w; } // Computes the screen-space bounding box of the given clip-space triangle and // stores it into [left, right, bottom, top], where left and bottom limits are // inclusive while right and top are not. // Returns true if the bounding box includes any screen pixels. bool ComputeTriangleBoundingBox(float v0x, float v0y, float v0z, float v0w, float v1x, float v1y, float v1z, float v1w, float v2x, float v2y, float v2z, float v2w, int image_width, int image_height, int* left, int* right, int* bottom, int* top) { // If the triangle is entirely visible, project the vertices to pixel // coordinates and find the triangle bounding box enlarged to the nearest // integer and clamped to the image boundaries. If the triangle is not // entirely visible, intersect the edges that cross the near plane with the // near plane and use those to compute screen bounds instead. *left = image_width; *right = 0; *bottom = image_height; *top = 0; auto add_point = [&](float x, float y, float w) { const float px = 0.5f * (x / w + 1) * image_width; const float py = 0.5f * (y / w + 1) * image_height; *left = ClampedIntegerMin(*left, px, 0, image_width); *right = ClampedIntegerMax(*right, px, 0, image_width); *bottom = ClampedIntegerMin(*bottom, py, 0, image_height); *top = ClampedIntegerMax(*top, py, 0, image_height); }; auto add_near_point = [&](float x0, float y0, float z0, float w0, float x1, float y1, float z1, float w1) { const float denom = z0 - z1 + w0 - w1; if (denom != 0) { // Interpolate to near plane, where z/w == -1. const float t = (z0 + w0) / denom; const float x = x0 + t * (x1 - x0); const float y = y0 + t * (y1 - y0); const float w = w0 + t * (w1 - w0); add_point(x, y, w); } }; const bool visible_v0 = IsClipPointVisible(v0z, v0w); const bool visible_v1 = IsClipPointVisible(v1z, v1w); const bool visible_v2 = IsClipPointVisible(v2z, v2w); if (visible_v0) { add_point(v0x, v0y, v0w); if (!visible_v1) add_near_point(v0x, v0y, v0z, v0w, v1x, v1y, v1z, v1w); if (!visible_v2) add_near_point(v0x, v0y, v0z, v0w, v2x, v2y, v2z, v2w); } if (visible_v1) { add_point(v1x, v1y, v1w); if (!visible_v2) add_near_point(v1x, v1y, v1z, v1w, v2x, v2y, v2z, v2w); if (!visible_v0) add_near_point(v1x, v1y, v1z, v1w, v0x, v0y, v0z, v0w); } if (visible_v2) { add_point(v2x, v2y, v2w); if (!visible_v0) add_near_point(v2x, v2y, v2z, v2w, v0x, v0y, v0z, v0w); if (!visible_v1) add_near_point(v2x, v2y, v2z, v2w, v1x, v1y, v1z, v1w); } const bool is_valid = (*right > *left) && (*top > *bottom); return is_valid; } // Computes a 3x3 matrix inverse without dividing by the determinant. // Instead, makes an unnormalized matrix inverse with the correct sign // by flipping the sign of the matrix if the determinant is negative. // By leaving out determinant division, the rows of M^-1 only depend on two out // of three of the columns of M; i.e., the first row of M^-1 only depends on the // second and third columns of M, the second only depends on the first and // third, etc. This means we can compute edge functions for two neighboring // triangles independently and produce exactly the same numerical result up to // the sign. // See http://mathworld.wolfram.com/MatrixInverse.html // Culling is accomplished by inspecting the sign of the determinant as in: // "Incremental and Hierarchical Hilbert Order Edge Equation Polygon // Rasterization," McCool, et al., 2001 void ComputeUnnormalizedMatrixInverse( const fixed_t a11, const fixed_t a12, const fixed_t a13, const fixed_t a21, const fixed_t a22, const fixed_t a23, const fixed_t a31, const fixed_t a32, const fixed_t a33, const FaceCullingMode culling_mode, fixed_t m_inv[9]) { m_inv[0] = a22 * a33 - a32 * a23; m_inv[1] = a13 * a32 - a33 * a12; m_inv[2] = a12 * a23 - a22 * a13; m_inv[3] = a23 * a31 - a33 * a21; m_inv[4] = a11 * a33 - a31 * a13; m_inv[5] = a13 * a21 - a23 * a11; m_inv[6] = a21 * a32 - a31 * a22; m_inv[7] = a12 * a31 - a32 * a11; m_inv[8] = a11 * a22 - a21 * a12; // If the culling mode is kBack, leave the sign of the matrix unchanged. // Transfer the sign of the determinant if mode is kNone. If mode is kFront, // just invert the matrix. if (culling_mode == FaceCullingMode::kNone || culling_mode == FaceCullingMode::kFront) { // The first column of the unnormalized M^-1 contains intermediate values // for det(M). const float det = a11 * m_inv[0] + a12 * m_inv[3] + a13 * m_inv[6]; const float multiplier = (culling_mode == FaceCullingMode::kNone) ? std::copysign(1.0, det) : -1.0; for (int i = 0; i < 9; ++i) { m_inv[i] *= multiplier; } } } // Computes the edge functions from M^-1 as described by Olano and Greer, // "Triangle Scan Conversion using 2D Homogeneous Coordinates." // // This function combines equations (3) and (4). It first computes // [a b c] = u_i * M^-1, where u_0 = [1 0 0], u_1 = [0 1 0], etc., // then computes edge_i = aX + bY + c void ComputeEdgeFunctions(const float px, const float py, const fixed_t m_inv[9], fixed_t values[3]) { const fixed_t px_i = ToFixedPoint(px); const fixed_t py_i = ToFixedPoint(py); for (int i = 0; i < 3; ++i) { const fixed_t a = m_inv[3 * i + 0]; const fixed_t b = m_inv[3 * i + 1]; const fixed_t c = m_inv[3 * i + 2]; // Before summing, shift the point of c to align with the products of // multiplication. values[i] = a * px_i + b * py_i + ShiftPointLeft(c); } } // Determines whether the point p lies inside a triangle. Counts pixels exactly // on an edge as inside the triangle, as long as the triangle is not degenerate. // Degenerate (zero-area) triangles always fail the inside test. bool PixelIsInsideTriangle(const fixed_t edge_values[3]) { // Check that the edge values are all non-negative and that at least one is // positive (triangle is non-degenerate). return (edge_values[0] >= 0 && edge_values[1] >= 0 && edge_values[2] >= 0) && (edge_values[0] > 0 || edge_values[1] > 0 || edge_values[2] > 0); } } // namespace void RasterizeTrianglesImpl(const float* vertices, const int32* triangles, int32 triangle_count, int32 image_width, int32 image_height, int32 num_layers, FaceCullingMode face_culling_mode, int32* triangle_ids, float* z_buffer, float* barycentric_coordinates) { const float half_image_width = 0.5f * image_width; const float half_image_height = 0.5f * image_height; fixed_t unnormalized_matrix_inverse[9]; fixed_t b_over_w[3]; int left, right, bottom, top; for (int32 triangle_id = 0; triangle_id < triangle_count; ++triangle_id) { const int32 v0_x_id = 4 * triangles[3 * triangle_id]; const int32 v1_x_id = 4 * triangles[3 * triangle_id + 1]; const int32 v2_x_id = 4 * triangles[3 * triangle_id + 2]; const float v0x = vertices[v0_x_id]; const float v0y = vertices[v0_x_id + 1]; const float v0z = vertices[v0_x_id + 2]; const float v0w = vertices[v0_x_id + 3]; const float v1x = vertices[v1_x_id]; const float v1y = vertices[v1_x_id + 1]; const float v1z = vertices[v1_x_id + 2]; const float v1w = vertices[v1_x_id + 3]; const float v2x = vertices[v2_x_id]; const float v2y = vertices[v2_x_id + 1]; const float v2z = vertices[v2_x_id + 2]; const float v2w = vertices[v2_x_id + 3]; const bool is_valid = ComputeTriangleBoundingBox( v0x, v0y, v0z, v0w, v1x, v1y, v1z, v1w, v2x, v2y, v2z, v2w, image_width, image_height, &left, &right, &bottom, &top); // Ignore triangles that do not overlap with any screen pixels. if (!is_valid) continue; ComputeUnnormalizedMatrixInverse( ToFixedPoint(v0x), ToFixedPoint(v1x), ToFixedPoint(v2x), ToFixedPoint(v0y), ToFixedPoint(v1y), ToFixedPoint(v2y), ToFixedPoint(v0w), ToFixedPoint(v1w), ToFixedPoint(v2w), face_culling_mode, unnormalized_matrix_inverse); // Iterate over each pixel in the bounding box. for (int iy = bottom; iy < top; ++iy) { for (int ix = left; ix < right; ++ix) { const float px = ((ix + 0.5f) / half_image_width) - 1.0f; const float py = ((iy + 0.5f) / half_image_height) - 1.0f; ComputeEdgeFunctions(px, py, unnormalized_matrix_inverse, b_over_w); if (!PixelIsInsideTriangle(b_over_w)) { continue; } const float one_over_w = b_over_w[0] + b_over_w[1] + b_over_w[2]; const float b0 = b_over_w[0] / one_over_w; const float b1 = b_over_w[1] / one_over_w; const float b2 = b_over_w[2] / one_over_w; // Since we computed an unnormalized w above, we need to recompute // a properly scaled clip-space w value and then divide clip-space z // by that. const float clip_z = b0 * v0z + b1 * v1z + b2 * v2z; const float clip_w = b0 * v0w + b1 * v1w + b2 * v2w; const float z = clip_z / clip_w; // Skip the pixel if it is beyond the near or far clipping plane. if (z < -1.0f || z > 1.0f) continue; // Insert into appropriate depth layer with insertion sort. float z_next = z; int32 id_next = triangle_id; float b0_next = b0; float b1_next = b1; float b2_next = b2; const int pixel_idx0 = iy * image_width + ix; for (int layer = 0; layer < num_layers; ++layer) { const int pixel_idx = pixel_idx0 + image_height * image_width * layer; if (z_next < z_buffer[pixel_idx]) { std::swap(z_next, z_buffer[pixel_idx]); std::swap(id_next, triangle_ids[pixel_idx]); if (barycentric_coordinates != nullptr) { std::swap(b0_next, barycentric_coordinates[3 * pixel_idx + 0]); std::swap(b1_next, barycentric_coordinates[3 * pixel_idx + 1]); std::swap(b2_next, barycentric_coordinates[3 * pixel_idx + 2]); } } // Exit the loop early if the clear depth (z == 1) is reached. if (z_next == 1) break; } } } } }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/shapenet/fakes/02691156/3d5354863690ac7eca27bba175814d1/models/model_normalized.obj
# Test data. # g tetrahedron v 1.00 1.00 1.00 v 2.00 1.00 1.00 v 1.00 2.00 1.00 v 1.00 1.00 2.00 f 1 3 2 f 1 4 3 f 1 2 4 f 2 3 4
# Test data. # g tetrahedron v 1.00 1.00 1.00 v 2.00 1.00 1.00 v 1.00 2.00 1.00 v 1.00 1.00 2.00 f 1 3 2 f 1 4 3 f 1 2 4 f 2 3 4
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./.git/ORIG_HEAD
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/neural_voxel_renderer/helpers.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions for neural voxel renderer +.""" import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import grid from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math.interpolation import trilinear from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.voxels import emission_absorption X_AXIS = np.array((1., 0., 0.), dtype=np.float32) Z_AXIS = np.array((0., 0., 1.), dtype=np.float32) PI = np.array((-np.pi,), dtype=np.float32) PI_2 = np.array((-np.pi/2.,), dtype=np.float32) ZERO = np.array((0.,), dtype=np.float32) MIRROR_X_MATRIX = np.eye(3, dtype=np.float32) MIRROR_X_MATRIX[0, 0] = -1 # Cube that encloses all the shapes in the dataset (world coordinates) CUBE_BOX_DIM = 1.1528184 # The bottom part of all shapes in world coordinates OBJECT_BOTTOM = -1.1167929 def generate_ground_image(height, width, focal, principal_point, camera_rotation_matrix, camera_translation_vector, ground_color=(0.43, 0.43, 0.8)): """Generate an image depicting only the ground.""" batch_size = camera_rotation_matrix.shape[0] background_image = np.ones((batch_size, height, width, 1, 1), dtype=np.float32) background_image[:, -1, ...] = 0 # Zero the bottom line for proper sampling # The projection of the ground depends on the top right corner (approximation) plane_point_np = np.tile(np.array([[3.077984, 2.905388, 0.]], dtype=np.float32), (batch_size, 1)) plane_point_rotated = rotation_matrix_3d.rotate(plane_point_np, camera_rotation_matrix) plane_point_translated = plane_point_rotated + camera_translation_vector plane_point2d = \ perspective.project(plane_point_translated, focal, principal_point) _, y = tf.split(plane_point2d, [1, 1], axis=-1) sfactor = height/y helper_matrix1 = np.tile(np.array([[[1, 0, 0], [0, 0, 0], [0, 0, 0]]]), (batch_size, 1, 1)) helper_matrix2 = np.tile(np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 1]]]), (batch_size, 1, 1)) transformation_matrix = tf.multiply(tf.expand_dims(sfactor, -1), helper_matrix1) + helper_matrix2 plane_points = grid.generate((0., 0., 0.), (float(height), float(width), 0.), (height, width, 1)) plane_points = tf.reshape(plane_points, [-1, 3]) transf_plane_points = tf.matmul(transformation_matrix, plane_points, transpose_b=True) interpolated_points = \ trilinear.interpolate(background_image, tf.linalg.matrix_transpose(transf_plane_points)) ground_alpha = (1- tf.reshape(interpolated_points, [batch_size, height, width, 1])) ground_image = tf.ones((batch_size, height, width, 3))*ground_color return ground_image, ground_alpha def sampling_points_to_voxel_index(sampling_points, voxel_size): """Transforms the sampling points from [-1, 1] to [0, voxel_size].""" voxel_size = tf.convert_to_tensor(value=voxel_size) max_size = tf.cast(voxel_size - 1, sampling_points.dtype) return 0.5 * ((sampling_points + 1) * max_size) def sampling_points_from_3d_grid(grid_size, dtype=tf.float32): """Returns a tensor of shape `[M, 3]`, with M the number of sampling points.""" sampling_points = grid.generate((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0), grid_size) sampling_points = tf.cast(sampling_points, dtype) return tf.reshape(sampling_points, [-1, 3]) def sampling_points_from_frustum(height, width, focal, principal_point, depth_min=0.0, depth_max=5., frustum_size=(256, 256, 256)): """Generates samples from a camera frustum.""" # ------------------ Get the rays from the camera ---------------------------- sampling_points = grid.generate((0., 0.), (float(width)-1, float(height)-1), (frustum_size[0], frustum_size[1])) sampling_points = tf.reshape(sampling_points, [-1, 2]) # [h*w, 2] rays = perspective.ray(sampling_points, focal, principal_point) # [h*w, 3] # ------------------ Extract a volume in front of the camera ----------------- depth_tensor = grid.generate((depth_min,), (depth_max,), (frustum_size[2],)) sampling_volume = tf.multiply(tf.expand_dims(rays, axis=-1), tf.transpose(depth_tensor)) # [h*w, 3, dstep] sampling_volume = tf.transpose(sampling_volume, [0, 2, 1]) # [h*w, dstep, 3] sampling_volume = tf.reshape(sampling_volume, [-1, 3]) # [h*w*dstep, 3] return sampling_volume def place_frustum_sampling_points_at_blender_camera(sampling_points, camera_rotation_matrix, camera_translation_vector): """Transform the TF-Graphics frustum points to the blender camera position.""" blender_rotation_matrix = rotation_matrix_3d.from_axis_angle(X_AXIS, -PI) camera_translation_vector = tf.matmul(blender_rotation_matrix, camera_translation_vector) # The original frustum points are mirrored in the x axis and rotated 270 mirror_x_matrix = tf.convert_to_tensor(MIRROR_X_MATRIX) up_rotation_matrix = rotation_matrix_3d.from_axis_angle(Z_AXIS, 3*PI_2) local_camera_transform = tf.matmul(mirror_x_matrix, up_rotation_matrix) sampling_points = tf.matmul(local_camera_transform, sampling_points, transpose_b=True) sampling_points = \ tf.matmul(tf.linalg.matrix_transpose(camera_rotation_matrix), sampling_points+camera_translation_vector) return tf.linalg.matrix_transpose(sampling_points) # [h*w*dstep, 3] def transform_volume(voxels, transformation_matrix, voxel_size=(128, 128, 128)): """Apply a transformation to the input voxels.""" voxels = tf.convert_to_tensor(voxels) volume_sampling = sampling_points_from_3d_grid(voxel_size) volume_sampling = tf.matmul(transformation_matrix, tf.transpose(a=volume_sampling)) volume_sampling = tf.cast(tf.linalg.matrix_transpose(volume_sampling), tf.float32) volume_sampling = sampling_points_to_voxel_index(volume_sampling, voxel_size) interpolated_voxels = trilinear.interpolate(voxels, volume_sampling) return tf.reshape(interpolated_voxels, tf.shape(voxels)) def object_rotation_in_blender_world(voxels, object_rotation): """Rotate the voxels as in blender world.""" euler_angles = np.array([0, 0, 1], dtype=np.float32)*np.deg2rad(90) object_correction_matrix = rotation_matrix_3d.from_euler(euler_angles) euler_angles = np.array([0, 1, 0], dtype=np.float32)*(-object_rotation) object_rotation_matrix = rotation_matrix_3d.from_euler(euler_angles) euler_angles_blender = np.array([1, 0, 0], dtype=np.float32)*np.deg2rad(-90) blender_object_correction_matrix = \ rotation_matrix_3d.from_euler(euler_angles_blender) transformation_matrix = tf.matmul(tf.matmul(object_correction_matrix, object_rotation_matrix), blender_object_correction_matrix) return transform_volume(voxels, transformation_matrix) def render_voxels_from_blender_camera(voxels, object_rotation, object_translation, height, width, focal, principal_point, camera_rotation_matrix, camera_translation_vector, frustum_size=(256, 256, 512), absorption_factor=0.1, cell_size=1.0, depth_min=0.0, depth_max=5.0): """Renders the voxels according to their position in the world.""" batch_size = voxels.shape[0] voxel_size = voxels.shape[1] sampling_volume = sampling_points_from_frustum(height, width, focal, principal_point, depth_min=depth_min, depth_max=depth_max, frustum_size=frustum_size) sampling_volume = \ place_frustum_sampling_points_at_blender_camera(sampling_volume, camera_rotation_matrix, camera_translation_vector) interpolated_voxels = \ object_rotation_in_blender_world(voxels, object_rotation) # Adjust the camera (translate the camera instead of the object) sampling_volume = sampling_volume - object_translation sampling_volume = sampling_volume/CUBE_BOX_DIM sampling_volume = sampling_points_to_voxel_index(sampling_volume, voxel_size) camera_voxels = trilinear.interpolate(interpolated_voxels, sampling_volume) camera_voxels = tf.reshape(camera_voxels, [batch_size] + list(frustum_size) + [4]) voxel_image = emission_absorption.render(camera_voxels, absorption_factor=absorption_factor, cell_size=cell_size) return voxel_image def object_to_world(voxels, euler_angles_x, euler_angles_y, translation_vector, target_volume_size=(128, 128, 128)): """Apply the transformations to the voxels and place them in world coords.""" scale_factor = 1.82 # object to world voxel space scale factor translation_vector = tf.expand_dims(translation_vector, axis=-1) sampling_points = tf.cast(sampling_points_from_3d_grid(target_volume_size), tf.float32) # 128^3 X 3 transf_matrix_x = rotation_matrix_3d.from_euler(euler_angles_x) # [B, 3, 3] transf_matrix_y = rotation_matrix_3d.from_euler(euler_angles_y) # [B, 3, 3] transf_matrix = tf.matmul(transf_matrix_x, transf_matrix_y) # [B, 3, 3] transf_matrix = transf_matrix*scale_factor # [B, 3, 3] sampling_points = tf.matmul(transf_matrix, tf.transpose(sampling_points)) # [B, 3, N] translation_vector = tf.matmul(transf_matrix, translation_vector) # [B, 3, 1] sampling_points = sampling_points - translation_vector sampling_points = tf.linalg.matrix_transpose(sampling_points) sampling_points = sampling_points_to_voxel_index(sampling_points, target_volume_size) sampling_points = tf.cast(sampling_points, tf.float32) interpolated_points = trilinear.interpolate(voxels, sampling_points) interpolated_voxels = tf.reshape(interpolated_points, [-1] + list(target_volume_size)+[4]) return interpolated_voxels
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper functions for neural voxel renderer +.""" import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import grid from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math.interpolation import trilinear from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.voxels import emission_absorption X_AXIS = np.array((1., 0., 0.), dtype=np.float32) Z_AXIS = np.array((0., 0., 1.), dtype=np.float32) PI = np.array((-np.pi,), dtype=np.float32) PI_2 = np.array((-np.pi/2.,), dtype=np.float32) ZERO = np.array((0.,), dtype=np.float32) MIRROR_X_MATRIX = np.eye(3, dtype=np.float32) MIRROR_X_MATRIX[0, 0] = -1 # Cube that encloses all the shapes in the dataset (world coordinates) CUBE_BOX_DIM = 1.1528184 # The bottom part of all shapes in world coordinates OBJECT_BOTTOM = -1.1167929 def generate_ground_image(height, width, focal, principal_point, camera_rotation_matrix, camera_translation_vector, ground_color=(0.43, 0.43, 0.8)): """Generate an image depicting only the ground.""" batch_size = camera_rotation_matrix.shape[0] background_image = np.ones((batch_size, height, width, 1, 1), dtype=np.float32) background_image[:, -1, ...] = 0 # Zero the bottom line for proper sampling # The projection of the ground depends on the top right corner (approximation) plane_point_np = np.tile(np.array([[3.077984, 2.905388, 0.]], dtype=np.float32), (batch_size, 1)) plane_point_rotated = rotation_matrix_3d.rotate(plane_point_np, camera_rotation_matrix) plane_point_translated = plane_point_rotated + camera_translation_vector plane_point2d = \ perspective.project(plane_point_translated, focal, principal_point) _, y = tf.split(plane_point2d, [1, 1], axis=-1) sfactor = height/y helper_matrix1 = np.tile(np.array([[[1, 0, 0], [0, 0, 0], [0, 0, 0]]]), (batch_size, 1, 1)) helper_matrix2 = np.tile(np.array([[[0, 0, 0], [0, 1, 0], [0, 0, 1]]]), (batch_size, 1, 1)) transformation_matrix = tf.multiply(tf.expand_dims(sfactor, -1), helper_matrix1) + helper_matrix2 plane_points = grid.generate((0., 0., 0.), (float(height), float(width), 0.), (height, width, 1)) plane_points = tf.reshape(plane_points, [-1, 3]) transf_plane_points = tf.matmul(transformation_matrix, plane_points, transpose_b=True) interpolated_points = \ trilinear.interpolate(background_image, tf.linalg.matrix_transpose(transf_plane_points)) ground_alpha = (1- tf.reshape(interpolated_points, [batch_size, height, width, 1])) ground_image = tf.ones((batch_size, height, width, 3))*ground_color return ground_image, ground_alpha def sampling_points_to_voxel_index(sampling_points, voxel_size): """Transforms the sampling points from [-1, 1] to [0, voxel_size].""" voxel_size = tf.convert_to_tensor(value=voxel_size) max_size = tf.cast(voxel_size - 1, sampling_points.dtype) return 0.5 * ((sampling_points + 1) * max_size) def sampling_points_from_3d_grid(grid_size, dtype=tf.float32): """Returns a tensor of shape `[M, 3]`, with M the number of sampling points.""" sampling_points = grid.generate((-1.0, -1.0, -1.0), (1.0, 1.0, 1.0), grid_size) sampling_points = tf.cast(sampling_points, dtype) return tf.reshape(sampling_points, [-1, 3]) def sampling_points_from_frustum(height, width, focal, principal_point, depth_min=0.0, depth_max=5., frustum_size=(256, 256, 256)): """Generates samples from a camera frustum.""" # ------------------ Get the rays from the camera ---------------------------- sampling_points = grid.generate((0., 0.), (float(width)-1, float(height)-1), (frustum_size[0], frustum_size[1])) sampling_points = tf.reshape(sampling_points, [-1, 2]) # [h*w, 2] rays = perspective.ray(sampling_points, focal, principal_point) # [h*w, 3] # ------------------ Extract a volume in front of the camera ----------------- depth_tensor = grid.generate((depth_min,), (depth_max,), (frustum_size[2],)) sampling_volume = tf.multiply(tf.expand_dims(rays, axis=-1), tf.transpose(depth_tensor)) # [h*w, 3, dstep] sampling_volume = tf.transpose(sampling_volume, [0, 2, 1]) # [h*w, dstep, 3] sampling_volume = tf.reshape(sampling_volume, [-1, 3]) # [h*w*dstep, 3] return sampling_volume def place_frustum_sampling_points_at_blender_camera(sampling_points, camera_rotation_matrix, camera_translation_vector): """Transform the TF-Graphics frustum points to the blender camera position.""" blender_rotation_matrix = rotation_matrix_3d.from_axis_angle(X_AXIS, -PI) camera_translation_vector = tf.matmul(blender_rotation_matrix, camera_translation_vector) # The original frustum points are mirrored in the x axis and rotated 270 mirror_x_matrix = tf.convert_to_tensor(MIRROR_X_MATRIX) up_rotation_matrix = rotation_matrix_3d.from_axis_angle(Z_AXIS, 3*PI_2) local_camera_transform = tf.matmul(mirror_x_matrix, up_rotation_matrix) sampling_points = tf.matmul(local_camera_transform, sampling_points, transpose_b=True) sampling_points = \ tf.matmul(tf.linalg.matrix_transpose(camera_rotation_matrix), sampling_points+camera_translation_vector) return tf.linalg.matrix_transpose(sampling_points) # [h*w*dstep, 3] def transform_volume(voxels, transformation_matrix, voxel_size=(128, 128, 128)): """Apply a transformation to the input voxels.""" voxels = tf.convert_to_tensor(voxels) volume_sampling = sampling_points_from_3d_grid(voxel_size) volume_sampling = tf.matmul(transformation_matrix, tf.transpose(a=volume_sampling)) volume_sampling = tf.cast(tf.linalg.matrix_transpose(volume_sampling), tf.float32) volume_sampling = sampling_points_to_voxel_index(volume_sampling, voxel_size) interpolated_voxels = trilinear.interpolate(voxels, volume_sampling) return tf.reshape(interpolated_voxels, tf.shape(voxels)) def object_rotation_in_blender_world(voxels, object_rotation): """Rotate the voxels as in blender world.""" euler_angles = np.array([0, 0, 1], dtype=np.float32)*np.deg2rad(90) object_correction_matrix = rotation_matrix_3d.from_euler(euler_angles) euler_angles = np.array([0, 1, 0], dtype=np.float32)*(-object_rotation) object_rotation_matrix = rotation_matrix_3d.from_euler(euler_angles) euler_angles_blender = np.array([1, 0, 0], dtype=np.float32)*np.deg2rad(-90) blender_object_correction_matrix = \ rotation_matrix_3d.from_euler(euler_angles_blender) transformation_matrix = tf.matmul(tf.matmul(object_correction_matrix, object_rotation_matrix), blender_object_correction_matrix) return transform_volume(voxels, transformation_matrix) def render_voxels_from_blender_camera(voxels, object_rotation, object_translation, height, width, focal, principal_point, camera_rotation_matrix, camera_translation_vector, frustum_size=(256, 256, 512), absorption_factor=0.1, cell_size=1.0, depth_min=0.0, depth_max=5.0): """Renders the voxels according to their position in the world.""" batch_size = voxels.shape[0] voxel_size = voxels.shape[1] sampling_volume = sampling_points_from_frustum(height, width, focal, principal_point, depth_min=depth_min, depth_max=depth_max, frustum_size=frustum_size) sampling_volume = \ place_frustum_sampling_points_at_blender_camera(sampling_volume, camera_rotation_matrix, camera_translation_vector) interpolated_voxels = \ object_rotation_in_blender_world(voxels, object_rotation) # Adjust the camera (translate the camera instead of the object) sampling_volume = sampling_volume - object_translation sampling_volume = sampling_volume/CUBE_BOX_DIM sampling_volume = sampling_points_to_voxel_index(sampling_volume, voxel_size) camera_voxels = trilinear.interpolate(interpolated_voxels, sampling_volume) camera_voxels = tf.reshape(camera_voxels, [batch_size] + list(frustum_size) + [4]) voxel_image = emission_absorption.render(camera_voxels, absorption_factor=absorption_factor, cell_size=cell_size) return voxel_image def object_to_world(voxels, euler_angles_x, euler_angles_y, translation_vector, target_volume_size=(128, 128, 128)): """Apply the transformations to the voxels and place them in world coords.""" scale_factor = 1.82 # object to world voxel space scale factor translation_vector = tf.expand_dims(translation_vector, axis=-1) sampling_points = tf.cast(sampling_points_from_3d_grid(target_volume_size), tf.float32) # 128^3 X 3 transf_matrix_x = rotation_matrix_3d.from_euler(euler_angles_x) # [B, 3, 3] transf_matrix_y = rotation_matrix_3d.from_euler(euler_angles_y) # [B, 3, 3] transf_matrix = tf.matmul(transf_matrix_x, transf_matrix_y) # [B, 3, 3] transf_matrix = transf_matrix*scale_factor # [B, 3, 3] sampling_points = tf.matmul(transf_matrix, tf.transpose(sampling_points)) # [B, 3, N] translation_vector = tf.matmul(transf_matrix, translation_vector) # [B, 3, 1] sampling_points = sampling_points - translation_vector sampling_points = tf.linalg.matrix_transpose(sampling_points) sampling_points = sampling_points_to_voxel_index(sampling_points, target_volume_size) sampling_points = tf.cast(sampling_points, tf.float32) interpolated_points = trilinear.interpolate(voxels, sampling_points) interpolated_voxels = tf.reshape(interpolated_points, [-1] + list(target_volume_size)+[4]) return interpolated_voxels
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/tests/linear_blend_skinning_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for linear blend skinning.""" # pylint: disable=line-too-long from absl.testing import flagsaver from absl.testing import parameterized import tensorflow as tf from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class LinearBlendSkinningTest(test_case.TestCase): # pyformat: disable @parameterized.parameters( ((3,), (7,), (7, 3, 3), (7, 3)), ((None, 3), (None, 9), (None, 9, 3, 3), (None, 9, 3)), ((7, 1, 3), (1, 4, 11), (5, 11, 3, 3), (1, 11, 3)), ((7, 4, 3), (4, 11), (11, 3, 3), (11, 3)), ((3,), (5, 4, 11), (11, 3, 3), (11, 3)), ) # pyformat: enable def test_blend_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(linear_blend_skinning.blend, shapes) # pyformat: disable @parameterized.parameters( ("points must have exactly 3 dimensions in axis -1", (None,), (7,), (7, 3, 3), (7, 3)), ("bone_rotations must have a rank greater than 2", (3,), (7,), (3, 3), (3,)), ("bone_rotations must have exactly 3 dimensions in axis -1", (3,), (7,), (7, 3, None), (7, 3)), ("bone_rotations must have exactly 3 dimensions in axis -2", (3,), (7,), (7, None, 3), (7, 3)), ("bone_translations must have a rank greater than 1", (3,), (7,), (7, 3, 3), (3,)), ("bone_translations must have exactly 3 dimensions in axis -1", (3,), (7,), (7, 3, 3), (7, None)), (r"Tensors \[\'skinning_weights\', \'bone_rotations\'\] must have the same number of dimensions in axes", (3,), (9,), (7, 3, 3), (9, 3)), (r"Tensors \[\'skinning_weights\', \'bone_translations\'\] must have the same number of dimensions in axes", (3,), (9,), (9, 3, 3), (7, 3)), ("Not all batch dimensions are broadcast-compatible", (2, 3, 3), (3, 1, 7), (7, 3, 3), (7, 3)), ("Not all batch dimensions are broadcast-compatible", (2, 3, 3), (2, 1, 7), (3, 7, 3, 3), (2, 7, 3)), ) # pyformat: enable def test_blend_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(linear_blend_skinning.blend, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_blend_jacobian_random(self): """Test the Jacobian of the blend function.""" (x_points_init, x_weights_init, x_rotations_init, x_translations_init) = test_helpers.generate_random_test_lbs_blend() self.assert_jacobian_is_correct_fn( linear_blend_skinning.blend, [x_points_init, x_weights_init, x_rotations_init, x_translations_init]) def test_blend_preset(self): """Checks that blend returns the expected value.""" (x_points_init, x_weights_init, x_rotations_init, x_translations_init, y_blended_points_init) = test_helpers.generate_preset_test_lbs_blend() x_points = tf.convert_to_tensor(value=x_points_init) x_weights = tf.convert_to_tensor(value=x_weights_init) x_rotations = tf.convert_to_tensor(value=x_rotations_init) x_translations = tf.convert_to_tensor(value=x_translations_init) y_blended_points = tf.convert_to_tensor(value=y_blended_points_init) y = linear_blend_skinning.blend(x_points, x_weights, x_rotations, x_translations) self.assertAllClose(y_blended_points, y) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for linear blend skinning.""" # pylint: disable=line-too-long from absl.testing import flagsaver from absl.testing import parameterized import tensorflow as tf from tensorflow_graphics.geometry.transformation import linear_blend_skinning from tensorflow_graphics.geometry.transformation.tests import test_helpers from tensorflow_graphics.util import test_case class LinearBlendSkinningTest(test_case.TestCase): # pyformat: disable @parameterized.parameters( ((3,), (7,), (7, 3, 3), (7, 3)), ((None, 3), (None, 9), (None, 9, 3, 3), (None, 9, 3)), ((7, 1, 3), (1, 4, 11), (5, 11, 3, 3), (1, 11, 3)), ((7, 4, 3), (4, 11), (11, 3, 3), (11, 3)), ((3,), (5, 4, 11), (11, 3, 3), (11, 3)), ) # pyformat: enable def test_blend_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(linear_blend_skinning.blend, shapes) # pyformat: disable @parameterized.parameters( ("points must have exactly 3 dimensions in axis -1", (None,), (7,), (7, 3, 3), (7, 3)), ("bone_rotations must have a rank greater than 2", (3,), (7,), (3, 3), (3,)), ("bone_rotations must have exactly 3 dimensions in axis -1", (3,), (7,), (7, 3, None), (7, 3)), ("bone_rotations must have exactly 3 dimensions in axis -2", (3,), (7,), (7, None, 3), (7, 3)), ("bone_translations must have a rank greater than 1", (3,), (7,), (7, 3, 3), (3,)), ("bone_translations must have exactly 3 dimensions in axis -1", (3,), (7,), (7, 3, 3), (7, None)), (r"Tensors \[\'skinning_weights\', \'bone_rotations\'\] must have the same number of dimensions in axes", (3,), (9,), (7, 3, 3), (9, 3)), (r"Tensors \[\'skinning_weights\', \'bone_translations\'\] must have the same number of dimensions in axes", (3,), (9,), (9, 3, 3), (7, 3)), ("Not all batch dimensions are broadcast-compatible", (2, 3, 3), (3, 1, 7), (7, 3, 3), (7, 3)), ("Not all batch dimensions are broadcast-compatible", (2, 3, 3), (2, 1, 7), (3, 7, 3, 3), (2, 7, 3)), ) # pyformat: enable def test_blend_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(linear_blend_skinning.blend, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_blend_jacobian_random(self): """Test the Jacobian of the blend function.""" (x_points_init, x_weights_init, x_rotations_init, x_translations_init) = test_helpers.generate_random_test_lbs_blend() self.assert_jacobian_is_correct_fn( linear_blend_skinning.blend, [x_points_init, x_weights_init, x_rotations_init, x_translations_init]) def test_blend_preset(self): """Checks that blend returns the expected value.""" (x_points_init, x_weights_init, x_rotations_init, x_translations_init, y_blended_points_init) = test_helpers.generate_preset_test_lbs_blend() x_points = tf.convert_to_tensor(value=x_points_init) x_weights = tf.convert_to_tensor(value=x_weights_init) x_rotations = tf.convert_to_tensor(value=x_rotations_init) x_translations = tf.convert_to_tensor(value=x_translations_init) y_blended_points = tf.convert_to_tensor(value=y_blended_points_init) y = linear_blend_skinning.blend(x_points, x_weights, x_rotations, x_translations) self.assertAllClose(y_blended_points, y) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./submodules/README.md
# Submodules If you are conducting research / development and would like to open-source deep-learning based solutions for problems making use of 3D / computer graphics techniques, we would love to host your project in TensorFlow Graphics! In order to provide you with both flexibility and visibility, the preferred setup will be to have your project as a git submodule under **tensorflow_graphics/submodules/PROJECT_NAME**. As a project owner, you set the bar in terms of code quality, style, and tests. The only requirement is a description of your project and how to use it inside **tensorflow_graphics/submodules/PROJECT_NAME/README.md**. If your project is linked to a publication, make sure to also include a link to the paper and a bibtex describing how to cite your work. If you have specific needs or requests, feel free to contact us at tf-graphics-contact@google.com; we would love to work with you to find a solution that fits your project!
# Submodules If you are conducting research / development and would like to open-source deep-learning based solutions for problems making use of 3D / computer graphics techniques, we would love to host your project in TensorFlow Graphics! In order to provide you with both flexibility and visibility, the preferred setup will be to have your project as a git submodule under **tensorflow_graphics/submodules/PROJECT_NAME**. As a project owner, you set the bar in terms of code quality, style, and tests. The only requirement is a description of your project and how to use it inside **tensorflow_graphics/submodules/PROJECT_NAME/README.md**. If your project is linked to a publication, make sure to also include a link to the paper and a bibtex describing how to cite your work. If you have specific needs or requests, feel free to contact us at tf-graphics-contact@google.com; we would love to work with you to find a solution that fits your project!
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/local_implicit_grid/resample_geometry.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Compute point samples from a mesh after normalizing its scale.""" import os from absl import app from absl import flags import numpy as np from tensorflow_graphics.projects.local_implicit_grid.core import point_utils as pu import trimesh os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags.DEFINE_string('input_mesh', '', 'Input geometry file. Must be a trimesh supported type') flags.DEFINE_string('output_ply', '', 'Samples points ply file.') flags.DEFINE_float('sampling_density', 2e-4, 'Approx surface area based point sampling density.') FLAGS = flags.FLAGS def normalize_mesh(mesh, in_place=True): """Rescales vertex positions to lie inside unit cube.""" scale = 1.0 / np.max(mesh.bounds[1, :] - mesh.bounds[0, :]) centroid = mesh.centroid scaled_vertices = (mesh.vertices - centroid) * scale if in_place: scaled_mesh = mesh scaled_mesh.vertices = scaled_vertices else: scaled_mesh = mesh.copy() scaled_mesh.vertices = scaled_vertices scaled_mesh.fix_normals() return scaled_mesh def sample_mesh(mesh): """Samples oriented points from a mesh.""" num_samples = int(mesh.area / FLAGS.sampling_density) sample_pts, sample_face_ids = trimesh.sample.sample_surface(mesh, num_samples) sample_normals = mesh.face_normals[sample_face_ids] return sample_pts, sample_normals def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') if not FLAGS.input_mesh: raise IOError('--input_mesh must be specified.') if not FLAGS.output_ply: raise IOError('--output_ply must be specified.') mesh = trimesh.load(FLAGS.input_mesh) mesh = normalize_mesh(mesh) sample_pts, sample_normals = sample_mesh(mesh) print('Computed {} samples from mesh.'.format(sample_pts.shape[0])) print('Writing sampled points to {}'.format(FLAGS.output_ply)) pu.write_point_ply(FLAGS.output_ply, sample_pts, sample_normals) if __name__ == '__main__': app.run(main)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Compute point samples from a mesh after normalizing its scale.""" import os from absl import app from absl import flags import numpy as np from tensorflow_graphics.projects.local_implicit_grid.core import point_utils as pu import trimesh os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags.DEFINE_string('input_mesh', '', 'Input geometry file. Must be a trimesh supported type') flags.DEFINE_string('output_ply', '', 'Samples points ply file.') flags.DEFINE_float('sampling_density', 2e-4, 'Approx surface area based point sampling density.') FLAGS = flags.FLAGS def normalize_mesh(mesh, in_place=True): """Rescales vertex positions to lie inside unit cube.""" scale = 1.0 / np.max(mesh.bounds[1, :] - mesh.bounds[0, :]) centroid = mesh.centroid scaled_vertices = (mesh.vertices - centroid) * scale if in_place: scaled_mesh = mesh scaled_mesh.vertices = scaled_vertices else: scaled_mesh = mesh.copy() scaled_mesh.vertices = scaled_vertices scaled_mesh.fix_normals() return scaled_mesh def sample_mesh(mesh): """Samples oriented points from a mesh.""" num_samples = int(mesh.area / FLAGS.sampling_density) sample_pts, sample_face_ids = trimesh.sample.sample_surface(mesh, num_samples) sample_normals = mesh.face_normals[sample_face_ids] return sample_pts, sample_normals def main(argv): if len(argv) > 1: raise app.UsageError('Too many command-line arguments.') if not FLAGS.input_mesh: raise IOError('--input_mesh must be specified.') if not FLAGS.output_ply: raise IOError('--output_ply must be specified.') mesh = trimesh.load(FLAGS.input_mesh) mesh = normalize_mesh(mesh) sample_pts, sample_normals = sample_mesh(mesh) print('Computed {} samples from mesh.'.format(sample_pts.shape[0])) print('Writing sampled points to {}'.format(FLAGS.output_ply)) pu.write_point_ply(FLAGS.output_ply, sample_pts, sample_normals) if __name__ == '__main__': app.run(main)
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/pix3d/fakes/model/bed/IKEA_MALM_3/model.obj
mtllib malm_bed_3_obj0_object.mtl g Mesh1 Group2 Group1 Model usemtl matress_white v -0.276638255695 -0.0620432731089 -0.340973939036 vt -15.199 12.4604 v -0.276638255695 -0.0581013347333 -0.344915788592 vt -14.7934 12.9394 v -0.279749634468 -0.0581013347333 -0.340973939036 vt -15.279 12.9394 f 1/1 2/2 3/3 vt -25.6116 14.4245 v -0.271215769996 -0.0581013347333 -0.347965437183 vt -24.8122 14.968 vt -25.2978 14.968 f 1/4 4/5 2/6 v -0.264207840075 -0.0620432731089 -0.347965437183 vt -24.4983 14.4245 f 4/5 1/4 5/7 vt -25.6116 14.4245 v -0.267711805035 -0.065093099341 -0.342944863814 vt -25.055 14.0039 vt -24.4983 14.4245 f 1/8 6/9 5/10 vt -25.6116 14.4245 v -0.271215769996 -0.065093099341 -0.340973939036 vt -25.3688 14.0039 vt -25.055 14.0039 f 1/11 7/12 6/13 v -0.276638255695 -0.0620432731089 0.34091540639 vt -77.7559 25.2978 vt -0.984252 24.8122 vt -0.984252 25.2978 f 8/14 7/15 1/16 v -0.271215769996 -0.065093099341 0.34091540639 vt -77.7559 24.8122 f 7/15 8/14 9/17 vt -30.0661 46.57 v -0.267711805035 -0.065093099341 0.342886331167 vt -30.6227 46.1495 vt -30.3089 46.1495 f 8/18 10/19 9/20 vt -30.0661 46.57 v -0.264207840075 -0.0620432731089 0.347907348639 vt -31.1794 46.57 vt -30.6227 46.1495 f 8/21 11/22 10/23 vt -30.0661 46.57 v -0.271215769996 -0.0581013347333 0.347907348639 vt -30.8655 47.1136 vt -31.1794 46.57 f 8/24 12/25 11/26 v -0.276638255695 -0.0581013347333 0.344857255945 vt -30.3799 47.1136 f 12/25 8/24 13/27 vt -57.1715 24.9552 vt -56.7659 24.4763 v -0.279749634468 -0.0581013347333 0.34091540639 vt -56.6859 24.9552 f 13/28 8/29 14/30 vt -0.984252 14.7934 vt -77.7559 15.279 vt -77.7559 14.7934 f 1/31 14/32 8/33 vt -0.984252 15.279 f 14/32 1/31 3/34 vt -0.984252 0.984252 v -0.279749634468 -0.0351453458881 0.34091540639 vt -77.7559 3.56882 vt -77.7559 0.984252 f 3/35 15/36 14/37 v -0.279749634468 -0.0351453458881 -0.340973939036 vt -0.984252 3.56882 f 15/36 3/35 16/38 vt -14.7934 0.984252 vt -15.279 3.56882 vt -15.279 0.984252 f 2/39 16/40 3/41 v -0.276638255695 -0.0351453458881 -0.344915788592 vt -14.7934 3.56882 f 16/40 2/39 17/42 vt -24.8122 0.984252 vt -25.2978 3.56882 vt -25.2978 0.984252 f 4/43 17/44 2/45 v -0.271215769996 -0.0351453458881 -0.347965437183 vt -24.8122 3.56882 f 17/44 4/43 18/46 vt -31.9702 0.984252 v -0.264207840075 -0.0351453458881 -0.349715732076 vt -31.4846 3.56882 vt -31.9702 3.56882 f 4/47 19/48 18/49 v -0.264207840075 -0.0581013347333 -0.349715732076 vt -31.4846 0.984252 f 19/48 4/47 20/50 vt -31.9702 6.16896 vt -31.5646 5.68999 vt -31.4846 6.16896 f 4/51 5/52 20/53 vt -34.4488 0.413961 v 0.264206951871 -0.0581013347333 -0.349715732076 vt -0.984252 0.899561 vt -34.4488 0.899561 f 5/54 21/55 20/56 v 0.264206951871 -0.0620432731089 -0.347965437183 vt -0.984252 0.413961 f 21/55 5/54 22/57 v -0.264207840075 -0.065093099341 -0.344915788592 vt -34.4488 -0.2428 vt -0.984252 0.2428 vt -34.4488 0.2428 f 23/58 22/59 5/60 v 0.264206951871 -0.065093099341 -0.344915788592 vt -0.984252 -0.2428 f 22/59 23/58 24/61 vt -34.4488 -0.413961 v 0.264206951871 -0.066843483054 -0.340973939036 vt -0.984252 -0.899561 vt -0.984252 -0.413961 f 23/62 25/63 24/64 v -0.264207840075 -0.066843483054 -0.340973939036 vt -34.4488 -0.899561 f 25/63 23/62 26/65 vt -25.055 20.4102 vt -25.055 20.0396 vt -24.7411 20.4102 f 6/66 26/67 23/68 vt -25.3688 20.4102 f 26/67 6/66 7/69 vt -0.984252 31.9702 v -0.264207840075 -0.066843483054 0.34091540639 vt -77.7559 31.4846 vt -0.984252 31.4846 f 7/70 27/71 26/72 vt -77.7559 31.9702 f 27/71 7/70 9/73 vt -30.6227 67.5622 vt -30.6227 67.1917 vt -30.3089 67.5622 f 10/74 27/75 9/76 v -0.264207840075 -0.065093099341 0.344857255945 vt -30.9366 67.5622 f 27/75 10/74 28/77 vt -31.1794 46.57 vt -30.9366 46.1495 vt -30.6227 46.1495 f 11/78 28/79 10/80 vt 34.4488 55.9205 v 0.264206951871 -0.065093099341 0.344857255945 vt 0.984252 55.4349 vt 34.4488 55.4349 f 11/81 29/82 28/83 v 0.264206951871 -0.0620432731089 0.347907348639 vt 0.984252 55.9205 f 29/82 11/81 30/84 v -0.264207840075 -0.0581013347333 0.349657110609 vt 34.4488 32.8538 vt 0.984252 32.3682 vt 34.4488 32.3682 f 31/85 30/86 11/87 v 0.264206951871 -0.0581013347333 0.349657110609 vt 0.984252 32.8538 f 30/86 31/85 32/88 v -0.264207840075 -0.0351453458881 0.349657110609 vt 34.4488 3.56882 vt 0.984252 0.984252 vt 34.4488 0.984252 f 33/89 32/90 31/91 v 0.264206951871 -0.0351453458881 0.349657110609 vt 0.984252 3.56882 f 32/90 33/89 34/92 v -0.264207840075 -0.0121888241204 0.349657110609 vt 34.4488 6.15339 f 35/93 34/92 33/89 v 0.264206951871 -0.0121888241204 0.349657110609 vt 0.984252 6.15339 f 34/92 35/93 36/94 v -0.264207840075 -0.00824697456519 0.347907348639 vt 34.4488 -25.8447 vt 0.984252 -26.3303 vt 34.4488 -26.3303 f 37/95 36/96 35/97 v 0.264206951871 -0.00824697456519 0.347907348639 vt 0.984252 -25.8447 f 36/96 37/95 38/98 v -0.264207840075 -0.00519688187195 0.344857255945 vt 34.4488 -50.3878 vt 0.984252 -50.8734 vt 34.4488 -50.8734 f 39/99 38/100 37/101 v 0.264206951871 -0.00519688187195 0.344857255945 vt 0.984252 -50.3878 f 38/100 39/99 40/102 vt 34.4488 -68.6543 v 0.264206951871 -0.00344711990173 0.34091540639 vt 0.984252 -68.1687 vt 0.984252 -68.6543 f 39/103 41/104 40/105 v -0.264207840075 -0.00344711990173 0.34091540639 vt 34.4488 -68.1687 f 41/104 39/103 42/106 v -0.267711805035 -0.00519688187195 0.342886331167 vt -30.6227 -63.7665 vt -30.6227 -63.3959 vt -30.9366 -63.7665 f 43/107 42/108 39/109 v -0.271215769996 -0.00519688187195 0.34091540639 vt -30.3089 -63.7665 f 42/108 43/107 44/110 vt -30.3089 -40.3216 vt -30.6227 -40.3216 v -0.276638255695 -0.00824697456519 0.34091540639 vt -30.0661 -40.7422 f 44/111 43/112 45/113 vt -30.0661 -40.7422 vt -30.6227 -40.3216 vt -31.1794 -40.7422 f 45/114 43/115 37/116 vt -31.1794 -40.7422 vt -30.6227 -40.3216 vt -30.9366 -40.3216 f 37/117 43/118 39/119 v -0.271215769996 -0.0121888241204 0.347907348639 vt -30.8655 -41.2857 vt -30.0661 -40.7422 vt -31.1794 -40.7422 f 46/120 45/121 37/122 v -0.276638255695 -0.0121888241204 0.344857255945 vt -30.3799 -41.2857 f 45/121 46/120 47/123 vt -30.8655 6.15339 v -0.276638255695 -0.0351453458881 0.344857255945 vt -30.3799 3.56882 vt -30.3799 6.15339 f 46/124 48/125 47/126 v -0.271215769996 -0.0351453458881 0.347907348639 vt -30.8655 3.56882 f 48/125 46/124 49/127 vt 0.0159934 6.15339 vt -0.469606 3.56882 vt 0.0159934 3.56882 f 46/128 33/129 49/130 vt -0.469606 6.15339 f 33/129 46/128 35/131 vt -0.389633 -26.1374 vt -0.469606 -26.6164 vt 0.0159934 -26.6164 f 37/132 35/133 46/134 vt -0.469606 0.984252 f 31/135 49/130 33/129 vt 0.0159934 0.984252 f 49/130 31/135 12/136 vt -0.469606 33.2302 vt -0.389633 32.7512 vt 0.0159934 33.2302 f 31/137 11/138 12/139 vt -30.3799 0.984252 vt -30.8655 0.984252 f 13/140 49/127 12/141 f 49/127 13/140 48/125 vt -56.6859 0.984252 vt -57.1715 3.56882 vt -57.1715 0.984252 f 14/142 48/143 13/144 vt -56.6859 3.56882 f 48/143 14/142 15/145 vt -57.1715 6.15339 f 15/145 47/146 48/143 v -0.279749634468 -0.0121888241204 0.34091540639 vt -56.6859 6.15339 f 47/146 15/145 50/147 vt -77.7559 6.15339 f 16/38 50/148 15/36 v -0.279749634468 -0.0121888241204 -0.340973939036 vt -0.984252 6.15339 f 50/148 16/38 51/149 vt -15.279 6.15339 f 17/42 51/150 16/40 v -0.276638255695 -0.0121888241204 -0.344915788592 vt -14.7934 6.15339 f 51/150 17/42 52/151 vt -25.2978 6.15339 f 18/46 52/152 17/44 v -0.271215769996 -0.0121888241204 -0.347965437183 vt -24.8122 6.15339 f 52/152 18/46 53/153 v -0.264207840075 -0.0121888241204 -0.349715732076 vt -31.4846 6.15339 vt -31.9702 6.15339 f 18/49 54/154 53/155 f 54/154 18/49 19/48 vt -34.4488 3.56882 v 0.264206951871 -0.0121888241204 -0.349715732076 vt -0.984252 6.15339 vt -34.4488 6.15339 f 19/156 55/157 54/158 v 0.264206951871 -0.0351453458881 -0.349715732076 vt -0.984252 3.56882 f 55/157 19/156 56/159 vt -34.4488 0.984252 f 20/160 56/159 19/156 vt -0.984252 0.984252 f 56/159 20/160 21/161 vt -0.899561 0.984252 v 0.271214881792 -0.0351453458881 -0.347965437183 vt -0.413961 3.56882 vt -0.899561 3.56882 f 21/162 57/163 56/164 v 0.271214881792 -0.0581013347333 -0.347965437183 vt -0.413961 0.984252 f 57/163 21/162 58/165 vt -0.899561 0.761815 vt -0.819588 0.282846 vt -0.413961 0.761815 f 21/166 22/167 58/168 v 0.276637367492 -0.0620432731089 -0.340973939036 vt 0.556625 -0.0410064 vt -0.2428 0.502555 vt -0.556625 -0.0410064 f 59/169 58/170 22/171 v 0.276637367492 -0.0581013347333 -0.344915788592 vt 0.2428 0.502555 f 58/170 59/169 60/172 v 0.279748746264 -0.0581013347333 -0.340973939036 vt 0.899561 0.761815 vt 0.413961 0.761815 vt 0.819588 0.282846 f 61/173 60/174 59/175 vt 0.899561 0.984252 v 0.276637367492 -0.0351453458881 -0.344915788592 vt 0.413961 3.56882 vt 0.413961 0.984252 f 61/176 62/177 60/178 v 0.279748746264 -0.0351453458881 -0.340973939036 vt 0.899561 3.56882 f 62/177 61/176 63/179 v 0.279748746264 -0.0581013347333 0.34091540639 vt 77.7559 0.984252 vt 0.984252 3.56882 vt 0.984252 0.984252 f 64/180 63/181 61/182 v 0.279748746264 -0.0351453458881 0.34091540639 vt 77.7559 3.56882 f 63/181 64/180 65/183 v 0.276637367492 -0.0581013347333 0.344857255945 vt 71.5509 0.984252 vt 71.0653 3.56882 vt 71.0653 0.984252 f 66/184 65/185 64/186 v 0.276637367492 -0.0351453458881 0.344857255945 vt 71.5509 3.56882 f 65/185 66/184 67/187 v 0.271214881792 -0.0581013347333 0.347907348639 vt 55.9205 0.984252 vt 55.4349 3.56882 vt 55.4349 0.984252 f 68/188 67/189 66/190 v 0.271214881792 -0.0351453458881 0.347907348639 vt 55.9205 3.56882 f 67/189 68/188 69/191 vt 32.3682 0.984252 vt 32.8538 3.56882 vt 32.3682 3.56882 f 68/192 34/193 69/194 vt 32.8538 0.984252 f 34/193 68/192 32/195 vt 32.3682 27.823 vt 32.7738 27.3441 vt 32.8538 27.823 f 68/196 30/197 32/198 vt 55.4349 32.6481 vt 56.2343 32.1045 vt 55.9205 32.6481 f 66/199 30/200 68/201 v 0.276637367492 -0.0620432731089 0.34091540639 vt 55.1211 32.1045 f 30/200 66/199 70/202 vt 71.5509 12.7777 vt 71.0653 12.7777 vt 71.1453 12.2987 f 66/203 64/204 70/205 vt 0.984252 0.899561 vt 77.7559 0.413961 vt 77.7559 0.899561 f 61/206 70/207 64/208 vt 0.984252 0.413961 f 70/207 61/206 59/209 vt 0.984252 0.2428 v 0.271214881792 -0.065093099341 0.34091540639 vt 77.7559 -0.2428 vt 77.7559 0.2428 f 59/210 71/211 70/212 v 0.271214881792 -0.065093099341 -0.340973939036 vt 0.984252 -0.2428 f 71/211 59/210 72/213 vt 0.556625 -0.0410064 v 0.267710916831 -0.065093099341 -0.342944863814 vt -1.59761e-013 -0.461548 vt 0.313825 -0.461548 f 59/214 73/215 72/216 vt 0.556625 -0.0410064 vt -0.556625 -0.0410064 vt -6.15619e-014 -0.461548 f 59/217 22/218 73/219 vt -0.556625 -0.0410064 vt -0.313825 -0.461548 vt -1.7758e-013 -0.461548 f 22/220 24/221 73/222 vt -2.81136e-013 -1.1788 vt -1.48576e-013 -0.808233 vt -0.313825 -0.808233 f 25/223 73/224 24/225 vt 0.313825 -0.808233 f 73/224 25/223 72/226 vt 0.984252 -0.899561 vt 77.7559 -0.413961 vt 0.984252 -0.413961 f 25/227 71/228 72/229 v 0.264206951871 -0.066843483054 0.34091540639 vt 77.7559 -0.899561 f 71/228 25/227 74/230 v 0.264206951871 -0.066843483054 -0.332231346614 vt 1.9685 -0.899561 f 74/230 25/227 75/231 vt 34.4488 0.984252 vt 0.984252 1.9685 vt 0.984252 0.984252 f 26/232 75/233 25/234 vt 0.984252 77.7559 f 75/233 26/232 74/235 vt 34.4488 77.7559 f 74/235 26/232 27/236 vt 34.4488 71.0653 vt 0.984252 71.5509 vt 0.984252 71.0653 f 27/237 29/238 74/239 vt 34.4488 71.5509 f 29/238 27/237 28/240 v 0.267710916831 -0.065093099341 0.342886331167 vt 55.6777 46.3438 vt 55.6777 45.9732 vt 55.9915 46.3438 f 76/241 74/242 29/243 vt 55.3639 46.3438 f 74/242 76/241 71/244 vt 55.1211 32.1045 vt 55.3639 31.684 vt 55.6777 31.684 f 70/245 71/246 76/247 vt 56.2343 32.1045 vt 55.1211 32.1045 vt 55.6777 31.684 f 30/248 70/249 76/250 vt 56.2343 32.1045 vt 55.6777 31.684 vt 55.9915 31.684 f 30/251 76/252 29/253 vt 32.8538 6.15339 f 36/254 69/194 34/193 v 0.271214881792 -0.0121888241204 0.347907348639 vt 32.3682 6.15339 f 69/194 36/254 77/255 vt 32.7738 -20.7303 vt 32.3682 -21.2093 vt 32.8538 -21.2093 f 38/256 77/257 36/258 v 0.276637367492 -0.00824697456519 0.34091540639 vt 55.1211 -26.2767 vt 55.9205 -26.8202 vt 56.2343 -26.2767 f 78/259 77/260 38/261 v 0.276637367492 -0.0121888241204 0.344857255945 vt 55.4349 -26.8202 f 77/260 78/259 79/262 vt 71.5509 -6.16391 vt 71.1453 -5.68494 v 0.279748746264 -0.0121888241204 0.34091540639 vt 71.0653 -6.16391 f 79/263 78/264 80/265 v 0.276637367492 -0.00824697456519 -0.340973939036 vt 0.984252 6.10951 vt 77.7559 5.62391 vt 77.7559 6.10951 f 81/266 80/267 78/268 v 0.279748746264 -0.0121888241204 -0.340973939036 vt 0.984252 5.62391 f 80/267 81/266 82/269 vt 0.819588 6.33093 v 0.276637367492 -0.0121888241204 -0.344915788592 vt 0.413961 5.85196 vt 0.899561 5.85196 f 81/270 83/271 82/272 vt 0.556625 5.86886 v 0.271214881792 -0.0121888241204 -0.347965437183 vt -0.2428 5.3253 vt 0.2428 5.3253 f 81/273 84/274 83/275 v 0.264206951871 -0.00824697456519 -0.347965437183 vt -0.556625 5.86886 f 84/274 81/273 85/276 v 0.267710916831 -0.00519688187195 -0.342944863814 vt -6.15064e-014 6.2894 vt -0.556625 5.86886 vt 0.556625 5.86886 f 86/277 85/278 81/279 v 0.264206951871 -0.00519688187195 -0.344915788592 vt -0.313825 6.2894 vt -0.556625 5.86886 vt -1.77858e-013 6.2894 f 87/280 85/281 86/282 vt -0.984252 5.28987 v -0.264207840075 -0.00824697456519 -0.347965437183 vt -34.4488 4.80427 vt -0.984252 4.80427 f 87/283 88/284 85/285 v -0.264207840075 -0.00519688187195 -0.344915788592 vt -34.4488 5.28987 f 88/284 87/283 89/286 vt -0.984252 3.31055 v -0.264207840075 -0.00344711990173 -0.340973939036 vt -34.4488 3.79615 vt -34.4488 3.31055 f 87/287 90/288 89/289 v 0.264206951871 -0.00344711990173 -0.340973939036 vt -0.984252 3.79615 f 90/288 87/287 91/290 vt -1.48548e-013 4.60397 vt -2.81108e-013 4.97454 vt -0.313825 4.60397 f 86/291 91/292 87/293 v 0.271214881792 -0.00519688187195 -0.340973939036 vt 0.313825 4.60397 f 91/292 86/291 92/294 vt -1.59761e-013 6.2894 vt 0.556625 5.86886 vt 0.313825 6.2894 f 86/295 81/296 92/297 vt 77.7559 4.80427 vt 0.984252 5.28987 vt 0.984252 4.80427 f 78/298 92/299 81/300 v 0.271214881792 -0.00519688187195 0.34091540639 vt 77.7559 5.28987 f 92/299 78/298 93/301 vt 55.3639 -25.8561 vt 55.1211 -26.2767 v 0.267710916831 -0.00519688187195 0.342886331167 vt 55.6777 -25.8561 f 93/302 78/303 94/304 vt 56.2343 -26.2767 vt 55.6777 -25.8561 vt 55.1211 -26.2767 f 38/305 94/306 78/307 vt 56.2343 -26.2767 vt 55.9915 -25.8561 vt 55.6777 -25.8561 f 38/308 40/309 94/310 vt 55.6777 -42.1775 vt 55.6777 -42.5481 vt 55.9915 -42.5481 f 41/311 94/312 40/313 vt 55.3639 -42.5481 f 94/312 41/311 93/314 vt 0.984252 3.79615 vt 77.7559 3.31055 vt 77.7559 3.79615 f 91/315 93/316 41/317 vt 0.984252 3.31055 f 93/316 91/315 92/318 v 0.264206951871 -0.00344711990173 -0.332231346614 vt 1.9685 3.79615 f 91/315 41/317 95/319 vt -34.4488 77.7559 vt -0.984252 1.9685 vt -0.984252 77.7559 f 42/320 95/321 41/322 vt -0.984252 0.984252 f 95/321 42/320 91/323 vt -34.4488 0.984252 f 91/323 42/320 90/324 vt -77.7559 -29.0736 vt -0.984252 -28.588 vt -77.7559 -28.588 f 44/325 90/326 42/327 v -0.271215769996 -0.00519688187195 -0.340973939036 vt -0.984252 -29.0736 f 90/326 44/325 96/328 vt -77.7559 -19.7651 v -0.276638255695 -0.00824697456519 -0.340973939036 vt -0.984252 -20.2507 vt -0.984252 -19.7651 f 44/329 97/330 96/331 vt -77.7559 -20.2507 f 97/330 44/329 45/332 vt -77.7559 -8.26989 vt -0.984252 -8.75549 vt -0.984252 -8.26989 f 45/333 51/334 97/335 vt -77.7559 -8.75549 f 51/334 45/333 50/336 vt -57.1715 -18.3415 vt -56.6859 -18.3415 vt -56.7659 -17.8625 f 47/337 50/338 45/339 vt -15.279 -6.32559 vt -14.7934 -6.32559 vt -15.199 -5.84662 f 51/340 52/341 97/342 vt -24.8122 -9.14019 vt -25.6116 -8.59663 vt -25.2978 -9.14019 f 53/343 97/344 52/345 vt -24.4983 -8.59663 f 97/344 53/343 88/346 vt -31.5646 0.923787 vt -31.9702 0.444818 vt -31.4846 0.444818 f 88/347 53/348 54/349 vt -34.4488 5.62391 vt -0.984252 6.10951 vt -34.4488 6.10951 f 54/350 85/351 88/352 vt -0.984252 5.62391 f 85/351 54/350 55/353 vt -0.819588 6.33093 vt -0.899561 5.85196 vt -0.413961 5.85196 f 85/354 55/355 84/356 vt -0.413961 6.15339 vt -0.899561 6.15339 f 56/164 84/357 55/358 f 84/357 56/164 57/163 vt 0.2428 3.56882 vt -0.2428 6.15339 vt -0.2428 3.56882 f 62/359 84/360 57/361 vt 0.2428 6.15339 f 84/360 62/359 83/362 vt 0.413961 6.15339 f 63/179 83/363 62/177 vt 0.899561 6.15339 f 83/363 63/179 82/364 vt 0.984252 6.15339 f 65/183 82/365 63/181 vt 77.7559 6.15339 f 82/365 65/183 80/366 vt 71.0653 6.15339 f 67/187 80/367 65/185 vt 71.5509 6.15339 f 80/367 67/187 79/368 vt 55.4349 6.15339 f 69/191 79/369 67/189 vt 55.9205 6.15339 f 79/369 69/191 77/370 vt 0.2428 0.984252 f 57/361 60/371 62/359 vt -0.2428 0.984252 f 60/371 57/361 58/372 vt -25.6116 -8.59663 vt -24.4983 -8.59663 v -0.267711805035 -0.00519688187195 -0.342944863814 vt -25.055 -8.17609 f 97/373 88/374 98/375 vt -25.055 -8.17609 vt -24.4983 -8.59663 vt -24.7411 -8.17609 f 98/376 88/377 89/378 vt -25.055 -16.2439 vt -25.055 -16.6144 vt -24.7411 -16.6144 f 90/379 98/380 89/381 vt -25.3688 -16.6144 f 98/380 90/379 96/382 vt -25.3688 -8.17609 vt -25.6116 -8.59663 vt -25.055 -8.17609 f 96/383 97/384 98/385 vt -25.055 14.0039 vt -24.7411 14.0039 vt -24.4983 14.4245 f 6/386 23/387 5/388 g Mesh2 Group3 Group1 Model usemtl Material15 v -0.309472494656 -0.0297237483926 0.349686421342 vt -69.685 80.9055 v -0.279749634468 -0.0297237483926 -0.349686865444 vt -66.3386 2.16535 v -0.279749634468 -0.0297237483926 0.349686421342 vt -66.3386 80.9055 f 99/389 100/390 101/391 v -0.309472494656 -0.0297237483926 -0.349686865444 vt -69.685 2.16535 f 100/390 99/389 102/392 vt -80.9055 27.084 v -0.309472494656 -0.0489562970574 -0.349686865444 vt -2.16535 24.9186 vt -2.16535 27.084 f 99/393 103/394 102/395 v -0.309472494656 -0.0489562970574 0.349686421342 vt -80.9055 24.9186 f 103/394 99/393 104/396 v -0.309472494656 0.134629528242 0.36891959175 vt -83.0709 45.5879 f 99/393 105/397 104/396 v -0.309472494656 0.134629528242 0.349686421342 vt -80.9055 45.5879 f 105/397 99/393 106/398 vt -69.685 27.084 v 0.309472494656 0.134629528242 0.349686421342 vt 1.67487e-015 45.5879 vt -69.685 45.5879 f 99/399 107/400 106/401 vt -66.3386 27.084 f 101/402 107/400 99/399 v 0.279749634468 -0.0297237483926 0.349686421342 vt -3.34646 27.084 f 108/403 107/400 101/402 v 0.309472494656 -0.0297237483926 0.349686421342 vt 1.67487e-015 27.084 f 107/400 108/403 109/404 vt -3.34646 80.9055 v 0.309472494656 -0.0297237483926 -0.349686865444 vt 1.43766e-014 2.16535 vt 1.43766e-014 80.9055 f 108/405 110/406 109/407 v 0.279749634468 -0.0297237483926 -0.349686865444 vt -3.34646 2.16535 f 110/406 108/405 111/408 v 0.279749634468 -0.0917929570598 -0.349686865444 vt -2.16535 20.0958 f 108/393 112/409 111/395 v 0.279749634468 -0.0917929570598 0.349686421342 vt -80.9055 20.0958 f 112/409 108/393 113/410 v -0.279749634468 -0.0917929570598 0.349686421342 vt -66.3386 20.0958 vt -3.34646 20.0958 f 108/403 114/411 113/412 f 114/411 108/403 101/402 vt 2.16535 27.084 vt 80.9055 20.0958 vt 80.9055 27.084 f 100/413 114/414 101/415 v -0.279749634468 -0.0917929570598 -0.349686865444 vt 2.16535 20.0958 f 114/414 100/413 115/416 vt 66.3386 27.084 vt 3.34646 20.0958 vt 66.3386 20.0958 f 100/417 112/418 115/419 vt 3.34646 27.084 f 112/418 100/417 111/420 v -0.309472494656 -0.0297237483926 -0.36891959175 vt -69.685 0 vt -3.34646 2.16535 vt -66.3386 2.16535 f 116/421 111/422 100/423 v 0.309472494656 -0.0297237483926 -0.36891959175 vt 0 0 f 117/424 111/422 116/421 vt 0 2.16535 f 111/422 117/424 110/425 vt 0 27.084 v 0.309472494656 -0.134629528242 -0.349686865444 vt 2.16535 15.273 f 117/426 118/427 110/413 v 0.309472494656 -0.134629528242 -0.36891959175 vt 0 15.273 f 118/427 117/426 119/428 v -0.309472494656 -0.134629528242 -0.36891959175 vt -69.685 15.273 f 117/426 120/429 119/428 vt -69.685 27.084 f 120/429 117/426 116/430 f 102/395 120/428 116/426 v -0.309472494656 -0.134629528242 -0.349686865444 vt -2.16535 15.273 f 120/428 102/395 121/431 f 121/431 102/395 103/394 vt 69.685 27.084 v -0.302478776 -0.0489562970574 -0.349686865444 vt 68.8976 24.9186 vt 69.685 24.9186 f 102/432 122/433 103/434 f 100/417 122/433 102/432 f 115/419 122/433 100/417 v -0.302478776 -0.0917929570598 -0.349686865444 vt 68.8976 20.0958 f 122/433 115/419 123/435 v 0.302478776 -0.0917929570598 -0.349686865444 vt 0.787402 20.0958 f 124/436 123/435 115/419 vt 2.29462e-016 15.273 f 124/436 118/437 123/435 v 0.309472494656 -0.0489562970574 -0.349686865444 vt 2.29462e-016 24.9186 f 118/437 124/436 125/438 v 0.302478776 -0.0489562970574 -0.349686865444 vt 0.787402 24.9186 f 125/438 124/436 126/439 v 0.302478776 -0.0917929570598 0.349686421342 vt 2.16535 24.9186 f 127/414 126/440 124/416 v 0.302478776 -0.0489562970574 0.349686421342 vt 80.9055 24.9186 f 126/440 127/414 128/441 vt -0.787402 20.0958 v 0.309472494656 -0.0489562970574 0.349686421342 vt 1.67487e-015 24.9186 vt -0.787402 24.9186 f 127/442 129/443 128/444 v 0.309472494656 -0.134629528242 0.349686421342 vt 1.67487e-015 15.273 f 127/442 130/445 129/443 v -0.309472494656 -0.134629528242 0.349686421342 f 130/445 127/442 131/429 v -0.302478776 -0.0917929570598 0.349686421342 vt -68.8976 20.0958 f 132/446 131/429 127/442 vt -69.685 24.9186 f 131/429 132/446 104/447 v -0.302478776 -0.0489562970574 0.349686421342 vt -68.8976 24.9186 f 104/447 132/446 133/448 f 123/409 133/396 132/410 f 133/396 123/409 122/394 f 123/435 103/434 122/433 vt 69.685 15.273 f 123/435 121/449 103/434 f 121/449 123/435 118/437 vt 1.0325e-016 2.16535 vt 69.685 -3.6758e-015 vt 69.685 2.16535 f 118/450 120/451 121/452 vt 1.0325e-016 -3.6758e-015 f 120/451 118/450 119/453 vt 69.685 2.16535 vt 68.8976 80.9055 vt 68.8976 2.16535 f 103/454 133/455 122/456 vt 69.685 80.9055 f 133/455 103/454 104/457 vt 66.3386 80.9055 f 114/458 123/456 132/455 vt 66.3386 2.16535 f 123/456 114/458 115/459 f 132/446 113/412 114/411 f 132/446 127/442 113/412 vt 0.787402 80.9055 vt 3.34646 2.16535 vt 3.34646 80.9055 f 127/460 112/461 113/462 vt 0.787402 2.16535 f 112/461 127/460 124/463 f 124/436 115/419 112/418 vt 0.787402 20.0958 f 111/420 124/464 112/418 vt 0.787402 24.9186 f 124/464 111/420 126/465 vt 0 24.9186 f 126/465 111/420 125/466 f 125/466 111/420 110/426 f 110/413 118/427 125/440 f 129/441 110/413 125/440 f 110/413 129/441 109/415 v 0.309472494656 -0.134629528242 0.36891959175 vt 83.0709 15.273 f 129/441 134/467 109/415 vt 80.9055 15.273 f 134/467 129/441 130/468 vt 0 83.0709 vt 0 80.9055 f 131/457 134/469 130/470 v -0.309472494656 -0.134629528242 0.36891959175 vt 69.685 83.0709 f 134/469 131/457 135/471 vt -80.9055 15.273 vt -83.0709 15.273 f 131/472 105/397 135/473 f 104/396 105/397 131/472 vt 69.685 45.5879 f 105/474 134/428 135/449 v 0.309472494656 0.134629528242 0.36891959175 vt 0 45.5879 f 134/428 105/474 136/475 vt -69.685 83.0709 f 105/476 107/470 136/469 vt -69.685 80.9055 f 107/470 105/476 106/477 vt 80.9055 45.5879 vt 83.0709 45.5879 f 107/478 134/467 136/479 f 109/415 134/467 107/478 vt 0.787402 2.16535 f 126/480 129/470 125/425 vt 0.787402 80.9055 f 129/470 126/480 128/481 vt -69.685 2.16535 f 116/421 100/423 102/482
mtllib malm_bed_3_obj0_object.mtl g Mesh1 Group2 Group1 Model usemtl matress_white v -0.276638255695 -0.0620432731089 -0.340973939036 vt -15.199 12.4604 v -0.276638255695 -0.0581013347333 -0.344915788592 vt -14.7934 12.9394 v -0.279749634468 -0.0581013347333 -0.340973939036 vt -15.279 12.9394 f 1/1 2/2 3/3 vt -25.6116 14.4245 v -0.271215769996 -0.0581013347333 -0.347965437183 vt -24.8122 14.968 vt -25.2978 14.968 f 1/4 4/5 2/6 v -0.264207840075 -0.0620432731089 -0.347965437183 vt -24.4983 14.4245 f 4/5 1/4 5/7 vt -25.6116 14.4245 v -0.267711805035 -0.065093099341 -0.342944863814 vt -25.055 14.0039 vt -24.4983 14.4245 f 1/8 6/9 5/10 vt -25.6116 14.4245 v -0.271215769996 -0.065093099341 -0.340973939036 vt -25.3688 14.0039 vt -25.055 14.0039 f 1/11 7/12 6/13 v -0.276638255695 -0.0620432731089 0.34091540639 vt -77.7559 25.2978 vt -0.984252 24.8122 vt -0.984252 25.2978 f 8/14 7/15 1/16 v -0.271215769996 -0.065093099341 0.34091540639 vt -77.7559 24.8122 f 7/15 8/14 9/17 vt -30.0661 46.57 v -0.267711805035 -0.065093099341 0.342886331167 vt -30.6227 46.1495 vt -30.3089 46.1495 f 8/18 10/19 9/20 vt -30.0661 46.57 v -0.264207840075 -0.0620432731089 0.347907348639 vt -31.1794 46.57 vt -30.6227 46.1495 f 8/21 11/22 10/23 vt -30.0661 46.57 v -0.271215769996 -0.0581013347333 0.347907348639 vt -30.8655 47.1136 vt -31.1794 46.57 f 8/24 12/25 11/26 v -0.276638255695 -0.0581013347333 0.344857255945 vt -30.3799 47.1136 f 12/25 8/24 13/27 vt -57.1715 24.9552 vt -56.7659 24.4763 v -0.279749634468 -0.0581013347333 0.34091540639 vt -56.6859 24.9552 f 13/28 8/29 14/30 vt -0.984252 14.7934 vt -77.7559 15.279 vt -77.7559 14.7934 f 1/31 14/32 8/33 vt -0.984252 15.279 f 14/32 1/31 3/34 vt -0.984252 0.984252 v -0.279749634468 -0.0351453458881 0.34091540639 vt -77.7559 3.56882 vt -77.7559 0.984252 f 3/35 15/36 14/37 v -0.279749634468 -0.0351453458881 -0.340973939036 vt -0.984252 3.56882 f 15/36 3/35 16/38 vt -14.7934 0.984252 vt -15.279 3.56882 vt -15.279 0.984252 f 2/39 16/40 3/41 v -0.276638255695 -0.0351453458881 -0.344915788592 vt -14.7934 3.56882 f 16/40 2/39 17/42 vt -24.8122 0.984252 vt -25.2978 3.56882 vt -25.2978 0.984252 f 4/43 17/44 2/45 v -0.271215769996 -0.0351453458881 -0.347965437183 vt -24.8122 3.56882 f 17/44 4/43 18/46 vt -31.9702 0.984252 v -0.264207840075 -0.0351453458881 -0.349715732076 vt -31.4846 3.56882 vt -31.9702 3.56882 f 4/47 19/48 18/49 v -0.264207840075 -0.0581013347333 -0.349715732076 vt -31.4846 0.984252 f 19/48 4/47 20/50 vt -31.9702 6.16896 vt -31.5646 5.68999 vt -31.4846 6.16896 f 4/51 5/52 20/53 vt -34.4488 0.413961 v 0.264206951871 -0.0581013347333 -0.349715732076 vt -0.984252 0.899561 vt -34.4488 0.899561 f 5/54 21/55 20/56 v 0.264206951871 -0.0620432731089 -0.347965437183 vt -0.984252 0.413961 f 21/55 5/54 22/57 v -0.264207840075 -0.065093099341 -0.344915788592 vt -34.4488 -0.2428 vt -0.984252 0.2428 vt -34.4488 0.2428 f 23/58 22/59 5/60 v 0.264206951871 -0.065093099341 -0.344915788592 vt -0.984252 -0.2428 f 22/59 23/58 24/61 vt -34.4488 -0.413961 v 0.264206951871 -0.066843483054 -0.340973939036 vt -0.984252 -0.899561 vt -0.984252 -0.413961 f 23/62 25/63 24/64 v -0.264207840075 -0.066843483054 -0.340973939036 vt -34.4488 -0.899561 f 25/63 23/62 26/65 vt -25.055 20.4102 vt -25.055 20.0396 vt -24.7411 20.4102 f 6/66 26/67 23/68 vt -25.3688 20.4102 f 26/67 6/66 7/69 vt -0.984252 31.9702 v -0.264207840075 -0.066843483054 0.34091540639 vt -77.7559 31.4846 vt -0.984252 31.4846 f 7/70 27/71 26/72 vt -77.7559 31.9702 f 27/71 7/70 9/73 vt -30.6227 67.5622 vt -30.6227 67.1917 vt -30.3089 67.5622 f 10/74 27/75 9/76 v -0.264207840075 -0.065093099341 0.344857255945 vt -30.9366 67.5622 f 27/75 10/74 28/77 vt -31.1794 46.57 vt -30.9366 46.1495 vt -30.6227 46.1495 f 11/78 28/79 10/80 vt 34.4488 55.9205 v 0.264206951871 -0.065093099341 0.344857255945 vt 0.984252 55.4349 vt 34.4488 55.4349 f 11/81 29/82 28/83 v 0.264206951871 -0.0620432731089 0.347907348639 vt 0.984252 55.9205 f 29/82 11/81 30/84 v -0.264207840075 -0.0581013347333 0.349657110609 vt 34.4488 32.8538 vt 0.984252 32.3682 vt 34.4488 32.3682 f 31/85 30/86 11/87 v 0.264206951871 -0.0581013347333 0.349657110609 vt 0.984252 32.8538 f 30/86 31/85 32/88 v -0.264207840075 -0.0351453458881 0.349657110609 vt 34.4488 3.56882 vt 0.984252 0.984252 vt 34.4488 0.984252 f 33/89 32/90 31/91 v 0.264206951871 -0.0351453458881 0.349657110609 vt 0.984252 3.56882 f 32/90 33/89 34/92 v -0.264207840075 -0.0121888241204 0.349657110609 vt 34.4488 6.15339 f 35/93 34/92 33/89 v 0.264206951871 -0.0121888241204 0.349657110609 vt 0.984252 6.15339 f 34/92 35/93 36/94 v -0.264207840075 -0.00824697456519 0.347907348639 vt 34.4488 -25.8447 vt 0.984252 -26.3303 vt 34.4488 -26.3303 f 37/95 36/96 35/97 v 0.264206951871 -0.00824697456519 0.347907348639 vt 0.984252 -25.8447 f 36/96 37/95 38/98 v -0.264207840075 -0.00519688187195 0.344857255945 vt 34.4488 -50.3878 vt 0.984252 -50.8734 vt 34.4488 -50.8734 f 39/99 38/100 37/101 v 0.264206951871 -0.00519688187195 0.344857255945 vt 0.984252 -50.3878 f 38/100 39/99 40/102 vt 34.4488 -68.6543 v 0.264206951871 -0.00344711990173 0.34091540639 vt 0.984252 -68.1687 vt 0.984252 -68.6543 f 39/103 41/104 40/105 v -0.264207840075 -0.00344711990173 0.34091540639 vt 34.4488 -68.1687 f 41/104 39/103 42/106 v -0.267711805035 -0.00519688187195 0.342886331167 vt -30.6227 -63.7665 vt -30.6227 -63.3959 vt -30.9366 -63.7665 f 43/107 42/108 39/109 v -0.271215769996 -0.00519688187195 0.34091540639 vt -30.3089 -63.7665 f 42/108 43/107 44/110 vt -30.3089 -40.3216 vt -30.6227 -40.3216 v -0.276638255695 -0.00824697456519 0.34091540639 vt -30.0661 -40.7422 f 44/111 43/112 45/113 vt -30.0661 -40.7422 vt -30.6227 -40.3216 vt -31.1794 -40.7422 f 45/114 43/115 37/116 vt -31.1794 -40.7422 vt -30.6227 -40.3216 vt -30.9366 -40.3216 f 37/117 43/118 39/119 v -0.271215769996 -0.0121888241204 0.347907348639 vt -30.8655 -41.2857 vt -30.0661 -40.7422 vt -31.1794 -40.7422 f 46/120 45/121 37/122 v -0.276638255695 -0.0121888241204 0.344857255945 vt -30.3799 -41.2857 f 45/121 46/120 47/123 vt -30.8655 6.15339 v -0.276638255695 -0.0351453458881 0.344857255945 vt -30.3799 3.56882 vt -30.3799 6.15339 f 46/124 48/125 47/126 v -0.271215769996 -0.0351453458881 0.347907348639 vt -30.8655 3.56882 f 48/125 46/124 49/127 vt 0.0159934 6.15339 vt -0.469606 3.56882 vt 0.0159934 3.56882 f 46/128 33/129 49/130 vt -0.469606 6.15339 f 33/129 46/128 35/131 vt -0.389633 -26.1374 vt -0.469606 -26.6164 vt 0.0159934 -26.6164 f 37/132 35/133 46/134 vt -0.469606 0.984252 f 31/135 49/130 33/129 vt 0.0159934 0.984252 f 49/130 31/135 12/136 vt -0.469606 33.2302 vt -0.389633 32.7512 vt 0.0159934 33.2302 f 31/137 11/138 12/139 vt -30.3799 0.984252 vt -30.8655 0.984252 f 13/140 49/127 12/141 f 49/127 13/140 48/125 vt -56.6859 0.984252 vt -57.1715 3.56882 vt -57.1715 0.984252 f 14/142 48/143 13/144 vt -56.6859 3.56882 f 48/143 14/142 15/145 vt -57.1715 6.15339 f 15/145 47/146 48/143 v -0.279749634468 -0.0121888241204 0.34091540639 vt -56.6859 6.15339 f 47/146 15/145 50/147 vt -77.7559 6.15339 f 16/38 50/148 15/36 v -0.279749634468 -0.0121888241204 -0.340973939036 vt -0.984252 6.15339 f 50/148 16/38 51/149 vt -15.279 6.15339 f 17/42 51/150 16/40 v -0.276638255695 -0.0121888241204 -0.344915788592 vt -14.7934 6.15339 f 51/150 17/42 52/151 vt -25.2978 6.15339 f 18/46 52/152 17/44 v -0.271215769996 -0.0121888241204 -0.347965437183 vt -24.8122 6.15339 f 52/152 18/46 53/153 v -0.264207840075 -0.0121888241204 -0.349715732076 vt -31.4846 6.15339 vt -31.9702 6.15339 f 18/49 54/154 53/155 f 54/154 18/49 19/48 vt -34.4488 3.56882 v 0.264206951871 -0.0121888241204 -0.349715732076 vt -0.984252 6.15339 vt -34.4488 6.15339 f 19/156 55/157 54/158 v 0.264206951871 -0.0351453458881 -0.349715732076 vt -0.984252 3.56882 f 55/157 19/156 56/159 vt -34.4488 0.984252 f 20/160 56/159 19/156 vt -0.984252 0.984252 f 56/159 20/160 21/161 vt -0.899561 0.984252 v 0.271214881792 -0.0351453458881 -0.347965437183 vt -0.413961 3.56882 vt -0.899561 3.56882 f 21/162 57/163 56/164 v 0.271214881792 -0.0581013347333 -0.347965437183 vt -0.413961 0.984252 f 57/163 21/162 58/165 vt -0.899561 0.761815 vt -0.819588 0.282846 vt -0.413961 0.761815 f 21/166 22/167 58/168 v 0.276637367492 -0.0620432731089 -0.340973939036 vt 0.556625 -0.0410064 vt -0.2428 0.502555 vt -0.556625 -0.0410064 f 59/169 58/170 22/171 v 0.276637367492 -0.0581013347333 -0.344915788592 vt 0.2428 0.502555 f 58/170 59/169 60/172 v 0.279748746264 -0.0581013347333 -0.340973939036 vt 0.899561 0.761815 vt 0.413961 0.761815 vt 0.819588 0.282846 f 61/173 60/174 59/175 vt 0.899561 0.984252 v 0.276637367492 -0.0351453458881 -0.344915788592 vt 0.413961 3.56882 vt 0.413961 0.984252 f 61/176 62/177 60/178 v 0.279748746264 -0.0351453458881 -0.340973939036 vt 0.899561 3.56882 f 62/177 61/176 63/179 v 0.279748746264 -0.0581013347333 0.34091540639 vt 77.7559 0.984252 vt 0.984252 3.56882 vt 0.984252 0.984252 f 64/180 63/181 61/182 v 0.279748746264 -0.0351453458881 0.34091540639 vt 77.7559 3.56882 f 63/181 64/180 65/183 v 0.276637367492 -0.0581013347333 0.344857255945 vt 71.5509 0.984252 vt 71.0653 3.56882 vt 71.0653 0.984252 f 66/184 65/185 64/186 v 0.276637367492 -0.0351453458881 0.344857255945 vt 71.5509 3.56882 f 65/185 66/184 67/187 v 0.271214881792 -0.0581013347333 0.347907348639 vt 55.9205 0.984252 vt 55.4349 3.56882 vt 55.4349 0.984252 f 68/188 67/189 66/190 v 0.271214881792 -0.0351453458881 0.347907348639 vt 55.9205 3.56882 f 67/189 68/188 69/191 vt 32.3682 0.984252 vt 32.8538 3.56882 vt 32.3682 3.56882 f 68/192 34/193 69/194 vt 32.8538 0.984252 f 34/193 68/192 32/195 vt 32.3682 27.823 vt 32.7738 27.3441 vt 32.8538 27.823 f 68/196 30/197 32/198 vt 55.4349 32.6481 vt 56.2343 32.1045 vt 55.9205 32.6481 f 66/199 30/200 68/201 v 0.276637367492 -0.0620432731089 0.34091540639 vt 55.1211 32.1045 f 30/200 66/199 70/202 vt 71.5509 12.7777 vt 71.0653 12.7777 vt 71.1453 12.2987 f 66/203 64/204 70/205 vt 0.984252 0.899561 vt 77.7559 0.413961 vt 77.7559 0.899561 f 61/206 70/207 64/208 vt 0.984252 0.413961 f 70/207 61/206 59/209 vt 0.984252 0.2428 v 0.271214881792 -0.065093099341 0.34091540639 vt 77.7559 -0.2428 vt 77.7559 0.2428 f 59/210 71/211 70/212 v 0.271214881792 -0.065093099341 -0.340973939036 vt 0.984252 -0.2428 f 71/211 59/210 72/213 vt 0.556625 -0.0410064 v 0.267710916831 -0.065093099341 -0.342944863814 vt -1.59761e-013 -0.461548 vt 0.313825 -0.461548 f 59/214 73/215 72/216 vt 0.556625 -0.0410064 vt -0.556625 -0.0410064 vt -6.15619e-014 -0.461548 f 59/217 22/218 73/219 vt -0.556625 -0.0410064 vt -0.313825 -0.461548 vt -1.7758e-013 -0.461548 f 22/220 24/221 73/222 vt -2.81136e-013 -1.1788 vt -1.48576e-013 -0.808233 vt -0.313825 -0.808233 f 25/223 73/224 24/225 vt 0.313825 -0.808233 f 73/224 25/223 72/226 vt 0.984252 -0.899561 vt 77.7559 -0.413961 vt 0.984252 -0.413961 f 25/227 71/228 72/229 v 0.264206951871 -0.066843483054 0.34091540639 vt 77.7559 -0.899561 f 71/228 25/227 74/230 v 0.264206951871 -0.066843483054 -0.332231346614 vt 1.9685 -0.899561 f 74/230 25/227 75/231 vt 34.4488 0.984252 vt 0.984252 1.9685 vt 0.984252 0.984252 f 26/232 75/233 25/234 vt 0.984252 77.7559 f 75/233 26/232 74/235 vt 34.4488 77.7559 f 74/235 26/232 27/236 vt 34.4488 71.0653 vt 0.984252 71.5509 vt 0.984252 71.0653 f 27/237 29/238 74/239 vt 34.4488 71.5509 f 29/238 27/237 28/240 v 0.267710916831 -0.065093099341 0.342886331167 vt 55.6777 46.3438 vt 55.6777 45.9732 vt 55.9915 46.3438 f 76/241 74/242 29/243 vt 55.3639 46.3438 f 74/242 76/241 71/244 vt 55.1211 32.1045 vt 55.3639 31.684 vt 55.6777 31.684 f 70/245 71/246 76/247 vt 56.2343 32.1045 vt 55.1211 32.1045 vt 55.6777 31.684 f 30/248 70/249 76/250 vt 56.2343 32.1045 vt 55.6777 31.684 vt 55.9915 31.684 f 30/251 76/252 29/253 vt 32.8538 6.15339 f 36/254 69/194 34/193 v 0.271214881792 -0.0121888241204 0.347907348639 vt 32.3682 6.15339 f 69/194 36/254 77/255 vt 32.7738 -20.7303 vt 32.3682 -21.2093 vt 32.8538 -21.2093 f 38/256 77/257 36/258 v 0.276637367492 -0.00824697456519 0.34091540639 vt 55.1211 -26.2767 vt 55.9205 -26.8202 vt 56.2343 -26.2767 f 78/259 77/260 38/261 v 0.276637367492 -0.0121888241204 0.344857255945 vt 55.4349 -26.8202 f 77/260 78/259 79/262 vt 71.5509 -6.16391 vt 71.1453 -5.68494 v 0.279748746264 -0.0121888241204 0.34091540639 vt 71.0653 -6.16391 f 79/263 78/264 80/265 v 0.276637367492 -0.00824697456519 -0.340973939036 vt 0.984252 6.10951 vt 77.7559 5.62391 vt 77.7559 6.10951 f 81/266 80/267 78/268 v 0.279748746264 -0.0121888241204 -0.340973939036 vt 0.984252 5.62391 f 80/267 81/266 82/269 vt 0.819588 6.33093 v 0.276637367492 -0.0121888241204 -0.344915788592 vt 0.413961 5.85196 vt 0.899561 5.85196 f 81/270 83/271 82/272 vt 0.556625 5.86886 v 0.271214881792 -0.0121888241204 -0.347965437183 vt -0.2428 5.3253 vt 0.2428 5.3253 f 81/273 84/274 83/275 v 0.264206951871 -0.00824697456519 -0.347965437183 vt -0.556625 5.86886 f 84/274 81/273 85/276 v 0.267710916831 -0.00519688187195 -0.342944863814 vt -6.15064e-014 6.2894 vt -0.556625 5.86886 vt 0.556625 5.86886 f 86/277 85/278 81/279 v 0.264206951871 -0.00519688187195 -0.344915788592 vt -0.313825 6.2894 vt -0.556625 5.86886 vt -1.77858e-013 6.2894 f 87/280 85/281 86/282 vt -0.984252 5.28987 v -0.264207840075 -0.00824697456519 -0.347965437183 vt -34.4488 4.80427 vt -0.984252 4.80427 f 87/283 88/284 85/285 v -0.264207840075 -0.00519688187195 -0.344915788592 vt -34.4488 5.28987 f 88/284 87/283 89/286 vt -0.984252 3.31055 v -0.264207840075 -0.00344711990173 -0.340973939036 vt -34.4488 3.79615 vt -34.4488 3.31055 f 87/287 90/288 89/289 v 0.264206951871 -0.00344711990173 -0.340973939036 vt -0.984252 3.79615 f 90/288 87/287 91/290 vt -1.48548e-013 4.60397 vt -2.81108e-013 4.97454 vt -0.313825 4.60397 f 86/291 91/292 87/293 v 0.271214881792 -0.00519688187195 -0.340973939036 vt 0.313825 4.60397 f 91/292 86/291 92/294 vt -1.59761e-013 6.2894 vt 0.556625 5.86886 vt 0.313825 6.2894 f 86/295 81/296 92/297 vt 77.7559 4.80427 vt 0.984252 5.28987 vt 0.984252 4.80427 f 78/298 92/299 81/300 v 0.271214881792 -0.00519688187195 0.34091540639 vt 77.7559 5.28987 f 92/299 78/298 93/301 vt 55.3639 -25.8561 vt 55.1211 -26.2767 v 0.267710916831 -0.00519688187195 0.342886331167 vt 55.6777 -25.8561 f 93/302 78/303 94/304 vt 56.2343 -26.2767 vt 55.6777 -25.8561 vt 55.1211 -26.2767 f 38/305 94/306 78/307 vt 56.2343 -26.2767 vt 55.9915 -25.8561 vt 55.6777 -25.8561 f 38/308 40/309 94/310 vt 55.6777 -42.1775 vt 55.6777 -42.5481 vt 55.9915 -42.5481 f 41/311 94/312 40/313 vt 55.3639 -42.5481 f 94/312 41/311 93/314 vt 0.984252 3.79615 vt 77.7559 3.31055 vt 77.7559 3.79615 f 91/315 93/316 41/317 vt 0.984252 3.31055 f 93/316 91/315 92/318 v 0.264206951871 -0.00344711990173 -0.332231346614 vt 1.9685 3.79615 f 91/315 41/317 95/319 vt -34.4488 77.7559 vt -0.984252 1.9685 vt -0.984252 77.7559 f 42/320 95/321 41/322 vt -0.984252 0.984252 f 95/321 42/320 91/323 vt -34.4488 0.984252 f 91/323 42/320 90/324 vt -77.7559 -29.0736 vt -0.984252 -28.588 vt -77.7559 -28.588 f 44/325 90/326 42/327 v -0.271215769996 -0.00519688187195 -0.340973939036 vt -0.984252 -29.0736 f 90/326 44/325 96/328 vt -77.7559 -19.7651 v -0.276638255695 -0.00824697456519 -0.340973939036 vt -0.984252 -20.2507 vt -0.984252 -19.7651 f 44/329 97/330 96/331 vt -77.7559 -20.2507 f 97/330 44/329 45/332 vt -77.7559 -8.26989 vt -0.984252 -8.75549 vt -0.984252 -8.26989 f 45/333 51/334 97/335 vt -77.7559 -8.75549 f 51/334 45/333 50/336 vt -57.1715 -18.3415 vt -56.6859 -18.3415 vt -56.7659 -17.8625 f 47/337 50/338 45/339 vt -15.279 -6.32559 vt -14.7934 -6.32559 vt -15.199 -5.84662 f 51/340 52/341 97/342 vt -24.8122 -9.14019 vt -25.6116 -8.59663 vt -25.2978 -9.14019 f 53/343 97/344 52/345 vt -24.4983 -8.59663 f 97/344 53/343 88/346 vt -31.5646 0.923787 vt -31.9702 0.444818 vt -31.4846 0.444818 f 88/347 53/348 54/349 vt -34.4488 5.62391 vt -0.984252 6.10951 vt -34.4488 6.10951 f 54/350 85/351 88/352 vt -0.984252 5.62391 f 85/351 54/350 55/353 vt -0.819588 6.33093 vt -0.899561 5.85196 vt -0.413961 5.85196 f 85/354 55/355 84/356 vt -0.413961 6.15339 vt -0.899561 6.15339 f 56/164 84/357 55/358 f 84/357 56/164 57/163 vt 0.2428 3.56882 vt -0.2428 6.15339 vt -0.2428 3.56882 f 62/359 84/360 57/361 vt 0.2428 6.15339 f 84/360 62/359 83/362 vt 0.413961 6.15339 f 63/179 83/363 62/177 vt 0.899561 6.15339 f 83/363 63/179 82/364 vt 0.984252 6.15339 f 65/183 82/365 63/181 vt 77.7559 6.15339 f 82/365 65/183 80/366 vt 71.0653 6.15339 f 67/187 80/367 65/185 vt 71.5509 6.15339 f 80/367 67/187 79/368 vt 55.4349 6.15339 f 69/191 79/369 67/189 vt 55.9205 6.15339 f 79/369 69/191 77/370 vt 0.2428 0.984252 f 57/361 60/371 62/359 vt -0.2428 0.984252 f 60/371 57/361 58/372 vt -25.6116 -8.59663 vt -24.4983 -8.59663 v -0.267711805035 -0.00519688187195 -0.342944863814 vt -25.055 -8.17609 f 97/373 88/374 98/375 vt -25.055 -8.17609 vt -24.4983 -8.59663 vt -24.7411 -8.17609 f 98/376 88/377 89/378 vt -25.055 -16.2439 vt -25.055 -16.6144 vt -24.7411 -16.6144 f 90/379 98/380 89/381 vt -25.3688 -16.6144 f 98/380 90/379 96/382 vt -25.3688 -8.17609 vt -25.6116 -8.59663 vt -25.055 -8.17609 f 96/383 97/384 98/385 vt -25.055 14.0039 vt -24.7411 14.0039 vt -24.4983 14.4245 f 6/386 23/387 5/388 g Mesh2 Group3 Group1 Model usemtl Material15 v -0.309472494656 -0.0297237483926 0.349686421342 vt -69.685 80.9055 v -0.279749634468 -0.0297237483926 -0.349686865444 vt -66.3386 2.16535 v -0.279749634468 -0.0297237483926 0.349686421342 vt -66.3386 80.9055 f 99/389 100/390 101/391 v -0.309472494656 -0.0297237483926 -0.349686865444 vt -69.685 2.16535 f 100/390 99/389 102/392 vt -80.9055 27.084 v -0.309472494656 -0.0489562970574 -0.349686865444 vt -2.16535 24.9186 vt -2.16535 27.084 f 99/393 103/394 102/395 v -0.309472494656 -0.0489562970574 0.349686421342 vt -80.9055 24.9186 f 103/394 99/393 104/396 v -0.309472494656 0.134629528242 0.36891959175 vt -83.0709 45.5879 f 99/393 105/397 104/396 v -0.309472494656 0.134629528242 0.349686421342 vt -80.9055 45.5879 f 105/397 99/393 106/398 vt -69.685 27.084 v 0.309472494656 0.134629528242 0.349686421342 vt 1.67487e-015 45.5879 vt -69.685 45.5879 f 99/399 107/400 106/401 vt -66.3386 27.084 f 101/402 107/400 99/399 v 0.279749634468 -0.0297237483926 0.349686421342 vt -3.34646 27.084 f 108/403 107/400 101/402 v 0.309472494656 -0.0297237483926 0.349686421342 vt 1.67487e-015 27.084 f 107/400 108/403 109/404 vt -3.34646 80.9055 v 0.309472494656 -0.0297237483926 -0.349686865444 vt 1.43766e-014 2.16535 vt 1.43766e-014 80.9055 f 108/405 110/406 109/407 v 0.279749634468 -0.0297237483926 -0.349686865444 vt -3.34646 2.16535 f 110/406 108/405 111/408 v 0.279749634468 -0.0917929570598 -0.349686865444 vt -2.16535 20.0958 f 108/393 112/409 111/395 v 0.279749634468 -0.0917929570598 0.349686421342 vt -80.9055 20.0958 f 112/409 108/393 113/410 v -0.279749634468 -0.0917929570598 0.349686421342 vt -66.3386 20.0958 vt -3.34646 20.0958 f 108/403 114/411 113/412 f 114/411 108/403 101/402 vt 2.16535 27.084 vt 80.9055 20.0958 vt 80.9055 27.084 f 100/413 114/414 101/415 v -0.279749634468 -0.0917929570598 -0.349686865444 vt 2.16535 20.0958 f 114/414 100/413 115/416 vt 66.3386 27.084 vt 3.34646 20.0958 vt 66.3386 20.0958 f 100/417 112/418 115/419 vt 3.34646 27.084 f 112/418 100/417 111/420 v -0.309472494656 -0.0297237483926 -0.36891959175 vt -69.685 0 vt -3.34646 2.16535 vt -66.3386 2.16535 f 116/421 111/422 100/423 v 0.309472494656 -0.0297237483926 -0.36891959175 vt 0 0 f 117/424 111/422 116/421 vt 0 2.16535 f 111/422 117/424 110/425 vt 0 27.084 v 0.309472494656 -0.134629528242 -0.349686865444 vt 2.16535 15.273 f 117/426 118/427 110/413 v 0.309472494656 -0.134629528242 -0.36891959175 vt 0 15.273 f 118/427 117/426 119/428 v -0.309472494656 -0.134629528242 -0.36891959175 vt -69.685 15.273 f 117/426 120/429 119/428 vt -69.685 27.084 f 120/429 117/426 116/430 f 102/395 120/428 116/426 v -0.309472494656 -0.134629528242 -0.349686865444 vt -2.16535 15.273 f 120/428 102/395 121/431 f 121/431 102/395 103/394 vt 69.685 27.084 v -0.302478776 -0.0489562970574 -0.349686865444 vt 68.8976 24.9186 vt 69.685 24.9186 f 102/432 122/433 103/434 f 100/417 122/433 102/432 f 115/419 122/433 100/417 v -0.302478776 -0.0917929570598 -0.349686865444 vt 68.8976 20.0958 f 122/433 115/419 123/435 v 0.302478776 -0.0917929570598 -0.349686865444 vt 0.787402 20.0958 f 124/436 123/435 115/419 vt 2.29462e-016 15.273 f 124/436 118/437 123/435 v 0.309472494656 -0.0489562970574 -0.349686865444 vt 2.29462e-016 24.9186 f 118/437 124/436 125/438 v 0.302478776 -0.0489562970574 -0.349686865444 vt 0.787402 24.9186 f 125/438 124/436 126/439 v 0.302478776 -0.0917929570598 0.349686421342 vt 2.16535 24.9186 f 127/414 126/440 124/416 v 0.302478776 -0.0489562970574 0.349686421342 vt 80.9055 24.9186 f 126/440 127/414 128/441 vt -0.787402 20.0958 v 0.309472494656 -0.0489562970574 0.349686421342 vt 1.67487e-015 24.9186 vt -0.787402 24.9186 f 127/442 129/443 128/444 v 0.309472494656 -0.134629528242 0.349686421342 vt 1.67487e-015 15.273 f 127/442 130/445 129/443 v -0.309472494656 -0.134629528242 0.349686421342 f 130/445 127/442 131/429 v -0.302478776 -0.0917929570598 0.349686421342 vt -68.8976 20.0958 f 132/446 131/429 127/442 vt -69.685 24.9186 f 131/429 132/446 104/447 v -0.302478776 -0.0489562970574 0.349686421342 vt -68.8976 24.9186 f 104/447 132/446 133/448 f 123/409 133/396 132/410 f 133/396 123/409 122/394 f 123/435 103/434 122/433 vt 69.685 15.273 f 123/435 121/449 103/434 f 121/449 123/435 118/437 vt 1.0325e-016 2.16535 vt 69.685 -3.6758e-015 vt 69.685 2.16535 f 118/450 120/451 121/452 vt 1.0325e-016 -3.6758e-015 f 120/451 118/450 119/453 vt 69.685 2.16535 vt 68.8976 80.9055 vt 68.8976 2.16535 f 103/454 133/455 122/456 vt 69.685 80.9055 f 133/455 103/454 104/457 vt 66.3386 80.9055 f 114/458 123/456 132/455 vt 66.3386 2.16535 f 123/456 114/458 115/459 f 132/446 113/412 114/411 f 132/446 127/442 113/412 vt 0.787402 80.9055 vt 3.34646 2.16535 vt 3.34646 80.9055 f 127/460 112/461 113/462 vt 0.787402 2.16535 f 112/461 127/460 124/463 f 124/436 115/419 112/418 vt 0.787402 20.0958 f 111/420 124/464 112/418 vt 0.787402 24.9186 f 124/464 111/420 126/465 vt 0 24.9186 f 126/465 111/420 125/466 f 125/466 111/420 110/426 f 110/413 118/427 125/440 f 129/441 110/413 125/440 f 110/413 129/441 109/415 v 0.309472494656 -0.134629528242 0.36891959175 vt 83.0709 15.273 f 129/441 134/467 109/415 vt 80.9055 15.273 f 134/467 129/441 130/468 vt 0 83.0709 vt 0 80.9055 f 131/457 134/469 130/470 v -0.309472494656 -0.134629528242 0.36891959175 vt 69.685 83.0709 f 134/469 131/457 135/471 vt -80.9055 15.273 vt -83.0709 15.273 f 131/472 105/397 135/473 f 104/396 105/397 131/472 vt 69.685 45.5879 f 105/474 134/428 135/449 v 0.309472494656 0.134629528242 0.36891959175 vt 0 45.5879 f 134/428 105/474 136/475 vt -69.685 83.0709 f 105/476 107/470 136/469 vt -69.685 80.9055 f 107/470 105/476 106/477 vt 80.9055 45.5879 vt 83.0709 45.5879 f 107/478 134/467 136/479 f 109/415 134/467 107/478 vt 0.787402 2.16535 f 126/480 129/470 125/425 vt 0.787402 80.9055 f 129/470 126/480 128/481 vt -69.685 2.16535 f 116/421 100/423 102/482
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./.github/workflows/tfg-nigthly-pypi.yml
# Publishes tfg-nightly name: Deploy tfg-nightly to pypi on: schedule: # * is a special character in YAML so you have to quote this string # runs daily at 00:30 am - cron: '30 0 * * *' jobs: deploy: if: github.repository == 'tensorflow/graphics' # prevents action from running on forks runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install system dependencies run: | sudo xargs apt-get update sudo xargs apt-get -y install < requirements.unix - name: Install pip requirements run: | python -m pip install --upgrade pip pip install -U -r requirements.txt pip install -U pytest pip install -U setuptools wheel pip install -U twine - name: Build ops run: | bazel build tensorflow_graphics/... --define=BASEDIR=$(pwd) --sandbox_writable_path=$(pwd) bazel clean --expunge - name: Run python tests env: MESA_GL_VERSION_OVERRIDE: 4.5 MESA_GLSL_VERSION_OVERRIDE: 450 run: | pytest tensorflow_graphics - name: Build pip package and install run: | python setup.py sdist bdist_wheel --nightly pip install dist/*.whl - name: Test install run: | cd $(mktemp -d) && python -c 'import tensorflow_graphics as tfg' - name: Publish to PyPi # https://pypi.org/project/tfg-nightly env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | twine upload dist/*
# Publishes tfg-nightly name: Deploy tfg-nightly to pypi on: schedule: # * is a special character in YAML so you have to quote this string # runs daily at 00:30 am - cron: '30 0 * * *' jobs: deploy: if: github.repository == 'tensorflow/graphics' # prevents action from running on forks runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install system dependencies run: | sudo xargs apt-get update sudo xargs apt-get -y install < requirements.unix - name: Install pip requirements run: | python -m pip install --upgrade pip pip install -U -r requirements.txt pip install -U pytest pip install -U setuptools wheel pip install -U twine - name: Build ops run: | bazel build tensorflow_graphics/... --define=BASEDIR=$(pwd) --sandbox_writable_path=$(pwd) bazel clean --expunge - name: Run python tests env: MESA_GL_VERSION_OVERRIDE: 4.5 MESA_GLSL_VERSION_OVERRIDE: 450 run: | pytest tensorflow_graphics - name: Build pip package and install run: | python setup.py sdist bdist_wheel --nightly pip install dist/*.whl - name: Test install run: | cd $(mktemp -d) && python -c 'import tensorflow_graphics as tfg' - name: Publish to PyPi # https://pypi.org/project/tfg-nightly env: TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} run: | twine upload dist/*
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/representation/tests/point_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for point.""" import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import point from tensorflow_graphics.util import test_case class PointTest(test_case.TestCase): @parameterized.parameters( ((None,), (None,), (None,)), ((None, None), (None, None), (None, None)), ((3,), (3,), (3,)), ((2, 3), (2, 3), (2, 3)), ((1, 2, 3), (2, 2, 3), (2, 3)), ) def test_distance_to_ray_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(point.distance_to_ray, shapes) @parameterized.parameters( ("must have the same number of dimensions", (0,), (None,), (None,)), ("must have the same number of dimensions", (None,), (0,), (None,)), ("must have the same number of dimensions", (None,), (None,), (0,)), ("must have the same number of dimensions", (0,), (1,), (1,)), ("must have the same number of dimensions", (2,), (1,), (2,)), ("must have the same number of dimensions", (2, 3), (2, 2), (2, 0)), ("Not all batch dimensions are broadcast-compatible.", (0, 3), (3, 3), (3, 3)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (2, 3), (3, 3)), ) def test_distance_to_ray_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(point.distance_to_ray, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_distance_to_ray_jacobian_random(self): """Tests the Jacobian of the distance to ray function.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_init = np.random.random(size=tensor_shape + [3]) origin_init = np.random.random(size=tensor_shape + [3]) direction_init = np.random.random(size=tensor_shape + [3]) direction_init /= np.maximum( np.linalg.norm(direction_init, axis=-1, keepdims=True), eps) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(x, origin_init, direction_init), [point_init]) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(point_init, x, direction_init), [origin_init]) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(point_init, origin_init, x), [direction_init]) @parameterized.parameters( (((1., 1., 1.), (-10., 1., 1.), (1., 0., 0.)), ((0.,),)),) def test_distance_to_ray_preset(self, test_inputs, test_outputs): """Tests 0 distance from point to ray.""" self.assert_output_is_correct(point.distance_to_ray, test_inputs, test_outputs) def test_distance_to_ray_random(self): """Tests distance point to ray.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_origin = np.random.random(size=tensor_shape + [3]) random_direction = np.random.random(size=tensor_shape + [3]) random_direction /= np.maximum( np.linalg.norm(random_direction, axis=-1, keepdims=True), eps) random_distances = np.random.random(size=tensor_shape + [1]) * 1000 x, y, _, _ = np.split(random_direction, (1, 2, 3), axis=-1) # Find perpendicular vector. perp = np.concatenate((-y, x, np.zeros_like(x)), axis=-1) perp /= np.maximum(np.linalg.norm(perp, axis=-1, keepdims=True), eps) # Choose a point on perpendicular unit vector at the good distance. points = random_origin + perp * random_distances distance = point.distance_to_ray(points, random_origin, random_direction) self.assertAllClose(random_distances, distance) @parameterized.parameters( ((None,), (None,), (None,)), ((None, None), (None, None), (None, None)), ((3,), (3,), (3,)), ((2, 3), (2, 3), (2, 3)), ((1, 2, 3), (2, 2, 3), (2, 3)), ) def test_project_to_ray_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(point.project_to_ray, shapes) @parameterized.parameters( ("must have the same number of dimensions", (0,), (None,), (None,)), ("must have the same number of dimensions", (None,), (0,), (None,)), ("must have the same number of dimensions", (None,), (None,), (0,)), ("must have the same number of dimensions", (0,), (1,), (1,)), ("must have the same number of dimensions", (2,), (1,), (2,)), ("must have the same number of dimensions", (2, 3), (2, 2), (2, 0)), ("Not all batch dimensions are broadcast-compatible.", (0, 3), (3, 3), (3, 3)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (2, 3), (3, 3)), ) def test_project_to_ray_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(point.project_to_ray, error_msg, shapes) @parameterized.parameters( (((1., 1., 1.), (-10., 1., 1.), (1., 0., 0.)), ((1., 1., 1.),)),) def test_project_to_ray_preset(self, test_inputs, test_outputs): """Tests that a point on a ray projects to itself.""" self.assert_output_is_correct(point.project_to_ray, test_inputs, test_outputs) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_project_to_ray_jacobian_random(self): """Tests the Jacobian of the distance to ray function.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_init = np.random.random(size=tensor_shape + [3]) origin_init = np.random.random(size=tensor_shape + [3]) direction_init = np.random.random(size=tensor_shape + [3]) direction_init /= np.maximum( np.linalg.norm(direction_init, axis=-1, keepdims=True), eps) point_tensor = tf.convert_to_tensor(value=point_init) origin_tensor = tf.convert_to_tensor(value=origin_init) direction_tensor = tf.convert_to_tensor(value=direction_init) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(x, origin_tensor, direction_tensor), [point_init]) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(point_tensor, x, direction_tensor), [origin_init]) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(point_tensor, origin_tensor, x), [direction_init]) def test_project_to_ray_random(self): """Tests the function that projects a point to a ray.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_origin = np.random.random(size=tensor_shape + [3]) random_direction = np.random.random(size=tensor_shape + [3]) random_direction /= np.maximum( np.linalg.norm(random_direction, axis=-1, keepdims=True), eps) random_distances = np.random.random(size=tensor_shape + [1]) * 1000 x, y, _, _ = np.split(random_direction, (1, 2, 3), axis=-1) # Find perpendicular vector. perp = np.concatenate((-y, x, np.zeros_like(x)), axis=-1) perp /= np.maximum(np.linalg.norm(perp, axis=-1, keepdims=True), eps) # Choose a point on perpendicular unit vector at the good distance. points = random_origin + perp * random_distances points = point.project_to_ray(points, random_origin, random_direction) self.assertAllClose(random_origin, points) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for point.""" import sys from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import point from tensorflow_graphics.util import test_case class PointTest(test_case.TestCase): @parameterized.parameters( ((None,), (None,), (None,)), ((None, None), (None, None), (None, None)), ((3,), (3,), (3,)), ((2, 3), (2, 3), (2, 3)), ((1, 2, 3), (2, 2, 3), (2, 3)), ) def test_distance_to_ray_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(point.distance_to_ray, shapes) @parameterized.parameters( ("must have the same number of dimensions", (0,), (None,), (None,)), ("must have the same number of dimensions", (None,), (0,), (None,)), ("must have the same number of dimensions", (None,), (None,), (0,)), ("must have the same number of dimensions", (0,), (1,), (1,)), ("must have the same number of dimensions", (2,), (1,), (2,)), ("must have the same number of dimensions", (2, 3), (2, 2), (2, 0)), ("Not all batch dimensions are broadcast-compatible.", (0, 3), (3, 3), (3, 3)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (2, 3), (3, 3)), ) def test_distance_to_ray_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(point.distance_to_ray, error_msg, shapes) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_distance_to_ray_jacobian_random(self): """Tests the Jacobian of the distance to ray function.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_init = np.random.random(size=tensor_shape + [3]) origin_init = np.random.random(size=tensor_shape + [3]) direction_init = np.random.random(size=tensor_shape + [3]) direction_init /= np.maximum( np.linalg.norm(direction_init, axis=-1, keepdims=True), eps) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(x, origin_init, direction_init), [point_init]) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(point_init, x, direction_init), [origin_init]) self.assert_jacobian_is_correct_fn( lambda x: point.distance_to_ray(point_init, origin_init, x), [direction_init]) @parameterized.parameters( (((1., 1., 1.), (-10., 1., 1.), (1., 0., 0.)), ((0.,),)),) def test_distance_to_ray_preset(self, test_inputs, test_outputs): """Tests 0 distance from point to ray.""" self.assert_output_is_correct(point.distance_to_ray, test_inputs, test_outputs) def test_distance_to_ray_random(self): """Tests distance point to ray.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_origin = np.random.random(size=tensor_shape + [3]) random_direction = np.random.random(size=tensor_shape + [3]) random_direction /= np.maximum( np.linalg.norm(random_direction, axis=-1, keepdims=True), eps) random_distances = np.random.random(size=tensor_shape + [1]) * 1000 x, y, _, _ = np.split(random_direction, (1, 2, 3), axis=-1) # Find perpendicular vector. perp = np.concatenate((-y, x, np.zeros_like(x)), axis=-1) perp /= np.maximum(np.linalg.norm(perp, axis=-1, keepdims=True), eps) # Choose a point on perpendicular unit vector at the good distance. points = random_origin + perp * random_distances distance = point.distance_to_ray(points, random_origin, random_direction) self.assertAllClose(random_distances, distance) @parameterized.parameters( ((None,), (None,), (None,)), ((None, None), (None, None), (None, None)), ((3,), (3,), (3,)), ((2, 3), (2, 3), (2, 3)), ((1, 2, 3), (2, 2, 3), (2, 3)), ) def test_project_to_ray_exception_not_raised(self, *shapes): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(point.project_to_ray, shapes) @parameterized.parameters( ("must have the same number of dimensions", (0,), (None,), (None,)), ("must have the same number of dimensions", (None,), (0,), (None,)), ("must have the same number of dimensions", (None,), (None,), (0,)), ("must have the same number of dimensions", (0,), (1,), (1,)), ("must have the same number of dimensions", (2,), (1,), (2,)), ("must have the same number of dimensions", (2, 3), (2, 2), (2, 0)), ("Not all batch dimensions are broadcast-compatible.", (0, 3), (3, 3), (3, 3)), ("Not all batch dimensions are broadcast-compatible.", (1, 3), (2, 3), (3, 3)), ) def test_project_to_ray_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(point.project_to_ray, error_msg, shapes) @parameterized.parameters( (((1., 1., 1.), (-10., 1., 1.), (1., 0., 0.)), ((1., 1., 1.),)),) def test_project_to_ray_preset(self, test_inputs, test_outputs): """Tests that a point on a ray projects to itself.""" self.assert_output_is_correct(point.project_to_ray, test_inputs, test_outputs) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_project_to_ray_jacobian_random(self): """Tests the Jacobian of the distance to ray function.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() point_init = np.random.random(size=tensor_shape + [3]) origin_init = np.random.random(size=tensor_shape + [3]) direction_init = np.random.random(size=tensor_shape + [3]) direction_init /= np.maximum( np.linalg.norm(direction_init, axis=-1, keepdims=True), eps) point_tensor = tf.convert_to_tensor(value=point_init) origin_tensor = tf.convert_to_tensor(value=origin_init) direction_tensor = tf.convert_to_tensor(value=direction_init) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(x, origin_tensor, direction_tensor), [point_init]) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(point_tensor, x, direction_tensor), [origin_init]) self.assert_jacobian_is_correct_fn( lambda x: point.project_to_ray(point_tensor, origin_tensor, x), [direction_init]) def test_project_to_ray_random(self): """Tests the function that projects a point to a ray.""" eps = sys.float_info.epsilon tensor_size = np.random.randint(3) tensor_shape = np.random.randint(1, 10, size=(tensor_size)).tolist() random_origin = np.random.random(size=tensor_shape + [3]) random_direction = np.random.random(size=tensor_shape + [3]) random_direction /= np.maximum( np.linalg.norm(random_direction, axis=-1, keepdims=True), eps) random_distances = np.random.random(size=tensor_shape + [1]) * 1000 x, y, _, _ = np.split(random_direction, (1, 2, 3), axis=-1) # Find perpendicular vector. perp = np.concatenate((-y, x, np.zeros_like(x)), axis=-1) perp /= np.maximum(np.linalg.norm(perp, axis=-1, keepdims=True), eps) # Choose a point on perpendicular unit vector at the good distance. points = random_origin + perp * random_distances points = point.project_to_ray(points, random_origin, random_direction) self.assertAllClose(random_origin, points) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/projects/neural_voxel_renderer/train.ipynb
{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9C18T_ESG5Qx" }, "source": [ "##### Copyright 2020 Google LLC." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "prnvFmh4G6_H" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "RMb8qzxEHFwS" }, "source": [ "# Neural Voxel Renderer\n", "\n", "\n", "![](https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/teaser2-01.png)\n", "\n", "This notebook illustrates how to train [Neural Voxel Renderer](https://arxiv.org/abs/1912.04591) (CVPR2020) in Tensorflow 2.\n", "\n", "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/projects/neural_voxel_renderer/train.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/projects/neural_voxel_renderer/train.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", " \u003c/td\u003e\n", "\u003c/table\u003e\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fkfUjFmxHnRz" }, "source": [ "## Setup and imports\n", "\n", "If Tensorflow Graphics is not installed on your system, the following cell can install the Tensorflow Graphics package for you.\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "QAvt9i8RHroc" }, "outputs": [], "source": [ "!pip install tensorflow_graphics" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vDWSNfpF3sd4" }, "outputs": [], "source": [ "import numpy as np\n", "import tensorflow as tf\n", "from tensorflow_graphics.projects.neural_voxel_renderer import helpers\n", "from tensorflow_graphics.projects.neural_voxel_renderer import models\n", "\n", "import datetime\n", "import matplotlib.pyplot as plt\n", "import os\n", "import re\n", "import time\n", "\n", "VOXEL_SIZE = (128, 128, 128, 4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5ok8IKzUIWCG" }, "source": [ "## Dataset loading\n", "\n", "We store our data in TFRecords with custom protobuf messages. Each training element contains the input voxels, the voxel rendering, the light position and the target image. The data is preprocessed (eg the colored voxels have been rendered and placed accordingly). See [this](https://) colab on how to generate the training/testing TFRecords.\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "gZG0Vn7M33Vl" }, "outputs": [], "source": [ "# Functions for dataset generation from a set of TFRecords.\n", "decode_proto = tf.compat.v1.io.decode_proto\n", "\n", "\n", "def tf_image_normalize(image):\n", " \"\"\"Normalizes the image [-1, 1].\"\"\"\n", " return (2 * tf.cast(image, tf.float32) / 255.) - 1\n", "\n", "\n", "def neural_voxel_plus_proto_get(element):\n", " \"\"\"Extracts the contents from a VoxelSample proto to tensors.\"\"\"\n", " _, values = decode_proto(element,\n", " \"giotto_blender.NeuralVoxelPlusSample\",\n", " [\"name\",\n", " \"voxel_data\",\n", " \"rerendering_data\",\n", " \"image_data\",\n", " \"light_position\"],\n", " [tf.string,\n", " tf.string,\n", " tf.string,\n", " tf.string,\n", " tf.float32])\n", " filename = tf.squeeze(values[0])\n", " voxel_data = tf.squeeze(values[1])\n", " rerendering_data = tf.squeeze(values[2])\n", " image_data = tf.squeeze(values[3])\n", " light_position = values[4]\n", " voxels = tf.io.decode_raw(voxel_data, out_type=tf.uint8)\n", " voxels = tf.cast(tf.reshape(voxels, VOXEL_SIZE), tf.float32) / 255.0\n", " rerendering = tf.cast(tf.image.decode_image(rerendering_data, channels=3),\n", " tf.float32)\n", " rerendering = tf_image_normalize(rerendering)\n", " image = tf.cast(tf.image.decode_image(image_data, channels=3), tf.float32)\n", " image = tf_image_normalize(image)\n", " return filename, voxels, rerendering, image, light_position\n", "\n", "\n", "def _expand_tfrecords_pattern(tfr_pattern):\n", " \"\"\"Helper function to expand a tfrecord patter\"\"\"\n", " def format_shards(m):\n", " return '{}-?????-of-{:0\u003e5}{}'.format(*m.groups())\n", " tfr_pattern = re.sub(r'^([^@]+)@(\\d+)([^@]+)$', format_shards, tfr_pattern)\n", " return tfr_pattern\n", "\n", "\n", "def tfrecords_to_dataset(tfrecords_pattern,\n", " mapping_func,\n", " batch_size,\n", " buffer_size=5000):\n", " \"\"\"Generates a TF Dataset from a rio pattern.\"\"\"\n", " with tf.name_scope('Input/'):\n", " tfrecords_pattern = _expand_tfrecords_pattern(tfrecords_pattern)\n", " dataset = tf.data.Dataset.list_files(tfrecords_pattern, shuffle=True)\n", " dataset = dataset.interleave(tf.data.TFRecordDataset, cycle_length=16)\n", " dataset = dataset.shuffle(buffer_size=buffer_size)\n", " dataset = dataset.map(mapping_func)\n", " dataset = dataset.batch(batch_size)\n", " return dataset" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "DMwsbJ6RL-Wc" }, "outputs": [], "source": [ "# Download the example data, licensed under the Apache License, Version 2.0\n", "!rm -rf /tmp/tfrecords_dir/\n", "!mkdir /tmp/tfrecords_dir/\n", "!wget -P /tmp/tfrecords_dir/ https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/train-00012-of-00100.tfrecord" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vE7eors94Dq9" }, "outputs": [], "source": [ "tfrecords_dir = '/tmp/tfrecords_dir/'\n", "tfrecords_pattern = os.path.join(tfrecords_dir, 'train@100.tfrecord')\n", "\n", "batch_size = 5\n", "mapping_function = neural_voxel_plus_proto_get\n", "dataset = tfrecords_to_dataset(tfrecords_pattern, mapping_function, batch_size)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "iGlgx3ly5eLb" }, "outputs": [], "source": [ "# Visualize some examples\n", "_, ax = plt.subplots(1, 4, figsize=(10, 10))\n", "i = 0\n", "for a in dataset.take(4):\n", " (filename,\n", " voxels,\n", " vox_render,\n", " target,\n", " light_position) = a\n", " ax[i].imshow(target[0]*0.5+0.5)\n", " ax[i].axis('off')\n", " i += 1\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "X_WgOOhjPayp" }, "source": [ "## Train the model\n", "\n", "NVR+ is trained with Adam optimizer and L1 and perceptual VGG loss. " ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vAjbsYCQs8n8" }, "outputs": [], "source": [ "# ==============================================================================\n", "# Defining model and optimizer\n", "LEARNING_RATE = 0.002\n", "\n", "nvr_plus_model = models.neural_voxel_renderer_plus_tf2()\n", "optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n", "\n", "# Saving and logging directories\n", "checkpoint_dir = '/tmp/checkpoints'\n", "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n", "checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=nvr_plus_model)\n", "log_dir=\"/tmp/logs/\"\n", "summary_writer = tf.summary.create_file_writer(\n", " log_dir + \"fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n", "\n", "# ==============================================================================\n", "# VGG loss\n", "VGG_LOSS_LAYER_NAMES = ['block1_conv1', 'block2_conv1']\n", "VGG_LOSS_LAYER_WEIGHTS = [1.0, 0.1]\n", "VGG_LOSS_WEIGHT = 0.001\n", "\n", "def vgg_layers(layer_names):\n", " \"\"\" Creates a vgg model that returns a list of intermediate output values.\"\"\"\n", " # Load our model. Load pretrained VGG, trained on imagenet data\n", " vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')\n", " vgg.trainable = False\n", " outputs = [vgg.get_layer(name).output for name in layer_names]\n", " model = tf.keras.Model([vgg.input], outputs)\n", " return model\n", "\n", "\n", "vgg_extractor = vgg_layers(VGG_LOSS_LAYER_NAMES)\n", "\n", "# ==============================================================================\n", "# Total loss\n", "def network_loss(output, target):\n", " # L1 loss\n", " l1_loss = tf.reduce_mean(tf.abs(target - output))\n", " # VGG loss\n", " vgg_output = vgg_extractor((output*0.5+0.5)*255)\n", " vgg_target = vgg_extractor((target*0.5+0.5)*255)\n", " vgg_loss = 0\n", " for l in range(len(VGG_LOSS_LAYER_WEIGHTS)):\n", " layer_loss = tf.reduce_mean(tf.square(vgg_target[l] - vgg_output[l]))\n", " vgg_loss += VGG_LOSS_LAYER_WEIGHTS[l]*layer_loss\n", " # Final loss\n", " total_loss = l1_loss + VGG_LOSS_WEIGHT*vgg_loss\n", " return l1_loss, vgg_loss, total_loss" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "SViS-K6OUgCC" }, "outputs": [], "source": [ "@tf.function\n", "def train_step(input_voxels, input_rendering, input_light, target, epoch):\n", " with tf.GradientTape() as tape:\n", " network_output = nvr_plus_model([input_voxels, \n", " input_rendering, \n", " input_light],\n", " training=True)\n", " l1_loss, vgg_loss, total_loss = network_loss(network_output, target)\n", " network_gradients = tape.gradient(total_loss,\n", " nvr_plus_model.trainable_variables)\n", " optimizer.apply_gradients(zip(network_gradients,\n", " nvr_plus_model.trainable_variables))\n", "\n", " with summary_writer.as_default():\n", " tf.summary.scalar('total_loss', total_loss, step=epoch)\n", " tf.summary.scalar('l1_loss', l1_loss, step=epoch)\n", " tf.summary.scalar('vgg_loss', vgg_loss, step=epoch)\n", " tf.summary.image('Vox_rendering', \n", " input_rendering*0.5+0.5, \n", " step=epoch, \n", " max_outputs=4)\n", " tf.summary.image('Prediction', \n", " network_output*0.5+0.5, \n", " step=epoch, \n", " max_outputs=4)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "FO3EHzQ66yxD" }, "outputs": [], "source": [ "def training_loop(train_ds, epochs):\n", " for epoch in range(epochs):\n", " start = time.time()\n", "\n", " # Train\n", " for n, (_, voxels, vox_rendering, target, light) in train_ds.enumerate():\n", " print('.', end='')\n", " if (n+1) % 100 == 0:\n", " print()\n", " train_step(voxels, vox_rendering, light, target, epoch)\n", " print()\n", "\n", " # saving (checkpoint) the model every 20 epochs\n", " if (epoch + 1) % 20 == 0:\n", " checkpoint.save(file_prefix = checkpoint_prefix)\n", "\n", " print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n", " time.time()-start))\n", " checkpoint.save(file_prefix = checkpoint_prefix)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "yuj29vLY6zPg" }, "outputs": [], "source": [ "NUMBER_OF_EPOCHS = 100\n", "training_loop(dataset, NUMBER_OF_EPOCHS)" ] } ], "metadata": { "colab": { "last_runtime": { "build_target": "", "kind": "local" }, "name": "nvr plus training.ipynb", "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9C18T_ESG5Qx" }, "source": [ "##### Copyright 2020 Google LLC." ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "cellView": "form", "colab": {}, "colab_type": "code", "id": "prnvFmh4G6_H" }, "outputs": [], "source": [ "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "RMb8qzxEHFwS" }, "source": [ "# Neural Voxel Renderer\n", "\n", "\n", "![](https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/teaser2-01.png)\n", "\n", "This notebook illustrates how to train [Neural Voxel Renderer](https://arxiv.org/abs/1912.04591) (CVPR2020) in Tensorflow 2.\n", "\n", "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/graphics/blob/master/tensorflow_graphics/projects/neural_voxel_renderer/train.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n", " \u003c/td\u003e\n", " \u003ctd\u003e\n", " \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/projects/neural_voxel_renderer/train.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n", " \u003c/td\u003e\n", "\u003c/table\u003e\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fkfUjFmxHnRz" }, "source": [ "## Setup and imports\n", "\n", "If Tensorflow Graphics is not installed on your system, the following cell can install the Tensorflow Graphics package for you.\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "QAvt9i8RHroc" }, "outputs": [], "source": [ "!pip install tensorflow_graphics" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vDWSNfpF3sd4" }, "outputs": [], "source": [ "import numpy as np\n", "import tensorflow as tf\n", "from tensorflow_graphics.projects.neural_voxel_renderer import helpers\n", "from tensorflow_graphics.projects.neural_voxel_renderer import models\n", "\n", "import datetime\n", "import matplotlib.pyplot as plt\n", "import os\n", "import re\n", "import time\n", "\n", "VOXEL_SIZE = (128, 128, 128, 4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5ok8IKzUIWCG" }, "source": [ "## Dataset loading\n", "\n", "We store our data in TFRecords with custom protobuf messages. Each training element contains the input voxels, the voxel rendering, the light position and the target image. The data is preprocessed (eg the colored voxels have been rendered and placed accordingly). See [this](https://) colab on how to generate the training/testing TFRecords.\n" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "gZG0Vn7M33Vl" }, "outputs": [], "source": [ "# Functions for dataset generation from a set of TFRecords.\n", "decode_proto = tf.compat.v1.io.decode_proto\n", "\n", "\n", "def tf_image_normalize(image):\n", " \"\"\"Normalizes the image [-1, 1].\"\"\"\n", " return (2 * tf.cast(image, tf.float32) / 255.) - 1\n", "\n", "\n", "def neural_voxel_plus_proto_get(element):\n", " \"\"\"Extracts the contents from a VoxelSample proto to tensors.\"\"\"\n", " _, values = decode_proto(element,\n", " \"giotto_blender.NeuralVoxelPlusSample\",\n", " [\"name\",\n", " \"voxel_data\",\n", " \"rerendering_data\",\n", " \"image_data\",\n", " \"light_position\"],\n", " [tf.string,\n", " tf.string,\n", " tf.string,\n", " tf.string,\n", " tf.float32])\n", " filename = tf.squeeze(values[0])\n", " voxel_data = tf.squeeze(values[1])\n", " rerendering_data = tf.squeeze(values[2])\n", " image_data = tf.squeeze(values[3])\n", " light_position = values[4]\n", " voxels = tf.io.decode_raw(voxel_data, out_type=tf.uint8)\n", " voxels = tf.cast(tf.reshape(voxels, VOXEL_SIZE), tf.float32) / 255.0\n", " rerendering = tf.cast(tf.image.decode_image(rerendering_data, channels=3),\n", " tf.float32)\n", " rerendering = tf_image_normalize(rerendering)\n", " image = tf.cast(tf.image.decode_image(image_data, channels=3), tf.float32)\n", " image = tf_image_normalize(image)\n", " return filename, voxels, rerendering, image, light_position\n", "\n", "\n", "def _expand_tfrecords_pattern(tfr_pattern):\n", " \"\"\"Helper function to expand a tfrecord patter\"\"\"\n", " def format_shards(m):\n", " return '{}-?????-of-{:0\u003e5}{}'.format(*m.groups())\n", " tfr_pattern = re.sub(r'^([^@]+)@(\\d+)([^@]+)$', format_shards, tfr_pattern)\n", " return tfr_pattern\n", "\n", "\n", "def tfrecords_to_dataset(tfrecords_pattern,\n", " mapping_func,\n", " batch_size,\n", " buffer_size=5000):\n", " \"\"\"Generates a TF Dataset from a rio pattern.\"\"\"\n", " with tf.name_scope('Input/'):\n", " tfrecords_pattern = _expand_tfrecords_pattern(tfrecords_pattern)\n", " dataset = tf.data.Dataset.list_files(tfrecords_pattern, shuffle=True)\n", " dataset = dataset.interleave(tf.data.TFRecordDataset, cycle_length=16)\n", " dataset = dataset.shuffle(buffer_size=buffer_size)\n", " dataset = dataset.map(mapping_func)\n", " dataset = dataset.batch(batch_size)\n", " return dataset" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "DMwsbJ6RL-Wc" }, "outputs": [], "source": [ "# Download the example data, licensed under the Apache License, Version 2.0\n", "!rm -rf /tmp/tfrecords_dir/\n", "!mkdir /tmp/tfrecords_dir/\n", "!wget -P /tmp/tfrecords_dir/ https://storage.googleapis.com/tensorflow-graphics/notebooks/neural_voxel_renderer/train-00012-of-00100.tfrecord" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vE7eors94Dq9" }, "outputs": [], "source": [ "tfrecords_dir = '/tmp/tfrecords_dir/'\n", "tfrecords_pattern = os.path.join(tfrecords_dir, 'train@100.tfrecord')\n", "\n", "batch_size = 5\n", "mapping_function = neural_voxel_plus_proto_get\n", "dataset = tfrecords_to_dataset(tfrecords_pattern, mapping_function, batch_size)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "iGlgx3ly5eLb" }, "outputs": [], "source": [ "# Visualize some examples\n", "_, ax = plt.subplots(1, 4, figsize=(10, 10))\n", "i = 0\n", "for a in dataset.take(4):\n", " (filename,\n", " voxels,\n", " vox_render,\n", " target,\n", " light_position) = a\n", " ax[i].imshow(target[0]*0.5+0.5)\n", " ax[i].axis('off')\n", " i += 1\n", "plt.show()\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "X_WgOOhjPayp" }, "source": [ "## Train the model\n", "\n", "NVR+ is trained with Adam optimizer and L1 and perceptual VGG loss. " ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "vAjbsYCQs8n8" }, "outputs": [], "source": [ "# ==============================================================================\n", "# Defining model and optimizer\n", "LEARNING_RATE = 0.002\n", "\n", "nvr_plus_model = models.neural_voxel_renderer_plus_tf2()\n", "optimizer = tf.keras.optimizers.Adam(learning_rate=LEARNING_RATE)\n", "\n", "# Saving and logging directories\n", "checkpoint_dir = '/tmp/checkpoints'\n", "checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\n", "checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=nvr_plus_model)\n", "log_dir=\"/tmp/logs/\"\n", "summary_writer = tf.summary.create_file_writer(\n", " log_dir + \"fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n", "\n", "# ==============================================================================\n", "# VGG loss\n", "VGG_LOSS_LAYER_NAMES = ['block1_conv1', 'block2_conv1']\n", "VGG_LOSS_LAYER_WEIGHTS = [1.0, 0.1]\n", "VGG_LOSS_WEIGHT = 0.001\n", "\n", "def vgg_layers(layer_names):\n", " \"\"\" Creates a vgg model that returns a list of intermediate output values.\"\"\"\n", " # Load our model. Load pretrained VGG, trained on imagenet data\n", " vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')\n", " vgg.trainable = False\n", " outputs = [vgg.get_layer(name).output for name in layer_names]\n", " model = tf.keras.Model([vgg.input], outputs)\n", " return model\n", "\n", "\n", "vgg_extractor = vgg_layers(VGG_LOSS_LAYER_NAMES)\n", "\n", "# ==============================================================================\n", "# Total loss\n", "def network_loss(output, target):\n", " # L1 loss\n", " l1_loss = tf.reduce_mean(tf.abs(target - output))\n", " # VGG loss\n", " vgg_output = vgg_extractor((output*0.5+0.5)*255)\n", " vgg_target = vgg_extractor((target*0.5+0.5)*255)\n", " vgg_loss = 0\n", " for l in range(len(VGG_LOSS_LAYER_WEIGHTS)):\n", " layer_loss = tf.reduce_mean(tf.square(vgg_target[l] - vgg_output[l]))\n", " vgg_loss += VGG_LOSS_LAYER_WEIGHTS[l]*layer_loss\n", " # Final loss\n", " total_loss = l1_loss + VGG_LOSS_WEIGHT*vgg_loss\n", " return l1_loss, vgg_loss, total_loss" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "SViS-K6OUgCC" }, "outputs": [], "source": [ "@tf.function\n", "def train_step(input_voxels, input_rendering, input_light, target, epoch):\n", " with tf.GradientTape() as tape:\n", " network_output = nvr_plus_model([input_voxels, \n", " input_rendering, \n", " input_light],\n", " training=True)\n", " l1_loss, vgg_loss, total_loss = network_loss(network_output, target)\n", " network_gradients = tape.gradient(total_loss,\n", " nvr_plus_model.trainable_variables)\n", " optimizer.apply_gradients(zip(network_gradients,\n", " nvr_plus_model.trainable_variables))\n", "\n", " with summary_writer.as_default():\n", " tf.summary.scalar('total_loss', total_loss, step=epoch)\n", " tf.summary.scalar('l1_loss', l1_loss, step=epoch)\n", " tf.summary.scalar('vgg_loss', vgg_loss, step=epoch)\n", " tf.summary.image('Vox_rendering', \n", " input_rendering*0.5+0.5, \n", " step=epoch, \n", " max_outputs=4)\n", " tf.summary.image('Prediction', \n", " network_output*0.5+0.5, \n", " step=epoch, \n", " max_outputs=4)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "FO3EHzQ66yxD" }, "outputs": [], "source": [ "def training_loop(train_ds, epochs):\n", " for epoch in range(epochs):\n", " start = time.time()\n", "\n", " # Train\n", " for n, (_, voxels, vox_rendering, target, light) in train_ds.enumerate():\n", " print('.', end='')\n", " if (n+1) % 100 == 0:\n", " print()\n", " train_step(voxels, vox_rendering, light, target, epoch)\n", " print()\n", "\n", " # saving (checkpoint) the model every 20 epochs\n", " if (epoch + 1) % 20 == 0:\n", " checkpoint.save(file_prefix = checkpoint_prefix)\n", "\n", " print ('Time taken for epoch {} is {} sec\\n'.format(epoch + 1,\n", " time.time()-start))\n", " checkpoint.save(file_prefix = checkpoint_prefix)" ] }, { "cell_type": "code", "execution_count": 0, "metadata": { "colab": {}, "colab_type": "code", "id": "yuj29vLY6zPg" }, "outputs": [], "source": [ "NUMBER_OF_EPOCHS = 100\n", "training_loop(dataset, NUMBER_OF_EPOCHS)" ] } ], "metadata": { "colab": { "last_runtime": { "build_target": "", "kind": "local" }, "name": "nvr plus training.ipynb", "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/geometry/transformation/quaternion.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow quaternion utility functions. A quaternion is written as $$q = xi + yj + zk + w$$, where $$i,j,k$$ forms the three bases of the imaginary part. The functions implemented in this file use the Hamilton convention where $$i^2 = j^2 = k^2 = ijk = -1$$. A quaternion is stored in a 4-D vector $$[x, y, z, w]^T$$. More details about Hamiltonian quaternions can be found on [this page.] (https://en.wikipedia.org/wiki/Quaternion) Note: Some of the functions expect normalized quaternions as inputs where $$x^2 + y^2 + z^2 + w^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles): """Builds a quaternion from sines and cosines of half Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of half Euler angles. cos_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of half Euler angles. Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. """ c1, c2, c3 = tf.unstack(cos_half_angles, axis=-1) s1, s2, s3 = tf.unstack(sin_half_angles, axis=-1) w = c1 * c2 * c3 + s1 * s2 * s3 x = -c1 * s2 * s3 + s1 * c2 * c3 y = c1 * s2 * c3 + s1 * c2 * s3 z = -s1 * s2 * c3 + c1 * c2 * s3 return tf.stack((x, y, z, w), axis=-1) def between_two_vectors_3d(vector1, vector2, name="quaternion_between_two_vectors_3d"): """Computes quaternion over the shortest arc between two vectors. Result quaternion describes shortest geodesic rotation from vector1 to vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vector. vector2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vector. name: A name for this op that defaults to "quaternion_between_two_vectors_3d". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `vector1` or `vector2` is not supported. """ with tf.name_scope(name): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(-1, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-2, broadcast_compatible=True) # Make sure that we are dealing with unit vectors. vector1 = tf.nn.l2_normalize(vector1, axis=-1) vector2 = tf.nn.l2_normalize(vector2, axis=-1) cos_theta = vector.dot(vector1, vector2) real_part = 1.0 + cos_theta axis = vector.cross(vector1, vector2) # Compute arbitrary antiparallel axes to rotate around in case of opposite # vectors. x, y, z = tf.split(vector1, (1, 1, 1), axis=-1) x_bigger_z = tf.abs(x) > tf.abs(z) x_bigger_z = tf.concat([x_bigger_z] * 3, axis=-1) antiparallel_axis = tf.where(x_bigger_z, tf.concat((-y, x, tf.zeros_like(z)), axis=-1), tf.concat((tf.zeros_like(x), -z, y), axis=-1)) # Compute rotation between two vectors. is_antiparallel = real_part < 1e-6 is_antiparallel = tf.concat([is_antiparallel] * 4, axis=-1) rot = tf.where( is_antiparallel, tf.concat((antiparallel_axis, tf.zeros_like(real_part)), axis=-1), tf.concat((axis, real_part), axis=-1)) return tf.nn.l2_normalize(rot, axis=-1) def conjugate(quaternion, name="quaternion_conjugate"): """Computes the conjugate of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) xyz, w = tf.split(quaternion, (3, 1), axis=-1) return tf.concat((-xyz, w), axis=-1) def from_axis_angle(axis, angle, name="quaternion_from_axis_angle"): """Converts an axis-angle representation to a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "quaternion_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) half_angle = 0.5 * angle w = tf.cos(half_angle) xyz = tf.sin(half_angle) * axis return tf.concat((xyz, w), axis=-1) def from_euler(angles, name="quaternion_from_euler"): """Converts an Euler angle representation to a quaternion. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = tf.cos(half_angles) sin_half_angles = tf.sin(half_angles) return _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles) def from_euler_with_small_angles_approximation(angles, name="quaternion_from_euler"): r"""Converts small Euler angles to quaternions. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = 1.0 - 0.5 * half_angles * half_angles sin_half_angles = half_angles quaternion = _build_quaternion_from_sines_and_cosines( sin_half_angles, cos_half_angles) # We need to normalize the quaternion due to the small angle approximation. return tf.nn.l2_normalize(quaternion, axis=-1) def from_rotation_matrix(rotation_matrix, name="quaternion_from_rotation_matrix"): """Converts a rotation matrix representation to a quaternion. Warning: This function is not smooth everywhere. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "quaternion_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) trace = tf.linalg.trace(rotation_matrix) eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) rows = tf.unstack(rotation_matrix, axis=-2) entries = [tf.unstack(row, axis=-1) for row in rows] def tr_positive(): sq = tf.sqrt(trace + 1.0) * 2. # sq = 4 * qw. qw = 0.25 * sq qx = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qy = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qz = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_1(): sq = tf.sqrt(1.0 + entries[0][0] - entries[1][1] - entries[2][2] + eps_addition) * 2. # sq = 4 * qx. qw = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qx = 0.25 * sq qy = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qz = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_2(): sq = tf.sqrt(1.0 + entries[1][1] - entries[0][0] - entries[2][2] + eps_addition) * 2. # sq = 4 * qy. qw = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qx = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qy = 0.25 * sq qz = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_3(): sq = tf.sqrt(1.0 + entries[2][2] - entries[0][0] - entries[1][1] + eps_addition) * 2. # sq = 4 * qz. qw = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) qx = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) qy = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) qz = 0.25 * sq return tf.stack((qx, qy, qz, qw), axis=-1) def cond_idx(cond): cond = tf.expand_dims(cond, -1) cond = tf.tile(cond, [1] * (rotation_matrix.shape.ndims - 2) + [4]) return cond where_2 = tf.where( cond_idx(entries[1][1] > entries[2][2]), cond_2(), cond_3()) where_1 = tf.where( cond_idx((entries[0][0] > entries[1][1]) & (entries[0][0] > entries[2][2])), cond_1(), where_2) quat = tf.where(cond_idx(trace > 0), tr_positive(), where_1) return quat def inverse(quaternion, name="quaternion_inverse"): """Computes the inverse of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_inverse". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) squared_norm = tf.reduce_sum( input_tensor=tf.square(quaternion), axis=-1, keepdims=True) return safe_ops.safe_unsigned_div(conjugate(quaternion), squared_norm) def is_normalized(quaternion, atol=1e-3, name="quaternion_is_normalized"): """Determines if quaternion is normalized quaternion or not. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. atol: The absolute tolerance parameter. name: A name for this op that defaults to "quaternion_is_normalized". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]`, where False indicates that the quaternion is not normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) norms = tf.norm(tensor=quaternion, axis=-1, keepdims=True) return tf.where( tf.abs(norms - 1.) < atol, tf.ones_like(norms, dtype=bool), tf.zeros_like(norms, dtype=bool)) def normalize(quaternion, eps=1e-12, name="quaternion_normalize"): """Normalizes a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. eps: A lower bound value for the norm that defaults to 1e-12. name: A name for this op that defaults to "quaternion_normalize". Returns: A N-D tensor of shape `[?, ..., ?, 1]` where the quaternion elements have been normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) return tf.math.l2_normalize(quaternion, axis=-1, epsilon=eps) def multiply(quaternion1, quaternion2, name="quaternion_multiply"): """Multiplies two quaternions. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. name: A name for this op that defaults to "quaternion_multiply". Returns: A tensor of shape `[A1, ..., An, 4]` representing quaternions. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) x1, y1, z1, w1 = tf.unstack(quaternion1, axis=-1) x2, y2, z2, w2 = tf.unstack(quaternion2, axis=-1) x = x1 * w2 + y1 * z2 - z1 * y2 + w1 * x2 y = -x1 * z2 + y1 * w2 + z1 * x2 + w1 * y2 z = x1 * y2 - y1 * x2 + z1 * w2 + w1 * z2 w = -x1 * x2 - y1 * y2 - z1 * z2 + w1 * w2 return tf.stack((x, y, z, w), axis=-1) def normalized_random_uniform(quaternion_shape, name="quaternion_normalized_random_uniform"): """Random normalized quaternion following a uniform distribution law on SO(3). Args: quaternion_shape: A list representing the shape of the output tensor. name: A name for this op that defaults to "quaternion_normalized_random_uniform". Returns: A tensor of shape `[quaternion_shape[0],...,quaternion_shape[-1], 4]` representing random normalized quaternions. """ with tf.name_scope(name): quaternion_shape = tf.convert_to_tensor( value=quaternion_shape, dtype=tf.int32) quaternion_shape = tf.concat((quaternion_shape, tf.constant([4])), axis=0) random_normal = tf.random.normal(quaternion_shape) return normalize(random_normal) def normalized_random_uniform_initializer(): """Random unit quaternion initializer.""" # Since variable initializers must take `shape` as input, we cannot prevent # a clash between util.shape and the argument here. Therefore we have to # disable redefined-outer-name for this function. # pylint: disable=redefined-outer-name def _initializer(shape, dtype=tf.float32, partition_info=None): """Generate a random normalized quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: shape: A list representing the shape of the output. The last entry of the list must be `4`. dtype: type of the output (tf.float32 is the only type supported). partition_info: how the variable is partitioned (not used). Returns: A tensor of shape `[A1, ..., An, 4]` representing normalized quaternions. Raises: ValueError: If `shape` or `dtype` are not supported. """ del partition_info # unused if dtype != tf.float32: raise ValueError("'dtype' must be tf.float32.") if shape[-1] != 4: raise ValueError("Last dimension of 'shape' must be 4.") return normalized_random_uniform(shape[:-1]) return _initializer # pylint: enable=redefined-outer-name def rotate(point, quaternion, name="quaternion_rotate"): """Rotates a point using a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `quaternion` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(point, quaternion), last_axes=-2, broadcast_compatible=True) quaternion = asserts.assert_normalized(quaternion) padding = [[0, 0] for _ in range(point.shape.ndims)] padding[-1][-1] = 1 point = tf.pad(tensor=point, paddings=padding, mode="CONSTANT") point = multiply(quaternion, point) point = multiply(point, conjugate(quaternion)) xyz, _ = tf.split(point, (3, 1), axis=-1) return xyz def relative_angle(quaternion1, quaternion2, name="quaternion_relative_angle"): r"""Computes the unsigned relative rotation angle between 2 unit quaternions. Given two normalized quanternions $$\mathbf{q}_1$$ and $$\mathbf{q}_2$$, the relative angle is computed as $$\theta = 2\arccos(\mathbf{q}_1^T\mathbf{q}_2)$$. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_relative_angle". Returns: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents rotation angles in the range [0.0, pi]. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = vector.dot(quaternion1, quaternion2, keepdims=False) # Ensure dot product is in range [-1. 1]. eps_dot_prod = 4.0 * asserts.select_eps_for_addition(dot_product.dtype) dot_product = safe_ops.safe_shrink( dot_product, -1.0, 1.0, False, eps=eps_dot_prod) return 2.0 * tf.acos(tf.abs(dot_product)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow quaternion utility functions. A quaternion is written as $$q = xi + yj + zk + w$$, where $$i,j,k$$ forms the three bases of the imaginary part. The functions implemented in this file use the Hamilton convention where $$i^2 = j^2 = k^2 = ijk = -1$$. A quaternion is stored in a 4-D vector $$[x, y, z, w]^T$$. More details about Hamiltonian quaternions can be found on [this page.] (https://en.wikipedia.org/wiki/Quaternion) Note: Some of the functions expect normalized quaternions as inputs where $$x^2 + y^2 + z^2 + w^2 = 1$$. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_3d from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles): """Builds a quaternion from sines and cosines of half Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of half Euler angles. cos_half_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of half Euler angles. Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. """ c1, c2, c3 = tf.unstack(cos_half_angles, axis=-1) s1, s2, s3 = tf.unstack(sin_half_angles, axis=-1) w = c1 * c2 * c3 + s1 * s2 * s3 x = -c1 * s2 * s3 + s1 * c2 * c3 y = c1 * s2 * c3 + s1 * c2 * s3 z = -s1 * s2 * c3 + c1 * c2 * s3 return tf.stack((x, y, z, w), axis=-1) def between_two_vectors_3d(vector1, vector2, name="quaternion_between_two_vectors_3d"): """Computes quaternion over the shortest arc between two vectors. Result quaternion describes shortest geodesic rotation from vector1 to vector2. Note: In the following, A1 to An are optional batch dimensions. Args: vector1: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the first vector. vector2: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the second vector. name: A name for this op that defaults to "quaternion_between_two_vectors_3d". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `vector1` or `vector2` is not supported. """ with tf.name_scope(name): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(-1, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-2, broadcast_compatible=True) # Make sure that we are dealing with unit vectors. vector1 = tf.nn.l2_normalize(vector1, axis=-1) vector2 = tf.nn.l2_normalize(vector2, axis=-1) cos_theta = vector.dot(vector1, vector2) real_part = 1.0 + cos_theta axis = vector.cross(vector1, vector2) # Compute arbitrary antiparallel axes to rotate around in case of opposite # vectors. x, y, z = tf.split(vector1, (1, 1, 1), axis=-1) x_bigger_z = tf.abs(x) > tf.abs(z) x_bigger_z = tf.concat([x_bigger_z] * 3, axis=-1) antiparallel_axis = tf.where(x_bigger_z, tf.concat((-y, x, tf.zeros_like(z)), axis=-1), tf.concat((tf.zeros_like(x), -z, y), axis=-1)) # Compute rotation between two vectors. is_antiparallel = real_part < 1e-6 is_antiparallel = tf.concat([is_antiparallel] * 4, axis=-1) rot = tf.where( is_antiparallel, tf.concat((antiparallel_axis, tf.zeros_like(real_part)), axis=-1), tf.concat((axis, real_part), axis=-1)) return tf.nn.l2_normalize(rot, axis=-1) def conjugate(quaternion, name="quaternion_conjugate"): """Computes the conjugate of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_conjugate". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) xyz, w = tf.split(quaternion, (3, 1), axis=-1) return tf.concat((-xyz, w), axis=-1) def from_axis_angle(axis, angle, name="quaternion_from_axis_angle"): """Converts an axis-angle representation to a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents an angle. name: A name for this op that defaults to "quaternion_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) half_angle = 0.5 * angle w = tf.cos(half_angle) xyz = tf.sin(half_angle) * axis return tf.concat((xyz, w), axis=-1) def from_euler(angles, name="quaternion_from_euler"): """Converts an Euler angle representation to a quaternion. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = tf.cos(half_angles) sin_half_angles = tf.sin(half_angles) return _build_quaternion_from_sines_and_cosines(sin_half_angles, cos_half_angles) def from_euler_with_small_angles_approximation(angles, name="quaternion_from_euler"): r"""Converts small Euler angles to quaternions. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: Uses the z-y-x rotation convention (Tait-Bryan angles). Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[..., 0]` is the angle about `x` in radians, `[..., 1]` is the angle about `y` in radians and `[..., 2]` is the angle about `z` in radians. name: A name for this op that defaults to "quaternion_from_euler". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) half_angles = angles / 2.0 cos_half_angles = 1.0 - 0.5 * half_angles * half_angles sin_half_angles = half_angles quaternion = _build_quaternion_from_sines_and_cosines( sin_half_angles, cos_half_angles) # We need to normalize the quaternion due to the small angle approximation. return tf.nn.l2_normalize(quaternion, axis=-1) def from_rotation_matrix(rotation_matrix, name="quaternion_from_rotation_matrix"): """Converts a rotation matrix representation to a quaternion. Warning: This function is not smooth everywhere. Note: In the following, A1 to An are optional batch dimensions. Args: rotation_matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a rotation matrix. name: A name for this op that defaults to "quaternion_from_rotation_matrix". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `rotation_matrix` is not supported. """ with tf.name_scope(name): rotation_matrix = tf.convert_to_tensor(value=rotation_matrix) shape.check_static( tensor=rotation_matrix, tensor_name="rotation_matrix", has_rank_greater_than=1, has_dim_equals=((-1, 3), (-2, 3))) rotation_matrix = rotation_matrix_3d.assert_rotation_matrix_normalized( rotation_matrix) trace = tf.linalg.trace(rotation_matrix) eps_addition = asserts.select_eps_for_addition(rotation_matrix.dtype) rows = tf.unstack(rotation_matrix, axis=-2) entries = [tf.unstack(row, axis=-1) for row in rows] def tr_positive(): sq = tf.sqrt(trace + 1.0) * 2. # sq = 4 * qw. qw = 0.25 * sq qx = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qy = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qz = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_1(): sq = tf.sqrt(1.0 + entries[0][0] - entries[1][1] - entries[2][2] + eps_addition) * 2. # sq = 4 * qx. qw = safe_ops.safe_unsigned_div(entries[2][1] - entries[1][2], sq) qx = 0.25 * sq qy = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qz = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_2(): sq = tf.sqrt(1.0 + entries[1][1] - entries[0][0] - entries[2][2] + eps_addition) * 2. # sq = 4 * qy. qw = safe_ops.safe_unsigned_div(entries[0][2] - entries[2][0], sq) qx = safe_ops.safe_unsigned_div(entries[0][1] + entries[1][0], sq) qy = 0.25 * sq qz = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) return tf.stack((qx, qy, qz, qw), axis=-1) def cond_3(): sq = tf.sqrt(1.0 + entries[2][2] - entries[0][0] - entries[1][1] + eps_addition) * 2. # sq = 4 * qz. qw = safe_ops.safe_unsigned_div(entries[1][0] - entries[0][1], sq) qx = safe_ops.safe_unsigned_div(entries[0][2] + entries[2][0], sq) qy = safe_ops.safe_unsigned_div(entries[1][2] + entries[2][1], sq) qz = 0.25 * sq return tf.stack((qx, qy, qz, qw), axis=-1) def cond_idx(cond): cond = tf.expand_dims(cond, -1) cond = tf.tile(cond, [1] * (rotation_matrix.shape.ndims - 2) + [4]) return cond where_2 = tf.where( cond_idx(entries[1][1] > entries[2][2]), cond_2(), cond_3()) where_1 = tf.where( cond_idx((entries[0][0] > entries[1][1]) & (entries[0][0] > entries[2][2])), cond_1(), where_2) quat = tf.where(cond_idx(trace > 0), tr_positive(), where_1) return quat def inverse(quaternion, name="quaternion_inverse"): """Computes the inverse of a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_inverse". Returns: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) squared_norm = tf.reduce_sum( input_tensor=tf.square(quaternion), axis=-1, keepdims=True) return safe_ops.safe_unsigned_div(conjugate(quaternion), squared_norm) def is_normalized(quaternion, atol=1e-3, name="quaternion_is_normalized"): """Determines if quaternion is normalized quaternion or not. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. atol: The absolute tolerance parameter. name: A name for this op that defaults to "quaternion_is_normalized". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]`, where False indicates that the quaternion is not normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) norms = tf.norm(tensor=quaternion, axis=-1, keepdims=True) return tf.where( tf.abs(norms - 1.) < atol, tf.ones_like(norms, dtype=bool), tf.zeros_like(norms, dtype=bool)) def normalize(quaternion, eps=1e-12, name="quaternion_normalize"): """Normalizes a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. eps: A lower bound value for the norm that defaults to 1e-12. name: A name for this op that defaults to "quaternion_normalize". Returns: A N-D tensor of shape `[?, ..., ?, 1]` where the quaternion elements have been normalized. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) return tf.math.l2_normalize(quaternion, axis=-1, epsilon=eps) def multiply(quaternion1, quaternion2, name="quaternion_multiply"): """Multiplies two quaternions. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a quaternion. name: A name for this op that defaults to "quaternion_multiply". Returns: A tensor of shape `[A1, ..., An, 4]` representing quaternions. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) x1, y1, z1, w1 = tf.unstack(quaternion1, axis=-1) x2, y2, z2, w2 = tf.unstack(quaternion2, axis=-1) x = x1 * w2 + y1 * z2 - z1 * y2 + w1 * x2 y = -x1 * z2 + y1 * w2 + z1 * x2 + w1 * y2 z = x1 * y2 - y1 * x2 + z1 * w2 + w1 * z2 w = -x1 * x2 - y1 * y2 - z1 * z2 + w1 * w2 return tf.stack((x, y, z, w), axis=-1) def normalized_random_uniform(quaternion_shape, name="quaternion_normalized_random_uniform"): """Random normalized quaternion following a uniform distribution law on SO(3). Args: quaternion_shape: A list representing the shape of the output tensor. name: A name for this op that defaults to "quaternion_normalized_random_uniform". Returns: A tensor of shape `[quaternion_shape[0],...,quaternion_shape[-1], 4]` representing random normalized quaternions. """ with tf.name_scope(name): quaternion_shape = tf.convert_to_tensor( value=quaternion_shape, dtype=tf.int32) quaternion_shape = tf.concat((quaternion_shape, tf.constant([4])), axis=0) random_normal = tf.random.normal(quaternion_shape) return normalize(random_normal) def normalized_random_uniform_initializer(): """Random unit quaternion initializer.""" # Since variable initializers must take `shape` as input, we cannot prevent # a clash between util.shape and the argument here. Therefore we have to # disable redefined-outer-name for this function. # pylint: disable=redefined-outer-name def _initializer(shape, dtype=tf.float32, partition_info=None): """Generate a random normalized quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: shape: A list representing the shape of the output. The last entry of the list must be `4`. dtype: type of the output (tf.float32 is the only type supported). partition_info: how the variable is partitioned (not used). Returns: A tensor of shape `[A1, ..., An, 4]` representing normalized quaternions. Raises: ValueError: If `shape` or `dtype` are not supported. """ del partition_info # unused if dtype != tf.float32: raise ValueError("'dtype' must be tf.float32.") if shape[-1] != 4: raise ValueError("Last dimension of 'shape' must be 4.") return normalized_random_uniform(shape[:-1]) return _initializer # pylint: enable=redefined-outer-name def rotate(point, quaternion, name="quaternion_rotate"): """Rotates a point using a quaternion. Note: In the following, A1 to An are optional batch dimensions. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `quaternion` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) shape.compare_batch_dimensions( tensors=(point, quaternion), last_axes=-2, broadcast_compatible=True) quaternion = asserts.assert_normalized(quaternion) padding = [[0, 0] for _ in range(point.shape.ndims)] padding[-1][-1] = 1 point = tf.pad(tensor=point, paddings=padding, mode="CONSTANT") point = multiply(quaternion, point) point = multiply(point, conjugate(quaternion)) xyz, _ = tf.split(point, (3, 1), axis=-1) return xyz def relative_angle(quaternion1, quaternion2, name="quaternion_relative_angle"): r"""Computes the unsigned relative rotation angle between 2 unit quaternions. Given two normalized quanternions $$\mathbf{q}_1$$ and $$\mathbf{q}_2$$, the relative angle is computed as $$\theta = 2\arccos(\mathbf{q}_1^T\mathbf{q}_2)$$. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion1: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. quaternion2: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "quaternion_relative_angle". Returns: A tensor of shape `[A1, ..., An, 1]` where the last dimension represents rotation angles in the range [0.0, pi]. Raises: ValueError: If the shape of `quaternion1` or `quaternion2` is not supported. """ with tf.name_scope(name): quaternion1 = tf.convert_to_tensor(value=quaternion1) quaternion2 = tf.convert_to_tensor(value=quaternion2) shape.check_static( tensor=quaternion1, tensor_name="quaternion1", has_dim_equals=(-1, 4)) shape.check_static( tensor=quaternion2, tensor_name="quaternion2", has_dim_equals=(-1, 4)) quaternion1 = asserts.assert_normalized(quaternion1) quaternion2 = asserts.assert_normalized(quaternion2) dot_product = vector.dot(quaternion1, quaternion2, keepdims=False) # Ensure dot product is in range [-1. 1]. eps_dot_prod = 4.0 * asserts.select_eps_for_addition(dot_product.dtype) dot_product = safe_ops.safe_shrink( dot_product, -1.0, 1.0, False, eps=eps_dot_prod) return 2.0 * tf.acos(tf.abs(dot_product)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/voxels/tests/absorption_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for absoprtion voxel rendering.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.voxels import absorption from tensorflow_graphics.rendering.voxels.tests import test_helpers from tensorflow_graphics.util import test_case class AbsorptionTest(test_case.TestCase): @parameterized.parameters( (0, (8, 16, 6, 1)), (1, (12, 8, 16, 6, 3)), ) def test_render_shape_exception_not_raised(self, axis, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(absorption.render, shape, axis=axis) @parameterized.parameters( ("must have a rank greater than 3", 2, (3,)), ("must have a rank greater than 3", 2, (16, 6, 3)), ("'axis' needs to be 0, 1 or 2", 5, (8, 16, 6, 1)), ) def test_render_shape_exception_raised(self, error_msg, axis, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(absorption.render, error_msg, shape, axis=axis) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_render_jacobian_random(self): """Tests the Jacobian of render.""" voxels_init = test_helpers.generate_random_test_voxels_render() absorption_factor_init = np.float64(np.random.uniform(low=0.1, high=2.0)) cell_size_init = np.float64(np.random.uniform(low=0.1, high=2.0)) self.assert_jacobian_is_correct_fn( absorption.render, [voxels_init, absorption_factor_init, cell_size_init]) def test_render_preset(self): """Checks that render returns the expected value.""" x_voxels_init, y_images_init = test_helpers.generate_preset_test_voxels_absorption_render( ) voxels = tf.convert_to_tensor(value=x_voxels_init) y_images = tf.convert_to_tensor(value=y_images_init) y = absorption.render(voxels, absorption_factor=0.1, cell_size=0.2) self.assertAllClose(y_images, y) if __name__ == "__main__": test_case.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for absoprtion voxel rendering.""" from absl.testing import flagsaver from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.rendering.voxels import absorption from tensorflow_graphics.rendering.voxels.tests import test_helpers from tensorflow_graphics.util import test_case class AbsorptionTest(test_case.TestCase): @parameterized.parameters( (0, (8, 16, 6, 1)), (1, (12, 8, 16, 6, 3)), ) def test_render_shape_exception_not_raised(self, axis, *shape): """Tests that the shape exceptions are not raised.""" self.assert_exception_is_not_raised(absorption.render, shape, axis=axis) @parameterized.parameters( ("must have a rank greater than 3", 2, (3,)), ("must have a rank greater than 3", 2, (16, 6, 3)), ("'axis' needs to be 0, 1 or 2", 5, (8, 16, 6, 1)), ) def test_render_shape_exception_raised(self, error_msg, axis, *shape): """Tests that the shape exception is raised.""" self.assert_exception_is_raised(absorption.render, error_msg, shape, axis=axis) @flagsaver.flagsaver(tfg_add_asserts_to_graph=False) def test_render_jacobian_random(self): """Tests the Jacobian of render.""" voxels_init = test_helpers.generate_random_test_voxels_render() absorption_factor_init = np.float64(np.random.uniform(low=0.1, high=2.0)) cell_size_init = np.float64(np.random.uniform(low=0.1, high=2.0)) self.assert_jacobian_is_correct_fn( absorption.render, [voxels_init, absorption_factor_init, cell_size_init]) def test_render_preset(self): """Checks that render returns the expected value.""" x_voxels_init, y_images_init = test_helpers.generate_preset_test_voxels_absorption_render( ) voxels = tf.convert_to_tensor(value=x_voxels_init) y_images = tf.convert_to_tensor(value=y_images_init) y = absorption.render(voxels, absorption_factor=0.1, cell_size=0.2) self.assertAllClose(y_images, y) if __name__ == "__main__": test_case.main()
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/datasets/pix3d/fixed_masks/1745.png
PNG  IHDR,BIDATxn@EH3ᵮHxIo7]0#W=,ݜ<a1KQѱ[QP<M3Upt1OG gu 2|2l< y9D A$!" 2sxk3pf֧'9?iÎRC׆iĽK\}s|m/pSÔ9K9Gp25,2H"B X:n T@3!8W|_˩$B`! CNжk׊(=w\uUcCAC0ow$T02T5ˀ|)7PF}fV7t/O f$Y ߂NB WOg[>CI2(ecI頖W  }HB w?sj{!Ljjӛ7*~O7C8M\5D,@!IB$ !D,@o+IB$]G]VHk_\p 8 +TIENDB`
PNG  IHDR,BIDATxn@EH3ᵮHxIo7]0#W=,ݜ<a1KQѱ[QP<M3Upt1OG gu 2|2l< y9D A$!" 2sxk3pf֧'9?iÎRC׆iĽK\}s|m/pSÔ9K9Gp25,2H"B X:n T@3!8W|_˩$B`! CNжk׊(=w\uUcCAC0ow$T02T5ˀ|)7PF}fV7t/O f$Y ߂NB WOg[>CI2(ecI頖W  }HB w?sj{!Ljjӛ7*~O7C8M\5D,@!IB$ !D,@o+IB$]G]VHk_\p 8 +TIENDB`
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./tensorflow_graphics/rendering/framebuffer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Storage classes for framebuffers and related data.""" from typing import Dict, Optional import dataclasses import tensorflow as tf @dataclasses.dataclass class RasterizedAttribute(object): """A single rasterized attribute and optionally its screen-space derivatives. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. Immutable once created. """ value: tf.Tensor d_dx: Optional[tf.Tensor] = None d_dy: Optional[tf.Tensor] = None def __post_init__(self): # Checks that all input tensors have the same shape and rank. tensors = [self.value, self.d_dx, self.d_dy] shapes = [ tensor.shape.as_list() for tensor in tensors if tensor is not None ] ranks = [len(shape) for shape in shapes] if not all(rank == ranks[0] for rank in ranks): raise ValueError( "Expected value and derivatives to be of the same rank, but found" f" ranks {shapes}") same_as_value = True static_shapes = [self.value.shape] if self.d_dx is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dx))) static_shapes.append(self.d_dx.shape) if self.d_dy is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dy))) static_shapes.append(self.d_dy.shape) tf.debugging.assert_equal( same_as_value, True, message="Expected all input shapes to be the same but found: " + ", ".join([str(s) for s in static_shapes])) @dataclasses.dataclass class Framebuffer(object): """A framebuffer holding rasterized values required for deferred shading. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. For now, the fields are specialized for triangle rendering. Other primitives may be supported in the future. Immutable once created. Uses cached_property to avoid creating redundant tf ops when properties are accessed multiple times. """ # The barycentric weights of the pixel centers in the covering triangle. barycentrics: RasterizedAttribute # The index of the triangle covering this pixel. Not differentiable. triangle_id: tf.Tensor # The indices of the vertices of the triangle covering this pixel. # Not differentiable. vertex_ids: tf.Tensor # A mask of the pixels covered by a triangle. 1 if covered, 0 if background. # Not differentiable. foreground_mask: tf.Tensor # Other rasterized attribute values (e.g., colors, UVs, normals, etc.). attributes: Dict[str, RasterizedAttribute] = dataclasses.field( default_factory=dict) def __post_init__(self): # Checks that all buffers have rank and same shape up to the # number of channels. values = [self.barycentrics.value, self.triangle_id, self.vertex_ids, self.foreground_mask] values += [v.value for k, v in self.attributes.items()] ranks = [len(v.shape) for v in values] shapes = [tf.shape(v) for v in values] if not all(rank == ranks[0] for rank in ranks): raise ValueError( f"Expected all inputs to have the same rank, but found {shapes}") same_as_first = [ tf.reduce_all(tf.equal(shapes[0][:-1], s[:-1])) for s in shapes[1:] ] all_same_as_first = tf.reduce_all(same_as_first) tf.debugging.assert_equal( all_same_as_first, True, message="Expected all input shapes to be the same " "(up to channels), but found: " + ", ".join([str(s) for s in shapes]))
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Storage classes for framebuffers and related data.""" from typing import Dict, Optional import dataclasses import tensorflow as tf @dataclasses.dataclass class RasterizedAttribute(object): """A single rasterized attribute and optionally its screen-space derivatives. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. Immutable once created. """ value: tf.Tensor d_dx: Optional[tf.Tensor] = None d_dy: Optional[tf.Tensor] = None def __post_init__(self): # Checks that all input tensors have the same shape and rank. tensors = [self.value, self.d_dx, self.d_dy] shapes = [ tensor.shape.as_list() for tensor in tensors if tensor is not None ] ranks = [len(shape) for shape in shapes] if not all(rank == ranks[0] for rank in ranks): raise ValueError( "Expected value and derivatives to be of the same rank, but found" f" ranks {shapes}") same_as_value = True static_shapes = [self.value.shape] if self.d_dx is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dx))) static_shapes.append(self.d_dx.shape) if self.d_dy is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dy))) static_shapes.append(self.d_dy.shape) tf.debugging.assert_equal( same_as_value, True, message="Expected all input shapes to be the same but found: " + ", ".join([str(s) for s in static_shapes])) @dataclasses.dataclass class Framebuffer(object): """A framebuffer holding rasterized values required for deferred shading. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. For now, the fields are specialized for triangle rendering. Other primitives may be supported in the future. Immutable once created. Uses cached_property to avoid creating redundant tf ops when properties are accessed multiple times. """ # The barycentric weights of the pixel centers in the covering triangle. barycentrics: RasterizedAttribute # The index of the triangle covering this pixel. Not differentiable. triangle_id: tf.Tensor # The indices of the vertices of the triangle covering this pixel. # Not differentiable. vertex_ids: tf.Tensor # A mask of the pixels covered by a triangle. 1 if covered, 0 if background. # Not differentiable. foreground_mask: tf.Tensor # Other rasterized attribute values (e.g., colors, UVs, normals, etc.). attributes: Dict[str, RasterizedAttribute] = dataclasses.field( default_factory=dict) def __post_init__(self): # Checks that all buffers have rank and same shape up to the # number of channels. values = [self.barycentrics.value, self.triangle_id, self.vertex_ids, self.foreground_mask] values += [v.value for k, v in self.attributes.items()] ranks = [len(v.shape) for v in values] shapes = [tf.shape(v) for v in values] if not all(rank == ranks[0] for rank in ranks): raise ValueError( f"Expected all inputs to have the same rank, but found {shapes}") same_as_first = [ tf.reduce_all(tf.equal(shapes[0][:-1], s[:-1])) for s in shapes[1:] ] all_same_as_first = tf.reduce_all(same_as_first) tf.debugging.assert_equal( all_same_as_first, True, message="Expected all input shapes to be the same " "(up to channels), but found: " + ", ".join([str(s) for s in shapes]))
-1
tensorflow/graphics
491
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
copybara-service[bot]
"2021-02-07T23:04:27Z"
"2021-02-10T06:29:46Z"
f683a9a5794bade30ede447339394e84b44acc0b
2f75af81b3b8e559716c3044730287af8721606d
Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2.. Migrate tensorflow_graphics/geometry/{representation, deformation_energy} to using TensorFlow 2. - tf.compat.v1.tensor_scatter_add -> tf.tensor_scatter_nd_add - tf.compat.v1.batch_gather -> tf.gather (with batch_dims=-1) - tf.compat.v1.name_scope -> tf.name_scope
./CONTRIBUTING.md
# How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. Head over to <https://cla.developers.google.com/> to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## What features to add? The library is open to any contributions along the lines of computer graphics, with the top-level themes being rendering, physics simulation, and geometry processing. Contributions can be in the form of low level functions (majority of the library), Neural Networks layers or Colaboratory notebooks. ## Guidelines for Tensorflow operations TensorFlow Graphics follows the TensorFlow [contributor guidelines](https://www.tensorflow.org/community/contribute) and [code style guide](\(https://www.tensorflow.org/community/contribute/code_style\)). Besides these, TensorFlow Graphics has a few more guidelines which you can find below. ### Programming languages Unless this comes at a significant performance hit, pure Python is preferred. ### Structure of a function The general structure of a function should be as follows: * Name of the function followed by inputs to that function * Doc-string documentation * Definition of the scope using `tf.compat.v1.name_scope` * Functions that take tensors as arguments should call `tf.convert_to_tensor` * Checking the shape and value of the inputs as necessary * Main logic of the function ### Function names Prefer function names that are concise, descriptive, and integrate well with the module name when called. For instance, the `rotate` function from the `rotation_matrix_3d` sub-module can be called using `rotation_matrix_3d.rotate`, and makes it easy for anyone to understand what is being calculated. Functions that are only meant to be local to the file in which they are written should have an underscore before their name. ### Input parameters The first arguments should be tensors, followed by python parameters, and finally the name scope for the TensorFlow operation. ### Input shapes * The first dimensions of a tensor should represent the shape of the batch, and the last dimensions should represent the core shape of the elements used by the function. For instance, `rotation_matrix_3d.rotate` accepts rotation matrices of shape `[A1, ..., An, 3, 3]` where `[A1, ..., An]` are the optional batch dimensions, and `[3, 3]` is the shape required to capture 3D rotation matrices. * Every function must support batch dimensions of any shape, including tensors with no batch dimensions. * For input tensors with common batch shapes, document whether they can be broadcast compatible or not, and try to make them compatible when possible by, for instance, using `shape.get_broadcasted_shape` and `tf.broadcast_to`. ### Documentation Every function must have a docstring-type documentation describing what the function is performing, its arguments, and what is returned. The input sizes must be written between backquotes with batch dimensions indexed by letters and numbers, for instance: \`[A1, ..., An, 3]\`. Here `[A1, ..., An]` are the batch dimensions, and 3 is the intrinsic dimension required for the operation (e.g. a point in 3d). Prefer to put the batch dimension first. ### Error handling Handling unexpected inputs usually consists in checking that their shapes are consistent with expectations, which can be performed with `shape.check_static`, but also checking that the content of the tensors are valid (e.g. value in a specific range, no NaNs etc.), which can be performed with utilities provided in the `asserts` module. ### Differentiability and stable gradients There are several TF operations that can turn derivatives to zero at unintended points of your functions / operations. This can be avoided by using tools provided in the util.safe_ops module. If it can not be avoided, make sure to add tests checking the Jacobians of the function at the potentially discontinuous points of the function. See [Testing Jacobians](#testing-jacobians) below. Examples of such functions include: * tf.maximum / tf.minimum(a(x), b(x)): These create piecewise functions, which means derivatives can be discontinuous or zero for some ranges or points. * tf.clip_by_value / tf.clip_by_norm: These are also piecewise functions where the actual function is replaced with a constant piece for certain points or ranges, which makes the derivative zero, even if it actually isn’t. * tf.where(cond, a, b): This is another way of creating piecewise functions. This should be used only if it is really meant to create a piecewise function. The util.safe_ops submodule contains helper functions that can resolve issues with divisions by zero, but also helpers to ensure that the data is in the appropriate range. For instance a dot product of two normalized vectors can result in values outside of [-1.0, 1.0] range due to fixed point arithmetic. This in turn may result in NaN if used with arcsin or arccos. In such cases, safe_shrink in util.safe_ops should be used rather than clipping the range, since clipping removes derivatives which should be non-zero at these points. Cases involving zero divided by zero are a bit more involved and require dedicated workarounds. ### Software compatibility The library is intended to be compatible with the latest stable TensorFlow 1 release as well as the latest nightly package for TensorFlow 2. We also aim to be compatible with a couple of versions of Python. Testing for all the above is automatically performed using [travis](https://travis-ci.org/tensorflow/graphics). ### Hardware compatibility Except for performance reasons, every function must be hardware agnostic (e.g. CPU / GPU / TPU). ### Python modules Each module must contain a \_\_init__.py file which lists all the sub-modules it contains. ## Tests Testing code is essential to make the library usable by everyone at all times. In the following, we will briefly review our policies around unit testing and code coverage. ### Unit testing * all test classes must derive from tensorflow_graphics.util.test_case.TestCase * to improve readability of the code, and minimize duplication, the parameters passed to all the test functions described below are passed using `parameterized.parameters` provided by `absl.testing`. #### Test files Each module containing code has associated tests in the module's test sub-folder. Each test sub-folder must contain an empty \_\_init__.py, and one file per .py file in the module. For instance, if the `transformation` module contains `quaternion.py`, the tests associated with that python file should be located in `transformation/tests/quaterion_test.py`. In the following, we use FN as shorthand for the name of the function to be tested. Let's now have a look at how tests are structured and specific things to test for. #### Structure of a test TensorFlow Graphics follow the arrange-act-assert testing pattern. Moreover, if multiple tests are used in a single function to test for different but similar behavior, self.subTest should be used to create separate blocks. #### Testing return values The function names and behavior to use for testing return values are as follows: * `test_FN_random` to ensure that functions return the expected result for any valid input. * `test_FN_preset` to test specific inputs, and to make sure that corner cases are handled appropriately. #### Error handling Following are the function names and behavior to use for testing that errors are handled appropriately: * `test_FN_exception_raised` to test that functions return the expected error messages when input parameters are invalid (e.g. shape or values). * `test_FN_exception_not_raised` to make sure that valid arguments do not raise any errors. N.B.: For both test functions above, make sure to include `None` in some of the input shapes. #### Testing Jacobians Derivatives and gradients being at the core of Deep Learning training algorithms, testing for the stability and correctness of gradients is core to prevent problems, especially while training large networks. We perform numerical differentiation to ensure the correctness and stability of the Jacobians of any function by defining: * `test_FN_jacobian_random` to ensure that Jacobians are correct on the whole input domain. * `test_FN_jacobian_preset` to test the stability of Jacobian around corner cases, or points where the function might not be smooth / continuous. N.B.: for both test functions above, make sure to decorate them with `@flagsaver.flagsaver(tfg_add_asserts_to_graph=False)` to avoid potential errors arising due to finite differentiation (e.g. tensor not normalized anymore) ### Coverage The GitHub mirror of Tensorflow Graphics is using <a href="https://coveralls.io/">coveralls</a> to assess the test coverage. The version of Tensorflow Graphics that is internal to Google contains the same features compared to what is available on GitHub, but has access to more tools for testing. For this project, our internal policy is to only submit code for which our internal testing tools report at least 99% coverage. This number might seem to be a steep requirement, but given the nature of the project, this is obtained with reasonable efforts.
# How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. Head over to <https://cla.developers.google.com/> to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## What features to add? The library is open to any contributions along the lines of computer graphics, with the top-level themes being rendering, physics simulation, and geometry processing. Contributions can be in the form of low level functions (majority of the library), Neural Networks layers or Colaboratory notebooks. ## Guidelines for Tensorflow operations TensorFlow Graphics follows the TensorFlow [contributor guidelines](https://www.tensorflow.org/community/contribute) and [code style guide](\(https://www.tensorflow.org/community/contribute/code_style\)). Besides these, TensorFlow Graphics has a few more guidelines which you can find below. ### Programming languages Unless this comes at a significant performance hit, pure Python is preferred. ### Structure of a function The general structure of a function should be as follows: * Name of the function followed by inputs to that function * Doc-string documentation * Definition of the scope using `tf.compat.v1.name_scope` * Functions that take tensors as arguments should call `tf.convert_to_tensor` * Checking the shape and value of the inputs as necessary * Main logic of the function ### Function names Prefer function names that are concise, descriptive, and integrate well with the module name when called. For instance, the `rotate` function from the `rotation_matrix_3d` sub-module can be called using `rotation_matrix_3d.rotate`, and makes it easy for anyone to understand what is being calculated. Functions that are only meant to be local to the file in which they are written should have an underscore before their name. ### Input parameters The first arguments should be tensors, followed by python parameters, and finally the name scope for the TensorFlow operation. ### Input shapes * The first dimensions of a tensor should represent the shape of the batch, and the last dimensions should represent the core shape of the elements used by the function. For instance, `rotation_matrix_3d.rotate` accepts rotation matrices of shape `[A1, ..., An, 3, 3]` where `[A1, ..., An]` are the optional batch dimensions, and `[3, 3]` is the shape required to capture 3D rotation matrices. * Every function must support batch dimensions of any shape, including tensors with no batch dimensions. * For input tensors with common batch shapes, document whether they can be broadcast compatible or not, and try to make them compatible when possible by, for instance, using `shape.get_broadcasted_shape` and `tf.broadcast_to`. ### Documentation Every function must have a docstring-type documentation describing what the function is performing, its arguments, and what is returned. The input sizes must be written between backquotes with batch dimensions indexed by letters and numbers, for instance: \`[A1, ..., An, 3]\`. Here `[A1, ..., An]` are the batch dimensions, and 3 is the intrinsic dimension required for the operation (e.g. a point in 3d). Prefer to put the batch dimension first. ### Error handling Handling unexpected inputs usually consists in checking that their shapes are consistent with expectations, which can be performed with `shape.check_static`, but also checking that the content of the tensors are valid (e.g. value in a specific range, no NaNs etc.), which can be performed with utilities provided in the `asserts` module. ### Differentiability and stable gradients There are several TF operations that can turn derivatives to zero at unintended points of your functions / operations. This can be avoided by using tools provided in the util.safe_ops module. If it can not be avoided, make sure to add tests checking the Jacobians of the function at the potentially discontinuous points of the function. See [Testing Jacobians](#testing-jacobians) below. Examples of such functions include: * tf.maximum / tf.minimum(a(x), b(x)): These create piecewise functions, which means derivatives can be discontinuous or zero for some ranges or points. * tf.clip_by_value / tf.clip_by_norm: These are also piecewise functions where the actual function is replaced with a constant piece for certain points or ranges, which makes the derivative zero, even if it actually isn’t. * tf.where(cond, a, b): This is another way of creating piecewise functions. This should be used only if it is really meant to create a piecewise function. The util.safe_ops submodule contains helper functions that can resolve issues with divisions by zero, but also helpers to ensure that the data is in the appropriate range. For instance a dot product of two normalized vectors can result in values outside of [-1.0, 1.0] range due to fixed point arithmetic. This in turn may result in NaN if used with arcsin or arccos. In such cases, safe_shrink in util.safe_ops should be used rather than clipping the range, since clipping removes derivatives which should be non-zero at these points. Cases involving zero divided by zero are a bit more involved and require dedicated workarounds. ### Software compatibility The library is intended to be compatible with the latest stable TensorFlow 1 release as well as the latest nightly package for TensorFlow 2. We also aim to be compatible with a couple of versions of Python. Testing for all the above is automatically performed using [travis](https://travis-ci.org/tensorflow/graphics). ### Hardware compatibility Except for performance reasons, every function must be hardware agnostic (e.g. CPU / GPU / TPU). ### Python modules Each module must contain a \_\_init__.py file which lists all the sub-modules it contains. ## Tests Testing code is essential to make the library usable by everyone at all times. In the following, we will briefly review our policies around unit testing and code coverage. ### Unit testing * all test classes must derive from tensorflow_graphics.util.test_case.TestCase * to improve readability of the code, and minimize duplication, the parameters passed to all the test functions described below are passed using `parameterized.parameters` provided by `absl.testing`. #### Test files Each module containing code has associated tests in the module's test sub-folder. Each test sub-folder must contain an empty \_\_init__.py, and one file per .py file in the module. For instance, if the `transformation` module contains `quaternion.py`, the tests associated with that python file should be located in `transformation/tests/quaterion_test.py`. In the following, we use FN as shorthand for the name of the function to be tested. Let's now have a look at how tests are structured and specific things to test for. #### Structure of a test TensorFlow Graphics follow the arrange-act-assert testing pattern. Moreover, if multiple tests are used in a single function to test for different but similar behavior, self.subTest should be used to create separate blocks. #### Testing return values The function names and behavior to use for testing return values are as follows: * `test_FN_random` to ensure that functions return the expected result for any valid input. * `test_FN_preset` to test specific inputs, and to make sure that corner cases are handled appropriately. #### Error handling Following are the function names and behavior to use for testing that errors are handled appropriately: * `test_FN_exception_raised` to test that functions return the expected error messages when input parameters are invalid (e.g. shape or values). * `test_FN_exception_not_raised` to make sure that valid arguments do not raise any errors. N.B.: For both test functions above, make sure to include `None` in some of the input shapes. #### Testing Jacobians Derivatives and gradients being at the core of Deep Learning training algorithms, testing for the stability and correctness of gradients is core to prevent problems, especially while training large networks. We perform numerical differentiation to ensure the correctness and stability of the Jacobians of any function by defining: * `test_FN_jacobian_random` to ensure that Jacobians are correct on the whole input domain. * `test_FN_jacobian_preset` to test the stability of Jacobian around corner cases, or points where the function might not be smooth / continuous. N.B.: for both test functions above, make sure to decorate them with `@flagsaver.flagsaver(tfg_add_asserts_to_graph=False)` to avoid potential errors arising due to finite differentiation (e.g. tensor not normalized anymore) ### Coverage The GitHub mirror of Tensorflow Graphics is using <a href="https://coveralls.io/">coveralls</a> to assess the test coverage. The version of Tensorflow Graphics that is internal to Google contains the same features compared to what is available on GitHub, but has access to more tools for testing. For this project, our internal policy is to only submit code for which our internal testing tools report at least 99% coverage. This number might seem to be a steep requirement, but given the nature of the project, this is obtained with reasonable efforts.
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/framebuffer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Storage classes for framebuffers and related data.""" from typing import Dict, Optional import dataclasses import tensorflow as tf @dataclasses.dataclass class RasterizedAttribute(object): """A single rasterized attribute and optionally its screen-space derivatives. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. Immutable once created. """ value: tf.Tensor d_dx: Optional[tf.Tensor] = None d_dy: Optional[tf.Tensor] = None def __post_init__(self): # Checks that all input tensors have the same shape and rank. tensors = [self.value, self.d_dx, self.d_dy] shapes = [ tensor.shape.as_list() for tensor in tensors if tensor is not None ] ranks = [len(shape) for shape in shapes] if not all(rank == ranks[0] for rank in ranks): raise ValueError( "Expected value and derivatives to be of the same rank, but found" f" ranks {shapes}") same_as_value = True static_shapes = [self.value.shape] if self.d_dx is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dx))) static_shapes.append(self.d_dx.shape) if self.d_dy is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dy))) static_shapes.append(self.d_dy.shape) tf.debugging.assert_equal( same_as_value, True, message="Expected all input shapes to be the same but found: " + ", ".join([str(s) for s in static_shapes])) @dataclasses.dataclass class Framebuffer(object): """A framebuffer holding rasterized values required for deferred shading. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. For now, the fields are specialized for triangle rendering. Other primitives may be supported in the future. Immutable once created. Uses cached_property to avoid creating redundant tf ops when properties are accessed multiple times. """ # The barycentric weights of the pixel centers in the covering triangle. barycentrics: RasterizedAttribute # The index of the triangle covering this pixel. Not differentiable. triangle_id: tf.Tensor # The indices of the vertices of the triangle covering this pixel. # Not differentiable. vertex_ids: tf.Tensor # A mask of the pixels covered by a triangle. 1 if covered, 0 if background. # Not differentiable. foreground_mask: tf.Tensor # Other rasterized attribute values (e.g., colors, UVs, normals, etc.). attributes: Dict[str, RasterizedAttribute] = dataclasses.field( default_factory=dict) def __post_init__(self): # Checks that all buffers have rank and same shape up to the # number of channels. values = [self.barycentrics.value, self.triangle_id, self.vertex_ids, self.foreground_mask] values += [v.value for k, v in self.attributes.items()] ranks = [len(v.shape) for v in values] shapes = [tf.shape(v) for v in values] if not all(rank == ranks[0] for rank in ranks): raise ValueError( f"Expected all inputs to have the same rank, but found {shapes}") same_as_first = [ tf.reduce_all(tf.equal(shapes[0][:-1], s[:-1])) for s in shapes[1:] ] all_same_as_first = tf.reduce_all(same_as_first) tf.debugging.assert_equal( all_same_as_first, True, message="Expected all input shapes to be the same " "(up to channels), but found: " + ", ".join([str(s) for s in shapes]))
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Storage classes for framebuffers and related data.""" from typing import Dict, Optional import dataclasses import tensorflow as tf @dataclasses.dataclass class RasterizedAttribute(object): """A single rasterized attribute and optionally its screen-space derivatives. Tensors are expected to have shape [batch, height, width, channels] or [batch, num_layers, height, width, channels]. Immutable once created. """ value: tf.Tensor d_dx: Optional[tf.Tensor] = None d_dy: Optional[tf.Tensor] = None def __post_init__(self): # Checks that all input tensors have the same shape and rank. tensors = [self.value, self.d_dx, self.d_dy] shapes = [ tensor.shape.as_list() for tensor in tensors if tensor is not None ] ranks = [len(shape) for shape in shapes] if not all(rank == ranks[0] for rank in ranks): raise ValueError( "Expected value and derivatives to be of the same rank, but found" f" ranks {shapes}") value_rank = len(self.value.shape) if value_rank != 4: raise ValueError( f"Expected input value to be rank 4, but is {value_rank}") same_as_value = True static_shapes = [self.value.shape] if self.d_dx is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dx))) static_shapes.append(self.d_dx.shape) if self.d_dy is not None: same_as_value = tf.logical_and( same_as_value, tf.equal(tf.shape(self.value), tf.shape(self.d_dy))) static_shapes.append(self.d_dy.shape) tf.debugging.assert_equal( same_as_value, True, message="Expected all input shapes to be the same but found: " + ", ".join([str(s) for s in static_shapes])) @dataclasses.dataclass class Framebuffer(object): """A framebuffer holding rasterized values required for deferred shading. Tensors are expected to have shape [batch, height, width, channels]. For now, the fields are specialized for triangle rendering. Other primitives may be supported in the future. Immutable once created. Uses cached_property to avoid creating redundant tf ops when properties are accessed multiple times. """ # The barycentric weights of the pixel centers in the covering triangle. barycentrics: RasterizedAttribute # The index of the triangle covering this pixel. Not differentiable. triangle_id: tf.Tensor # The indices of the vertices of the triangle covering this pixel. # Not differentiable. vertex_ids: tf.Tensor # A mask of the pixels covered by a triangle. 1 if covered, 0 if background. # Not differentiable. foreground_mask: tf.Tensor # Other rasterized attribute values (e.g., colors, UVs, normals, etc.). attributes: Dict[str, RasterizedAttribute] = dataclasses.field( default_factory=dict) def __post_init__(self): # Checks that all buffers have rank and same shape up to the # number of channels. values = [self.barycentrics.value, self.triangle_id, self.vertex_ids, self.foreground_mask] values += [v.value for k, v in self.attributes.items()] ranks = [len(v.shape) for v in values] shapes = [tf.shape(v) for v in values] if not all(rank == ranks[0] for rank in ranks): raise ValueError( f"Expected all inputs to have the same rank, but found {shapes}") same_as_first = [ tf.reduce_all(tf.equal(shapes[0][:-1], s[:-1])) for s in shapes[1:] ] all_same_as_first = tf.reduce_all(same_as_first) tf.debugging.assert_equal( all_same_as_first, True, message="Expected all input shapes to be the same " "(up to channels), but found: " + ", ".join([str(s) for s in shapes]))
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/opengl/rasterization_backend.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenGL rasterization backend for TF Graphics.""" import tensorflow as tf from tensorflow_graphics.rendering import framebuffer as fb from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape # pylint: disable=g-import-not-at-top try: from tensorflow_graphics.rendering.opengl import gen_rasterizer_op as render_ops except ImportError: import os dir_path = os.path.dirname(os.path.abspath(__file__)) render_ops = tf.load_op_library(os.path.join(dir_path, "rasterizer_op.so")) # pylint: enable=g-import-not-at-top def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) # Empty vertex shader; all the work happens in the geometry shader. vertex_shader = """ #version 430 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. geometry_shader = """ #version 430 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec2 barycentric_coordinates; out layout(location = 1) float triangle_index; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int vertex_index) { // Triangles are packed as 3 consecuitve vertices, each with 3 coordinates. int offset = gl_PrimitiveIDIn * 9 + vertex_index * 3; return vec3(mesh_buffer[offset], mesh_buffer[offset + 1], mesh_buffer[offset + 2]); } void main() { vec3 positions[3] = {get_vertex_position(0), get_vertex_position(1), get_vertex_position(2)}; vec4 projected_vertices[3] = { view_projection_matrix * vec4(positions[0], 1.0), view_projection_matrix * vec4(positions[1], 1.0), view_projection_matrix * vec4(positions[2], 1.0)}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable. gl_Position = projected_vertices[i]; barycentric_coordinates = vec2(i==0 ? 1.0 : 0.0, i==1 ? 1.0 : 0.0); triangle_index = gl_PrimitiveIDIn; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, and triangle index. fragment_shader = """ #version 430 in layout(location = 0) vec2 barycentric_coordinates; in layout(location = 1) float triangle_index; out vec4 output_color; void main() { output_color = vec4(round(triangle_index), barycentric_coordinates, 1.0); } """ def rasterize(vertices, triangles, view_projection_matrices, image_size, name=None): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. name: A name for this op. Defaults to 'rasterization_backend_rasterize'. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ with tf.compat.v1.name_scope(name, "rasterization_backend_rasterize", (vertices, triangles, view_projection_matrices)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) view_projection_matrices = tf.convert_to_tensor( value=view_projection_matrices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=view_projection_matrices, tensor_name="view_projection_matrices", has_rank_greater_than=1, has_dim_equals=((-1, 4), (-2, 4))) shape.compare_batch_dimensions( tensors=(vertices, view_projection_matrices), tensor_names=("vertices", "view_projection_matrices"), last_axes=(-3, -3), broadcast_compatible=True) common_batch_shape = shape.get_broadcasted_shape( vertices.shape[:-2], view_projection_matrices.shape[:-2]) common_batch_shape = [_dim_value(dim) for dim in common_batch_shape] vertices = tf.broadcast_to(vertices, common_batch_shape + vertices.shape[-2:]) view_projection_matrices = tf.broadcast_to(view_projection_matrices, common_batch_shape + [4, 4]) geometry = tf.gather(vertices, triangles, axis=-2) rasterized = render_ops.rasterize( num_points=geometry.shape[-3], alpha_clear=0.0, enable_cull_face=True, variable_names=("view_projection_matrix", "triangular_mesh"), variable_kinds=("mat", "buffer"), variable_values=(view_projection_matrices, tf.reshape(geometry, shape=common_batch_shape + [-1])), output_resolution=image_size, vertex_shader=vertex_shader, geometry_shader=geometry_shader, fragment_shader=fragment_shader) triangle_index = tf.cast(rasterized[..., 0], tf.int32) # Slicing of the tensor will result in all batch dimensions being # `None` for tensorflow graph mode, therefore we have to fix it in order to # have explicit shape. width, height = image_size triangle_index = tf.reshape(triangle_index, common_batch_shape + [height, width, 1]) barycentric_coordinates = rasterized[..., 1:3] barycentric_coordinates = tf.concat( (barycentric_coordinates, 1.0 - barycentric_coordinates[..., 0:1] - barycentric_coordinates[..., 1:2]), axis=-1) mask = tf.cast(rasterized[..., 3], tf.int32) mask = tf.reshape(mask, common_batch_shape + [height, width, 1]) triangles_batch = tf.broadcast_to(triangles, common_batch_shape + triangles.shape) vertex_ids = tf.gather( triangles_batch, triangle_index[..., 0], batch_dims=len(common_batch_shape)) return fb.Framebuffer( foreground_mask=mask, triangle_id=triangle_index, vertex_ids=vertex_ids, barycentrics=fb.RasterizedAttribute( value=barycentric_coordinates, d_dx=None, d_dy=None)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenGL rasterization backend for TF Graphics.""" import tensorflow as tf from tensorflow_graphics.rendering import framebuffer as fb from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape # pylint: disable=g-import-not-at-top try: from tensorflow_graphics.rendering.opengl import gen_rasterizer_op as render_ops except ImportError: import os dir_path = os.path.dirname(os.path.abspath(__file__)) render_ops = tf.load_op_library(os.path.join(dir_path, "rasterizer_op.so")) # pylint: enable=g-import-not-at-top def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) # Empty vertex shader; all the work happens in the geometry shader. vertex_shader = """ #version 430 void main() { } """ # Geometry shader that projects the vertices of visible triangles onto the image # plane. geometry_shader = """ #version 430 uniform mat4 view_projection_matrix; layout(points) in; layout(triangle_strip, max_vertices=3) out; out layout(location = 0) vec2 barycentric_coordinates; out layout(location = 1) float triangle_index; layout(binding=0) buffer triangular_mesh { float mesh_buffer[]; }; vec3 get_vertex_position(int vertex_index) { // Triangles are packed as 3 consecuitve vertices, each with 3 coordinates. int offset = gl_PrimitiveIDIn * 9 + vertex_index * 3; return vec3(mesh_buffer[offset], mesh_buffer[offset + 1], mesh_buffer[offset + 2]); } void main() { vec3 positions[3] = {get_vertex_position(0), get_vertex_position(1), get_vertex_position(2)}; vec4 projected_vertices[3] = { view_projection_matrix * vec4(positions[0], 1.0), view_projection_matrix * vec4(positions[1], 1.0), view_projection_matrix * vec4(positions[2], 1.0)}; for (int i = 0; i < 3; ++i) { // gl_Position is a pre-defined size 4 output variable. gl_Position = projected_vertices[i]; barycentric_coordinates = vec2(i==0 ? 1.0 : 0.0, i==1 ? 1.0 : 0.0); triangle_index = gl_PrimitiveIDIn; EmitVertex(); } EndPrimitive(); } """ # Fragment shader that packs barycentric coordinates, and triangle index. fragment_shader = """ #version 430 in layout(location = 0) vec2 barycentric_coordinates; in layout(location = 1) float triangle_index; out vec4 output_color; void main() { output_color = vec4(round(triangle_index), barycentric_coordinates, 1.0); } """ def rasterize(vertices, triangles, view_projection_matrices, image_size, name=None): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[batch, num_vertices, 3]` containing batches vertices, each defined by a 3D point. triangles: A tensor of shape `[num_triangles, 3]` each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[batch, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. name: A name for this op. Defaults to 'rasterization_backend_rasterize'. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ with tf.compat.v1.name_scope(name, "rasterization_backend_rasterize", (vertices, triangles, view_projection_matrices)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) view_projection_matrices = tf.convert_to_tensor( value=view_projection_matrices) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank=3, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=view_projection_matrices, tensor_name="view_projection_matrices", has_rank=3, has_dim_equals=((-1, 4), (-2, 4))) shape.compare_batch_dimensions( tensors=(vertices, view_projection_matrices), tensor_names=("vertices", "view_projection_matrices"), last_axes=(-3, -3), broadcast_compatible=True) geometry = tf.gather(vertices, triangles, axis=-2) # Extract batch size in order to make sure it is preserved after `gather` # operation. batch_size = _dim_value(vertices.shape[0]) rasterized = render_ops.rasterize( num_points=geometry.shape[-3], alpha_clear=0.0, enable_cull_face=True, variable_names=("view_projection_matrix", "triangular_mesh"), variable_kinds=("mat", "buffer"), variable_values=(view_projection_matrices, tf.reshape(geometry, shape=[batch_size, -1])), output_resolution=image_size, vertex_shader=vertex_shader, geometry_shader=geometry_shader, fragment_shader=fragment_shader) triangle_index = tf.cast(rasterized[..., 0], tf.int32) # Slicing of the tensor will result in all batch dimensions being # `None` for tensorflow graph mode, therefore we have to fix it in order to # have explicit shape. width, height = image_size triangle_index = tf.reshape(triangle_index, [batch_size, height, width, 1]) barycentric_coordinates = rasterized[..., 1:3] barycentric_coordinates = tf.concat( (barycentric_coordinates, 1.0 - barycentric_coordinates[..., 0:1] - barycentric_coordinates[..., 1:2]), axis=-1) mask = tf.cast(rasterized[..., 3], tf.int32) mask = tf.reshape(mask, [batch_size, height, width, 1]) vertex_ids = tf.gather(triangles, triangle_index[..., 0], batch_dims=0) return fb.Framebuffer( foreground_mask=mask, triangle_id=triangle_index, vertex_ids=vertex_ids, barycentrics=fb.RasterizedAttribute( value=barycentric_coordinates, d_dx=None, d_dy=None)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/opengl/rasterizer_op.cc
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include "absl/types/span.h" #include "macros.h" #include "rasterizer_with_context.h" #include "thread_safe_resource_pool.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" static tensorflow::Status GetVariablesRank( ::tensorflow::shape_inference::InferenceContext* c, tensorflow::int32* rank) { std::vector<std::string> variable_names, variable_kinds; TF_RETURN_IF_ERROR(c->GetAttr("variable_names", &variable_names)); TF_RETURN_IF_ERROR(c->GetAttr("variable_kinds", &variable_kinds)); std::vector<tensorflow::shape_inference::ShapeHandle> variable_values; TF_RETURN_IF_ERROR(c->input("variable_values", &variable_values)); if (variable_names.size() != variable_values.size() || variable_names.size() != variable_kinds.size()) { return tensorflow::errors::InvalidArgument( "The variable names, kinds, and values must have the same size."); } for (int index = 0; index < variable_kinds.size(); index++) { absl::string_view kind = variable_kinds[index]; const tensorflow::shape_inference::ShapeHandle& h = variable_values[index]; auto batch_rank = c->Rank(h); if (kind == "mat") { if (batch_rank < 2) return tensorflow::errors::InvalidArgument( "Matrix with name='", variable_names[index], "' has an invalid rank of ", batch_rank); batch_rank -= 2; } else if (kind == "buffer") { if (batch_rank < 1) return tensorflow::errors::InvalidArgument( "Buffer with name='", variable_names[index], "' has an invalid rank of ", batch_rank); batch_rank -= 1; } if (index == 0) *rank = batch_rank; else if (*rank != batch_rank) return tensorflow::errors::InvalidArgument( "Variable with name='", variable_names[index], "' has an invalid batch rank of ", batch_rank, "; expected ", *rank); } return tensorflow::Status::OK(); } REGISTER_OP("Rasterize") .Attr("output_resolution: shape") .Attr("red_clear: float = 0.0") .Attr("green_clear: float = 0.0") .Attr("blue_clear: float = 0.0") .Attr("alpha_clear: float = 1.0") .Attr("depth_clear: float = 1.0") .Attr("enable_cull_face: bool = false") .Attr("vertex_shader: string") .Attr("fragment_shader: string") .Attr("geometry_shader: string") .Attr("variable_names: list(string)") .Attr("variable_kinds: list({'mat', 'buffer'})") .Attr("T: list({float})") .Input("num_points: int32") .Input("variable_values: T") .Output("rendered_image: float") .Doc(R"doc( Rasterization OP that runs the program specified by the supplied vertex, geometry and fragment shaders. Uniform variables and buffers can be passed to the program using variable_names, variable_kinds, and variable_values. Note that in the following, A1 to An are optional batch dimensions. output_resolution: a 2D shape containing the width and height of the resulting image. red_clear: the red component for glClear. green_clear: the green component for glClear. blue_clear: the blue component for glClear. alpha_clear: the alpha component for glClear. depth_clear: the depth value for glClearDepthf. enable_cull_face: enable face culling. vertex_shader: A string containing a valid vertex shader. fragment_shader: A string containing a valid fragment shader. geometry_shader: A string containing a valid geometry shader. variable_names: A list of strings describing the name of each variable passed to the shaders. These names must map to the name of uniforms or buffers in the supplied shaders. variable_kinds: A list of strings containing the type of each variable. Possible values for each element are `mat` and `buffer`. num_points: The number of points to be rendered. When rasterizing a mesh, this number should be set to the number of vertices in the mesh. variable_values: A list containing matrices of shape `[A1, ..., An, W, H]` and/or buffers of shape `[A1, ..., An, S]`, with `W` and `H` in `[1,4]` and S of arbitrary value. Using their associated name and kind, these values are mapped to the corresponding uniform or buffer in the program. Note that all variables must have the same batch dimensions `[A1, ..., An]`, and that matrices are expected to be in row-major format. rendered_image: A tensor of shape `[A1, ..., An, width, height, 4]`, with the width and height defined by `output_resolution`. )doc") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { tensorflow::int32 variables_rank; TF_RETURN_IF_ERROR(GetVariablesRank(c, &variables_rank)); auto batch_shape = c->UnknownShapeOfRank(variables_rank); tensorflow::TensorShape resolution; TF_RETURN_IF_ERROR(c->GetAttr("output_resolution", &resolution)); auto image_shape = c->MakeShape({resolution.dim_size(1), resolution.dim_size(0), 4}); tensorflow::shape_inference::ShapeHandle output_shape; TF_RETURN_IF_ERROR( c->Concatenate(batch_shape, image_shape, &output_shape)); c->set_output(0, output_shape); return tensorflow::Status::OK(); }); class RasterizeOp : public tensorflow::OpKernel { public: explicit RasterizeOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) { std::string fragment_shader; std::string geometry_shader; std::string vertex_shader; float red_clear = 0.0; float green_clear = 0.0; float blue_clear = 0.0; float alpha_clear = 1.0; float depth_clear = 1.0; bool enable_cull_face = false; OP_REQUIRES_OK(context, context->GetAttr("red_clear", &red_clear)); OP_REQUIRES_OK(context, context->GetAttr("green_clear", &green_clear)); OP_REQUIRES_OK(context, context->GetAttr("blue_clear", &blue_clear)); OP_REQUIRES_OK(context, context->GetAttr("alpha_clear", &alpha_clear)); OP_REQUIRES_OK(context, context->GetAttr("depth_clear", &depth_clear)); OP_REQUIRES_OK(context, context->GetAttr("enable_cull_face", &enable_cull_face)); OP_REQUIRES_OK(context, context->GetAttr("vertex_shader", &vertex_shader)); OP_REQUIRES_OK(context, context->GetAttr("fragment_shader", &fragment_shader)); OP_REQUIRES_OK(context, context->GetAttr("geometry_shader", &geometry_shader)); OP_REQUIRES_OK(context, context->GetAttr("variable_names", &variable_names_)); OP_REQUIRES_OK(context, context->GetAttr("variable_kinds", &variable_kinds_)); OP_REQUIRES_OK(context, context->GetAttr("output_resolution", &output_resolution_)); auto rasterizer_creator = [vertex_shader, geometry_shader, fragment_shader, red_clear, green_clear, blue_clear, alpha_clear, depth_clear, enable_cull_face, this](std::unique_ptr<RasterizerWithContext>* resource) -> tensorflow::Status { return RasterizerWithContext::Create( output_resolution_.dim_size(0), output_resolution_.dim_size(1), vertex_shader, geometry_shader, fragment_shader, resource, red_clear, green_clear, blue_clear, alpha_clear, depth_clear, enable_cull_face); }; rasterizer_pool_ = std::unique_ptr<ThreadSafeResourcePool<RasterizerWithContext>>( new ThreadSafeResourcePool<RasterizerWithContext>( rasterizer_creator)); } void Compute(tensorflow::OpKernelContext* context) override { tensorflow::TensorShape batch_shape; OP_REQUIRES_OK(context, ValidateVariables(context, &batch_shape)); // Allocate the output images. tensorflow::Tensor* output_image; tensorflow::TensorShape output_image_shape; output_image_shape.AppendShape(batch_shape); output_image_shape.AddDim(output_resolution_.dim_size(1)); output_image_shape.AddDim(output_resolution_.dim_size(0)); output_image_shape.AddDim(4); OP_REQUIRES_OK(context, context->allocate_output(0, output_image_shape, &output_image)); std::unique_ptr<RasterizerWithContext> rasterizer; float* image_data = output_image->flat<float>().data(); const tensorflow::int64 image_size = output_resolution_.dim_size(0) * output_resolution_.dim_size(1) * 4; OP_REQUIRES_OK(context, rasterizer_pool_->AcquireResource(&rasterizer)); for (int i = 0; i < batch_shape.num_elements(); ++i) { OP_REQUIRES_OK(context, SetVariables(context, rasterizer, i)); OP_REQUIRES_OK(context, RenderImage(context, rasterizer, image_size, image_data + i * image_size)); } OP_REQUIRES_OK(context, rasterizer_pool_->ReturnResource(rasterizer)); } private: tensorflow::Status SetVariables( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, int outer_dim); tensorflow::Status RenderImage( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, tensorflow::int64 image_size, float* image_data); tensorflow::Status ValidateVariables(tensorflow::OpKernelContext* context, tensorflow::TensorShape* batch_shape); std::unique_ptr<ThreadSafeResourcePool<RasterizerWithContext>> rasterizer_pool_; std::vector<std::string> variable_names_; std::vector<std::string> variable_kinds_; tensorflow::TensorShape output_resolution_; }; tensorflow::Status RasterizeOp::RenderImage( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, const tensorflow::int64 image_size, float* image_data) { int num_points = context->input(0).scalar<int>()(); TF_RETURN_IF_ERROR(rasterizer->Render( num_points, absl::MakeSpan(image_data, image_data + image_size))); return tensorflow::Status::OK(); } tensorflow::Status RasterizeOp::SetVariables( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, int outer_dim) { tensorflow::OpInputList variable_values; TF_RETURN_IF_ERROR(context->input_list("variable_values", &variable_values)); for (int index = 0; index < variable_names_.size(); ++index) { const std::string name = variable_names_[index]; const std::string kind = variable_kinds_[index]; const tensorflow::Tensor& value = variable_values[index]; const tensorflow::TensorShape value_shape = value.shape(); if (kind == "mat") { const int num_rows = value_shape.dim_size(value_shape.dims() - 2); const int num_cols = value_shape.dim_size(value_shape.dims() - 1); const int num_elements = num_rows * num_cols; const auto value_pointer = value.flat<float>().data(); TF_RETURN_IF_ERROR(rasterizer->SetUniformMatrix( name, num_cols, num_rows, true, absl::MakeConstSpan(value_pointer + num_elements * outer_dim, value_pointer + num_elements * (outer_dim + 1)))); } else if (kind == "buffer") { const tensorflow::int32 buffer_length = value_shape.dim_size(value_shape.dims() - 1); const auto value_pointer = value.flat<float>().data(); TF_RETURN_IF_ERROR(rasterizer->SetShaderStorageBuffer( name, absl::MakeConstSpan( value_pointer + buffer_length * outer_dim, value_pointer + buffer_length * (outer_dim + 1)))); } } return tensorflow::Status::OK(); } tensorflow::Status RasterizeOp::ValidateVariables( tensorflow::OpKernelContext* context, tensorflow::TensorShape* batch_shape) { tensorflow::OpInputList variable_values; TF_RETURN_IF_ERROR(context->input_list("variable_values", &variable_values)); if (variable_names_.size() != variable_values.size() || variable_names_.size() != variable_kinds_.size()) { return tensorflow::errors::InvalidArgument( "The variable names, kinds, and values must have the same size."); } bool batch_initialized = false; batch_shape->Clear(); for (int index = 0; index < variable_kinds_.size(); ++index) { const std::string name = variable_names_[index]; const std::string kind = variable_kinds_[index]; const tensorflow::Tensor& value = variable_values[index]; tensorflow::TensorShape value_batch_shape = value.shape(); if (kind == "mat") { if (value_batch_shape.dims() < 2) return tensorflow::errors::InvalidArgument( "Matrix with name='", name, "' has an invalid shape=", value_batch_shape.DebugString()); value_batch_shape.RemoveLastDims(2); } else if (kind == "buffer") { if (value_batch_shape.dims() < 1) return tensorflow::errors::InvalidArgument( "Buffer with name='", name, "' has an invalid shape=", value_batch_shape.DebugString()); value_batch_shape.RemoveLastDims(1); } if (batch_initialized == false) { *batch_shape = value_batch_shape; batch_initialized = true; } else if (*batch_shape != value_batch_shape) { return tensorflow::errors::InvalidArgument( "Variable with name='", name, "' has an invalid batch shape=", value_batch_shape); } } return tensorflow::Status::OK(); } // Register kernel with TF REGISTER_KERNEL_BUILDER(Name("Rasterize").Device(tensorflow::DEVICE_CPU), RasterizeOp);
/* Copyright 2020 The TensorFlow Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include "absl/types/span.h" #include "macros.h" #include "rasterizer_with_context.h" #include "thread_safe_resource_pool.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" static tensorflow::Status GetVariablesRank( ::tensorflow::shape_inference::InferenceContext* c, tensorflow::int32* rank) { std::vector<std::string> variable_names, variable_kinds; TF_RETURN_IF_ERROR(c->GetAttr("variable_names", &variable_names)); TF_RETURN_IF_ERROR(c->GetAttr("variable_kinds", &variable_kinds)); std::vector<tensorflow::shape_inference::ShapeHandle> variable_values; TF_RETURN_IF_ERROR(c->input("variable_values", &variable_values)); if (variable_names.size() != variable_values.size() || variable_names.size() != variable_kinds.size()) { return tensorflow::errors::InvalidArgument( "The variable names, kinds, and values must have the same size."); } for (int index = 0; index < variable_kinds.size(); index++) { absl::string_view kind = variable_kinds[index]; const tensorflow::shape_inference::ShapeHandle& h = variable_values[index]; auto batch_rank = c->Rank(h); if (kind == "mat") { if (batch_rank < 2) return tensorflow::errors::InvalidArgument( "Matrix with name='", variable_names[index], "' has an invalid rank of ", batch_rank); batch_rank -= 2; } else if (kind == "buffer") { if (batch_rank < 1) return tensorflow::errors::InvalidArgument( "Buffer with name='", variable_names[index], "' has an invalid rank of ", batch_rank); batch_rank -= 1; } if (index == 0) *rank = batch_rank; else if (*rank != batch_rank) return tensorflow::errors::InvalidArgument( "Variable with name='", variable_names[index], "' has an invalid batch rank of ", batch_rank, "; expected ", *rank); } return tensorflow::Status::OK(); } REGISTER_OP("Rasterize") .Attr("output_resolution: shape") .Attr("red_clear: float = 0.0") .Attr("green_clear: float = 0.0") .Attr("blue_clear: float = 0.0") .Attr("alpha_clear: float = 1.0") .Attr("depth_clear: float = 1.0") .Attr("enable_cull_face: bool = false") .Attr("vertex_shader: string") .Attr("fragment_shader: string") .Attr("geometry_shader: string") .Attr("variable_names: list(string)") .Attr("variable_kinds: list({'mat', 'buffer'})") .Attr("T: list({float})") .Input("num_points: int32") .Input("variable_values: T") .Output("rendered_image: float") .Doc(R"doc( Rasterization OP that runs the program specified by the supplied vertex, geometry and fragment shaders. Uniform variables and buffers can be passed to the program using variable_names, variable_kinds, and variable_values. Note that in the following, A1 to An are optional batch dimensions. output_resolution: a 2D shape containing the width and height of the resulting image. red_clear: the red component for glClear. green_clear: the green component for glClear. blue_clear: the blue component for glClear. alpha_clear: the alpha component for glClear. depth_clear: the depth value for glClearDepthf. enable_cull_face: enable face culling. vertex_shader: A string containing a valid vertex shader. fragment_shader: A string containing a valid fragment shader. geometry_shader: A string containing a valid geometry shader. variable_names: A list of strings describing the name of each variable passed to the shaders. These names must map to the name of uniforms or buffers in the supplied shaders. variable_kinds: A list of strings containing the type of each variable. Possible values for each element are `mat` and `buffer`. num_points: The number of points to be rendered. When rasterizing a mesh, this number should be set to the number of vertices in the mesh. variable_values: A list containing matrices of shape `[A1, ..., An, W, H]` and/or buffers of shape `[A1, ..., An, S]`, with `W` and `H` in `[1,4]` and S of arbitrary value. Using their associated name and kind, these values are mapped to the corresponding uniform or buffer in the program. Note that all variables must have the same batch dimensions `[A1, ..., An]`, and that matrices are expected to be in row-major format. rendered_image: A tensor of shape `[A1, ..., An, width, height, 4]`, with the width and height defined by `output_resolution`. )doc") .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { tensorflow::int32 variables_rank; TF_RETURN_IF_ERROR(GetVariablesRank(c, &variables_rank)); auto batch_shape = c->UnknownShapeOfRank(variables_rank); tensorflow::TensorShape resolution; TF_RETURN_IF_ERROR(c->GetAttr("output_resolution", &resolution)); auto image_shape = c->MakeShape({resolution.dim_size(1), resolution.dim_size(0), 4}); tensorflow::shape_inference::ShapeHandle output_shape; TF_RETURN_IF_ERROR( c->Concatenate(batch_shape, image_shape, &output_shape)); c->set_output(0, output_shape); return tensorflow::Status::OK(); }); class RasterizeOp : public tensorflow::OpKernel { public: explicit RasterizeOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) { std::string fragment_shader; std::string geometry_shader; std::string vertex_shader; float red_clear = 0.0; float green_clear = 0.0; float blue_clear = 0.0; float alpha_clear = 1.0; float depth_clear = 1.0; bool enable_cull_face = false; OP_REQUIRES_OK(context, context->GetAttr("red_clear", &red_clear)); OP_REQUIRES_OK(context, context->GetAttr("green_clear", &green_clear)); OP_REQUIRES_OK(context, context->GetAttr("blue_clear", &blue_clear)); OP_REQUIRES_OK(context, context->GetAttr("alpha_clear", &alpha_clear)); OP_REQUIRES_OK(context, context->GetAttr("depth_clear", &depth_clear)); OP_REQUIRES_OK(context, context->GetAttr("enable_cull_face", &enable_cull_face)); OP_REQUIRES_OK(context, context->GetAttr("vertex_shader", &vertex_shader)); OP_REQUIRES_OK(context, context->GetAttr("fragment_shader", &fragment_shader)); OP_REQUIRES_OK(context, context->GetAttr("geometry_shader", &geometry_shader)); OP_REQUIRES_OK(context, context->GetAttr("variable_names", &variable_names_)); OP_REQUIRES_OK(context, context->GetAttr("variable_kinds", &variable_kinds_)); OP_REQUIRES_OK(context, context->GetAttr("output_resolution", &output_resolution_)); auto rasterizer_creator = [vertex_shader, geometry_shader, fragment_shader, red_clear, green_clear, blue_clear, alpha_clear, depth_clear, enable_cull_face, this](std::unique_ptr<RasterizerWithContext>* resource) -> tensorflow::Status { return RasterizerWithContext::Create( output_resolution_.dim_size(0), output_resolution_.dim_size(1), vertex_shader, geometry_shader, fragment_shader, resource, red_clear, green_clear, blue_clear, alpha_clear, depth_clear, enable_cull_face); }; rasterizer_pool_ = std::unique_ptr<ThreadSafeResourcePool<RasterizerWithContext>>( new ThreadSafeResourcePool<RasterizerWithContext>( rasterizer_creator)); } void Compute(tensorflow::OpKernelContext* context) override { tensorflow::TensorShape batch_shape; OP_REQUIRES_OK(context, ValidateVariables(context, &batch_shape)); // Allocate the output images. tensorflow::Tensor* output_image; tensorflow::TensorShape output_image_shape; output_image_shape.AppendShape(batch_shape); output_image_shape.AddDim(output_resolution_.dim_size(1)); output_image_shape.AddDim(output_resolution_.dim_size(0)); output_image_shape.AddDim(4); OP_REQUIRES_OK(context, context->allocate_output(0, output_image_shape, &output_image)); std::unique_ptr<RasterizerWithContext> rasterizer; float* image_data = output_image->flat<float>().data(); const tensorflow::int64 image_size = output_resolution_.dim_size(0) * output_resolution_.dim_size(1) * 4; OP_REQUIRES_OK(context, rasterizer_pool_->AcquireResource(&rasterizer)); for (int i = 0; i < batch_shape.num_elements(); ++i) { OP_REQUIRES_OK(context, SetVariables(context, rasterizer, i)); OP_REQUIRES_OK(context, RenderImage(context, rasterizer, image_size, image_data + i * image_size)); } OP_REQUIRES_OK(context, rasterizer_pool_->ReturnResource(rasterizer)); } private: tensorflow::Status SetVariables( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, int outer_dim); tensorflow::Status RenderImage( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, tensorflow::int64 image_size, float* image_data); tensorflow::Status ValidateVariables(tensorflow::OpKernelContext* context, tensorflow::TensorShape* batch_shape); std::unique_ptr<ThreadSafeResourcePool<RasterizerWithContext>> rasterizer_pool_; std::vector<std::string> variable_names_; std::vector<std::string> variable_kinds_; tensorflow::TensorShape output_resolution_; }; tensorflow::Status RasterizeOp::RenderImage( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, const tensorflow::int64 image_size, float* image_data) { int num_points = context->input(0).scalar<int>()(); TF_RETURN_IF_ERROR(rasterizer->Render( num_points, absl::MakeSpan(image_data, image_data + image_size))); return tensorflow::Status::OK(); } tensorflow::Status RasterizeOp::SetVariables( tensorflow::OpKernelContext* context, std::unique_ptr<RasterizerWithContext>& rasterizer, int outer_dim) { tensorflow::OpInputList variable_values; TF_RETURN_IF_ERROR(context->input_list("variable_values", &variable_values)); for (int index = 0; index < variable_names_.size(); ++index) { const std::string name = variable_names_[index]; const std::string kind = variable_kinds_[index]; const tensorflow::Tensor& value = variable_values[index]; const tensorflow::TensorShape value_shape = value.shape(); if (kind == "mat") { const int num_rows = value_shape.dim_size(value_shape.dims() - 2); const int num_cols = value_shape.dim_size(value_shape.dims() - 1); const int num_elements = num_rows * num_cols; const auto value_pointer = value.flat<float>().data(); TF_RETURN_IF_ERROR(rasterizer->SetUniformMatrix( name, num_cols, num_rows, true, absl::MakeConstSpan(value_pointer + num_elements * outer_dim, value_pointer + num_elements * (outer_dim + 1)))); } else if (kind == "buffer") { const tensorflow::int32 buffer_length = value_shape.dim_size(value_shape.dims() - 1); const auto value_pointer = value.flat<float>().data(); TF_RETURN_IF_ERROR(rasterizer->SetShaderStorageBuffer( name, absl::MakeConstSpan( value_pointer + buffer_length * outer_dim, value_pointer + buffer_length * (outer_dim + 1)))); } } return tensorflow::Status::OK(); } tensorflow::Status RasterizeOp::ValidateVariables( tensorflow::OpKernelContext* context, tensorflow::TensorShape* batch_shape) { tensorflow::OpInputList variable_values; TF_RETURN_IF_ERROR(context->input_list("variable_values", &variable_values)); if (variable_names_.size() != variable_values.size() || variable_names_.size() != variable_kinds_.size()) { return tensorflow::errors::InvalidArgument( "The variable names, kinds, and values must have the same size."); } bool batch_initialized = false; batch_shape->Clear(); for (int index = 0; index < variable_kinds_.size(); ++index) { const std::string name = variable_names_[index]; const std::string kind = variable_kinds_[index]; const tensorflow::Tensor& value = variable_values[index]; tensorflow::TensorShape value_batch_shape = value.shape(); if (kind == "mat") { if (value_batch_shape.dims() < 2) return tensorflow::errors::InvalidArgument( "Matrix with name='", name, "' has an invalid shape=", value_batch_shape.DebugString()); value_batch_shape.RemoveLastDims(2); } else if (kind == "buffer") { if (value_batch_shape.dims() < 1) return tensorflow::errors::InvalidArgument( "Buffer with name='", name, "' has an invalid shape=", value_batch_shape.DebugString()); value_batch_shape.RemoveLastDims(1); } if (batch_initialized == false) { *batch_shape = value_batch_shape; batch_initialized = true; } else if (*batch_shape != value_batch_shape) { return tensorflow::errors::InvalidArgument( "Variable with name='", name, "' has an invalid batch shape=", value_batch_shape, " expected ", *batch_shape); } } return tensorflow::Status::OK(); } // Register kernel with TF REGISTER_KERNEL_BUILDER(Name("Rasterize").Device(tensorflow::DEVICE_CPU), RasterizeOp);
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/opengl/tests/rasterization_backend_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import grid from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.rendering.opengl import rasterization_backend from tensorflow_graphics.util import test_case _IMAGE_HEIGHT = 5 _IMAGE_WIDTH = 7 _TRIANGLE_SIZE = 2.0 def _generate_vertices_and_view_matrices(): camera_origin = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)) camera_up = ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0)) look_at_point = ((0.0, 0.0, 1.0), (0.0, 0.0, -1.0)) field_of_view = ((60 * np.math.pi / 180,), (60 * np.math.pi / 180,)) near_plane = ((0.01,), (0.01,)) far_plane = ((400.0,), (400.0,)) aspect_ratio = ((float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),), (float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),)) # Construct the view projection matrix. world_to_camera = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed(field_of_view, aspect_ratio, near_plane, far_plane) view_projection_matrix = tf.linalg.matmul(perspective_matrix, world_to_camera) depth = 1.0 vertices = (((-10.0 * _TRIANGLE_SIZE, 10.0 * _TRIANGLE_SIZE, depth), (10.0 * _TRIANGLE_SIZE, 10.0 * _TRIANGLE_SIZE, depth), (0.0, -10.0 * _TRIANGLE_SIZE, depth)), ((-_TRIANGLE_SIZE, 0.0, depth), (0.0, _TRIANGLE_SIZE, depth), (0.0, 0.0, depth))) return vertices, view_projection_matrix def _proxy_rasterize(vertices, triangles, view_projection_matrices): return rasterization_backend.rasterize(vertices, triangles, view_projection_matrices, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) class RasterizationBackendTest(test_case.TestCase): @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2, 6, 32, 2), (17, 3), (2, 6, 4, 4)), ("must have exactly 3 dimensions in axis -1", (2, 6, 32, 3), (17, 2), (2, 6, 4, 4)), ("must have a rank of 2", (2, 6, 32, 3), (3, 17, 2), (2, 6, 4, 4)), ("must have exactly 4 dimensions in axis -1", (2, 6, 32, 3), (17, 3), (2, 6, 4, 3)), ("must have exactly 4 dimensions in axis -2", (2, 6, 32, 3), (17, 3), (2, 6, 3, 4)), ("Not all batch dimensions are broadcast-compatible", (3, 6, 32, 3), (17, 3), (5, 6, 4, 4)), ) def test_rasterize_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(_proxy_rasterize, error_msg, shapes) @parameterized.parameters( (((32, 3), (17, 3), (4, 4)), (tf.float32, tf.int32, tf.float32)), (((None, 32, 3), (17, 3), (None, 4, 4)), (tf.float32, tf.int32, tf.float32)), (((None, 9, 32, 3), (17, 3), (None, 9, 4, 4)), (tf.float32, tf.int32, tf.float32)), ) def test_rasterize_exception_not_raised(self, shapes, dtypes): self.assert_exception_is_not_raised( _proxy_rasterize, shapes=shapes, dtypes=dtypes) def test_rasterize_batch_vertices_only(self): triangles = np.array(((0, 1, 2),), np.int32) vertices, view_projection_matrix = _generate_vertices_and_view_matrices() predicted_fb = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix[0], (_IMAGE_WIDTH, _IMAGE_HEIGHT)) mask = predicted_fb.foreground_mask self.assertAllEqual(mask[0, ...], tf.ones_like(mask[0, ...])) gt_layer_1 = np.zeros((_IMAGE_HEIGHT, _IMAGE_WIDTH, 1), np.float32) gt_layer_1[_IMAGE_HEIGHT // 2:, _IMAGE_WIDTH // 2:, 0] = 1.0 self.assertAllEqual(mask[1, ...], gt_layer_1) def test_rasterize_batch_view_only(self): triangles = np.array(((0, 1, 2),), np.int32) vertices, view_projection_matrix = _generate_vertices_and_view_matrices() predicted_fb = rasterization_backend.rasterize( vertices[0], triangles, view_projection_matrix, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) self.assertAllEqual(predicted_fb.foreground_mask[0, ...], tf.ones_like(predicted_fb.foreground_mask[0, ...])) self.assertAllEqual(predicted_fb.foreground_mask[1, ...], tf.zeros_like(predicted_fb.foreground_mask[1, ...])) def test_rasterize_preset(self): camera_origin = (0.0, 0.0, 0.0) camera_up = (0.0, 1.0, 0.0) look_at_point = (0.0, 0.0, 1.0) field_of_view = (60 * np.math.pi / 180,) near_plane = (0.01,) far_plane = (400.0,) # Construct the view projection matrix. model_to_eye_matrix = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed( field_of_view, (float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),), near_plane, far_plane) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) depth = 1.0 vertices = ((-2.0 * _TRIANGLE_SIZE, 0.0, depth), (0.0, _TRIANGLE_SIZE, depth), (0.0, 0.0, depth), (0.0, -_TRIANGLE_SIZE, depth)) triangles = np.array(((1, 2, 0), (0, 2, 3)), np.int32) predicted_fb = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) with self.subTest(name="triangle_index"): groundtruth_triangle_index = np.zeros((_IMAGE_HEIGHT, _IMAGE_WIDTH, 1), dtype=np.int32) groundtruth_triangle_index[..., :_IMAGE_WIDTH // 2, 0] = 0 groundtruth_triangle_index[:_IMAGE_HEIGHT // 2, _IMAGE_WIDTH // 2:, 0] = 1 self.assertAllEqual(groundtruth_triangle_index, predicted_fb.triangle_id) with self.subTest(name="mask"): groundtruth_mask = np.ones((_IMAGE_HEIGHT, _IMAGE_WIDTH, 1), dtype=np.int32) groundtruth_mask[..., :_IMAGE_WIDTH // 2, 0] = 0 self.assertAllEqual(groundtruth_mask, predicted_fb.foreground_mask) attributes = np.array( ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))).astype(np.float32) perspective_correct_interpolation = lambda geometry, pixels: glm.perspective_correct_interpolation( # pylint: disable=g-long-lambda,line-too-long geometry, attributes, pixels, model_to_eye_matrix, perspective_matrix, np.array((_IMAGE_WIDTH, _IMAGE_HEIGHT)).astype(np.float32), np.array((0.0, 0.0)).astype(np.float32)) with self.subTest(name="barycentric_coordinates_triangle_0"): geometry_0 = tf.gather(vertices, triangles[0, :]) pixels_0 = tf.transpose( grid.generate((3.5, 2.5), (6.5, 4.5), (4, 3)), perm=(1, 0, 2)) barycentrics_gt_0 = perspective_correct_interpolation( geometry_0, pixels_0) self.assertAllClose( barycentrics_gt_0, predicted_fb.barycentrics.value[2:, 3:, :], atol=1e-3) with self.subTest(name="barycentric_coordinates_triangle_1"): geometry_1 = tf.gather(vertices, triangles[1, :]) pixels_1 = tf.transpose( grid.generate((3.5, 0.5), (6.5, 1.5), (4, 2)), perm=(1, 0, 2)) barycentrics_gt_1 = perspective_correct_interpolation( geometry_1, pixels_1) self.assertAllClose( barycentrics_gt_1, predicted_fb.barycentrics.value[0:2, 3:, :], atol=1e-3)
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from absl.testing import parameterized import numpy as np import tensorflow as tf from tensorflow_graphics.geometry.representation import grid from tensorflow_graphics.geometry.transformation import look_at from tensorflow_graphics.rendering.camera import perspective from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.rendering.opengl import rasterization_backend from tensorflow_graphics.util import test_case _IMAGE_HEIGHT = 5 _IMAGE_WIDTH = 7 _TRIANGLE_SIZE = 2.0 def _generate_vertices_and_view_matrices(): camera_origin = ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)) camera_up = ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0)) look_at_point = ((0.0, 0.0, 1.0), (0.0, 0.0, -1.0)) field_of_view = ((60 * np.math.pi / 180,), (60 * np.math.pi / 180,)) near_plane = ((0.01,), (0.01,)) far_plane = ((400.0,), (400.0,)) aspect_ratio = ((float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),), (float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),)) # Construct the view projection matrix. world_to_camera = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed(field_of_view, aspect_ratio, near_plane, far_plane) # Shape [2, 4, 4] view_projection_matrix = tf.linalg.matmul(perspective_matrix, world_to_camera) depth = 1.0 # Shape [2, 3, 3] vertices = (((-10.0 * _TRIANGLE_SIZE, 10.0 * _TRIANGLE_SIZE, depth), (10.0 * _TRIANGLE_SIZE, 10.0 * _TRIANGLE_SIZE, depth), (0.0, -10.0 * _TRIANGLE_SIZE, depth)), ((-_TRIANGLE_SIZE, 0.0, depth), (0.0, _TRIANGLE_SIZE, depth), (0.0, 0.0, depth))) return vertices, view_projection_matrix def _proxy_rasterize(vertices, triangles, view_projection_matrices): return rasterization_backend.rasterize(vertices, triangles, view_projection_matrices, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) class RasterizationBackendTest(test_case.TestCase): @parameterized.parameters( ("must have exactly 3 dimensions in axis -1", (2, 32, 2), (17, 3), (2, 4, 4)), ("must have exactly 3 dimensions in axis -1", (2, 32, 3), (17, 2), (2, 4, 4)), ("must have a rank of 2", (2, 32, 3), (3, 17, 2), (2, 4, 4)), ("must have exactly 4 dimensions in axis -1", (2, 32, 3), (17, 3), (2, 4, 3)), ("must have exactly 4 dimensions in axis -2", (2, 32, 3), (17, 3), (2, 3, 4)), ("Not all batch dimensions are broadcast-compatible", (3, 32, 3), (17, 3), (5, 4, 4)), ("vertices must have a rank of 3, but it has rank 2", (32, 3), (17, 3), (4, 4)), ) def test_rasterize_exception_raised(self, error_msg, *shapes): """Tests that the shape exceptions are properly raised.""" self.assert_exception_is_raised(_proxy_rasterize, error_msg, shapes) @parameterized.parameters( (((1, 32, 3), (17, 3), (1, 4, 4)), (tf.float32, tf.int32, tf.float32)), (((None, 32, 3), (17, 3), (None, 4, 4)), (tf.float32, tf.int32, tf.float32)), (((2, 32, 3), (17, 3), (2, 4, 4)), (tf.float32, tf.int32, tf.float32)), ) def test_rasterize_exception_not_raised(self, shapes, dtypes): self.assert_exception_is_not_raised( _proxy_rasterize, shapes=shapes, dtypes=dtypes) def test_rasterize_batch_vertices_only(self): triangles = np.array(((0, 1, 2),), np.int32) vertices, view_projection_matrix = _generate_vertices_and_view_matrices() # Use just first view projection matrix. view_projection_matrix = [ view_projection_matrix[0], view_projection_matrix[0] ] predicted_fb = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) mask = predicted_fb.foreground_mask self.assertAllEqual(mask[0, ...], tf.ones_like(mask[0, ...])) gt_layer_1 = np.zeros((_IMAGE_HEIGHT, _IMAGE_WIDTH, 1), np.float32) gt_layer_1[_IMAGE_HEIGHT // 2:, _IMAGE_WIDTH // 2:, 0] = 1.0 self.assertAllEqual(mask[1, ...], gt_layer_1) def test_rasterize_batch_view_only(self): triangles = np.array(((0, 1, 2),), np.int32) vertices, view_projection_matrix = _generate_vertices_and_view_matrices() vertices = np.array([vertices[0], vertices[0]], dtype=np.float32) predicted_fb = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) self.assertAllEqual(predicted_fb.foreground_mask[0, ...], tf.ones_like(predicted_fb.foreground_mask[0, ...])) self.assertAllEqual(predicted_fb.foreground_mask[1, ...], tf.zeros_like(predicted_fb.foreground_mask[1, ...])) def test_rasterize_preset(self): camera_origin = (0.0, 0.0, 0.0) camera_up = (0.0, 1.0, 0.0) look_at_point = (0.0, 0.0, 1.0) field_of_view = (60 * np.math.pi / 180,) near_plane = (0.01,) far_plane = (400.0,) # Construct the view projection matrix. model_to_eye_matrix = look_at.right_handed(camera_origin, look_at_point, camera_up) perspective_matrix = perspective.right_handed( field_of_view, (float(_IMAGE_WIDTH) / float(_IMAGE_HEIGHT),), near_plane, far_plane) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) view_projection_matrix = tf.expand_dims(view_projection_matrix, axis=0) depth = 1.0 vertices = np.array([[(-2.0 * _TRIANGLE_SIZE, 0.0, depth), (0.0, _TRIANGLE_SIZE, depth), (0.0, 0.0, depth), (0.0, -_TRIANGLE_SIZE, depth)]], dtype=np.float32) triangles = np.array(((1, 2, 0), (0, 2, 3)), np.int32) predicted_fb = rasterization_backend.rasterize( vertices, triangles, view_projection_matrix, (_IMAGE_WIDTH, _IMAGE_HEIGHT)) with self.subTest(name="triangle_index"): groundtruth_triangle_index = np.zeros((1, _IMAGE_HEIGHT, _IMAGE_WIDTH, 1), dtype=np.int32) groundtruth_triangle_index[..., :_IMAGE_WIDTH // 2, 0] = 0 groundtruth_triangle_index[..., :_IMAGE_HEIGHT // 2, _IMAGE_WIDTH // 2:, 0] = 1 self.assertAllEqual(groundtruth_triangle_index, predicted_fb.triangle_id) with self.subTest(name="mask"): groundtruth_mask = np.ones((1, _IMAGE_HEIGHT, _IMAGE_WIDTH, 1), dtype=np.int32) groundtruth_mask[..., :_IMAGE_WIDTH // 2, 0] = 0 self.assertAllEqual(groundtruth_mask, predicted_fb.foreground_mask) attributes = np.array( ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))).astype(np.float32) perspective_correct_interpolation = lambda geometry, pixels: glm.perspective_correct_interpolation( # pylint: disable=g-long-lambda,line-too-long geometry, attributes, pixels, model_to_eye_matrix, perspective_matrix, np.array((_IMAGE_WIDTH, _IMAGE_HEIGHT)).astype(np.float32), np.array((0.0, 0.0)).astype(np.float32)) with self.subTest(name="barycentric_coordinates_triangle_0"): geometry_0 = tf.gather(vertices, triangles[0, :], axis=1) pixels_0 = tf.transpose( grid.generate((3.5, 2.5), (6.5, 4.5), (4, 3)), perm=(1, 0, 2)) barycentrics_gt_0 = perspective_correct_interpolation( geometry_0, pixels_0) self.assertAllClose( barycentrics_gt_0, predicted_fb.barycentrics.value[0, 2:, 3:, :], atol=1e-3) with self.subTest(name="barycentric_coordinates_triangle_1"): geometry_1 = tf.gather(vertices, triangles[1, :], axis=1) pixels_1 = tf.transpose( grid.generate((3.5, 0.5), (6.5, 1.5), (4, 2)), perm=(1, 0, 2)) barycentrics_gt_1 = perspective_correct_interpolation( geometry_1, pixels_1) self.assertAllClose( barycentrics_gt_1, predicted_fb.barycentrics.value[0, 0:2, 3:, :], atol=1e-3)
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/rasterization_backend.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rasterization backends selector for TF Graphics.""" import enum from tensorflow_graphics.rendering.opengl import rasterization_backend as gl_backend from tensorflow_graphics.util import export_api class RasterizationBackends(enum.Enum): OPENGL = 0 _BACKENDS = { RasterizationBackends.OPENGL: gl_backend, } def rasterize(vertices, triangles, view_projection_matrices, image_size, backend=RasterizationBackends.OPENGL): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Note: In the following, A1 to An are optional batch dimensions which must be broadcast compatible for inputs `vertices` and `view_projection_matrices`. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. backend: An enum containing the backend method to use for rasterization. Supported options are defined in the RasterizationBackends enum. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ return _BACKENDS[backend].rasterize(vertices, triangles, view_projection_matrices, image_size) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Rasterization backends selector for TF Graphics.""" import enum from tensorflow_graphics.rendering.opengl import rasterization_backend as gl_backend from tensorflow_graphics.util import export_api class RasterizationBackends(enum.Enum): OPENGL = 0 _BACKENDS = { RasterizationBackends.OPENGL: gl_backend, } def rasterize(vertices, triangles, view_projection_matrices, image_size, backend=RasterizationBackends.OPENGL): """Rasterizes the scene. This rasterizer estimates which triangle is associated with each pixel using OpenGL. Args: vertices: A tensor of shape `[batch, num_vertices, 3]` containing batches of vertices, each defined by a 3D point. triangles: A tensor of shape `[num_triangles, 3]` containing triangles, each associated with 3 vertices from `scene_vertices` view_projection_matrices: A tensor of shape `[batch, 4, 4]` containing batches of view projection matrices image_size: An tuple of integers (width, height) containing the dimensions in pixels of the rasterized image. backend: An enum containing the backend method to use for rasterization. Supported options are defined in the RasterizationBackends enum. Returns: A Framebuffer containing the rasterized values: barycentrics, triangle_id, foreground_mask, vertex_ids. Returned Tensors have shape [batch, num_layers, height, width, channels] Note: triangle_id contains the triangle id value for each pixel in the output image. For pixels within the mesh, this is the integer value in the range [0, num_vertices] from triangles. For vertices outside the mesh this is 0; 0 can either indicate belonging to triangle 0, or being outside the mesh. This ensures all returned triangle ids will validly index into the vertex array, enabling the use of tf.gather with indices from this tensor. The barycentric coordinates can be used to determine pixel validity instead. See framebuffer.py for a description of the Framebuffer fields. """ return _BACKENDS[backend].rasterize(vertices, triangles, view_projection_matrices, image_size) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/tests/framebuffer_test.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.rendering.framebuffer.""" import tensorflow as tf from tensorflow_graphics.rendering import framebuffer as fb from tensorflow_graphics.util import test_case class FramebufferTest(test_case.TestCase): def test_initialize_rasterized_attribute_with_wrong_rank(self): with self.assertRaisesRegex( ValueError, "Expected value and derivatives to be of the same rank"): fb.RasterizedAttribute( tf.ones([4, 4, 1]), tf.ones([4, 3]), tf.ones([3, 4, 4, 5, 5])) def test_initialize_rasterized_attribute_with_wrong_shapes(self): with self.assertRaisesRegex(tf.errors.InvalidArgumentError, "Expected all input shapes to be the same"): fb.RasterizedAttribute(tf.ones([1, 1, 4, 4, 1]), tf.ones([1, 1, 4, 3, 1])) def test_initialize_framebuffer_with_wrong_rank(self): with self.assertRaisesRegex(ValueError, "Expected all inputs to have the same rank"): fb.Framebuffer( fb.RasterizedAttribute(tf.ones([1, 1, 4, 4, 1])), tf.ones([4, 3]), tf.ones([3, 4, 4, 5, 5]), tf.ones([3, 4, 4, 5, 5])) def test_initialize_framebuffer_with_wrong_shapes(self): with self.assertRaisesRegex(tf.errors.InvalidArgumentError, "Expected all input shapes to be the same"): fb.Framebuffer( fb.RasterizedAttribute(tf.ones([1, 1, 4, 4, 3])), tf.ones([1, 1, 4, 4, 1]), tf.ones([1, 1, 4, 4, 3]), tf.ones([1, 1, 4, 4, 1]), {"an_attr": fb.RasterizedAttribute(tf.ones([1, 1, 4, 3, 4]))}) if __name__ == "__main__": tf.test.main()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Tests for tensorflow_graphics.rendering.framebuffer.""" import tensorflow as tf from tensorflow_graphics.rendering import framebuffer as fb from tensorflow_graphics.util import test_case class FramebufferTest(test_case.TestCase): def test_initialize_rasterized_attribute_and_derivatives_with_wrong_rank( self): with self.assertRaisesRegex( ValueError, "Expected value and derivatives to be of the same rank"): fb.RasterizedAttribute( tf.ones([4, 4, 1]), tf.ones([4, 3]), tf.ones([3, 4, 4, 5, 5])) def test_initialize_rasterized_attribute_with_wrong_rank(self): with self.assertRaisesRegex(ValueError, "Expected input value to be rank 4"): fb.RasterizedAttribute(tf.ones([4, 4, 1])) def test_initialize_rasterized_attribute_with_wrong_shapes(self): with self.assertRaisesRegex(tf.errors.InvalidArgumentError, "Expected all input shapes to be the same"): fb.RasterizedAttribute( tf.ones([2, 4, 4, 1]), tf.ones([2, 4, 3, 1]), tf.ones([2, 4, 3, 5])) def test_initialize_framebuffer_with_wrong_rank(self): with self.assertRaisesRegex(ValueError, "Expected all inputs to have the same rank"): fb.Framebuffer( fb.RasterizedAttribute(tf.ones([1, 4, 4, 1])), tf.ones([4, 3]), tf.ones([3, 4, 4, 5, 5]), tf.ones([3, 4, 4, 5, 5])) def test_initialize_framebuffer_with_wrong_shapes(self): with self.assertRaisesRegex(tf.errors.InvalidArgumentError, "Expected all input shapes to be the same"): fb.Framebuffer( fb.RasterizedAttribute(tf.ones([2, 4, 4, 3])), tf.ones([2, 4, 4, 1]), tf.ones([2, 4, 4, 3]), tf.ones([2, 4, 4, 1]), {"an_attr": fb.RasterizedAttribute(tf.ones([2, 4, 3, 4]))}) if __name__ == "__main__": tf.test.main()
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/triangle_rasterizer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width, 1]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) rasterized = rasterization_backend.rasterize(vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = { "mask": rasterized.foreground_mask, "triangle_indices": rasterized.triangle_id } # Extract batch shape in order to make sure it is preserved after `gather` # operation. batch_shape = rasterized.triangle_id.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices_per_pixel = tf.gather( vertices, rasterized.vertex_ids, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(rasterized.foreground_mask, vertices.dtype) outputs["barycentrics"] = mask_float * barycentrics for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) outputs[key] = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, rasterized.triangle_id[..., 0], len(batch_shape)) return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements a differentiable rasterizer of triangular meshes. The resulting rendering contains perspective-correct interpolation of attributes defined at the vertices of the rasterized meshes. This rasterizer does not provide gradients through visibility, but it does through visible geometry and attributes. """ import tensorflow as tf from tensorflow_graphics.rendering import rasterization_backend from tensorflow_graphics.rendering.opengl import math as glm from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _tile_to_image_size(tensor, image_shape): """Inserts `image_shape` dimensions after `tensor` batch dimension.""" non_batch_dims = len(tensor.shape) - 1 for _ in image_shape: tensor = tf.expand_dims(tensor, axis=1) tensor = tf.tile(tensor, [1] + image_shape + [1] * non_batch_dims) return tensor def _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float): """Creates the pixels grid and computes barycentrics.""" # Construct the pixel grid with half-integer pixel centers. width = image_size_float[1] height = image_size_float[0] px = tf.linspace(0.5, width - 0.5, num=int(width)) py = tf.linspace(0.5, height - 0.5, num=int(height)) xv, yv = tf.meshgrid(px, py) pixel_position = tf.stack((xv, yv), axis=-1) # Since `model_to_eye_matrix` is defined per batch, while vertices in # `vertices_per_pixel` are defined per batch per pixel, we have to make them # broadcast-compatible. In other words we want to tile matrices per vertex # per pixel. image_shape = vertices_per_pixel.shape[1:-1] model_to_eye_matrix = _tile_to_image_size(model_to_eye_matrix, image_shape) perspective_matrix = _tile_to_image_size(perspective_matrix, image_shape) return glm.perspective_correct_barycentrics(vertices_per_pixel, pixel_position, model_to_eye_matrix, perspective_matrix, (width, height)) def _perspective_correct_attributes(attribute, barycentrics, triangles, triangle_index, len_batch_shape): attribute = tf.gather(attribute, triangles, axis=-2) attribute_per_pixel = tf.gather( attribute, triangle_index, axis=-3, batch_dims=len_batch_shape) return glm.interpolate_attributes(attribute_per_pixel, barycentrics) def _dim_value(dim): return 1 if dim is None else tf.compat.v1.dimension_value(dim) def _merge_batch_dims(tensor, last_axis): """Merges all dimensions into one starting from 0 till `last_axis` exluding.""" return tf.reshape(tensor, [-1] + tensor.shape.as_list()[last_axis:]) def _restore_batch_dims(tensor, batch_shape): """Unpack first dimension into batch_shape, preserving the rest of the dimensions.""" return tf.reshape(tensor, batch_shape + tensor.shape.as_list()[1:]) def rasterize(vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix, image_size, backend=rasterization_backend.RasterizationBackends.OPENGL, name=None): """Rasterizes the scene. Note: In the following, A1 to An are optional batch dimensions. Args: vertices: A tensor of shape `[A1, ..., An, V, 3]` containing batches of `V` vertices, each defined by a 3D point. triangles: A tensor of shape `[T, 3]` containing `T` triangles, each associated with 3 vertices from `vertices`. attributes: A dictionary of tensors, each of shape `[A1, ..., An, V, K_a]` containing batches of `V` vertices, each associated with K-dimensional attributes. K_a may vary by attribute. model_to_eye_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to transform vertices from model to eye coordinates. perspective_matrix: A tensor of shape `[A1, ..., An, 4, 4]` containing batches of matrices used to project vertices from eye to clip coordinates. image_size: A tuple (height, width) containing the dimensions in pixels of the rasterized image. backend: A rasterization_backend.RasterizationBackends enum containing the backend method to use for rasterization. name: A name for this op. Defaults to 'triangle_rasterizer_rasterize'. Returns: A dictionary. The key "mask" is of shape `[A1, ..., An, height, width, 1]` and stores a value of `0` of the pixel is assciated with the background, and `1` with the foreground. The key "barycentrics" is of shape `[A1, ..., An, height, width, 3]` and stores barycentric weights. Finally, the dictionary contains perspective correct interpolated attributes of shape `[A1, ..., An, height, width, K]` per entry in the `attributes` dictionary. """ with tf.compat.v1.name_scope(name, "triangle_rasterizer_rasterize", (vertices, triangles, attributes, model_to_eye_matrix, perspective_matrix)): vertices = tf.convert_to_tensor(value=vertices) triangles = tf.convert_to_tensor(value=triangles) model_to_eye_matrix = tf.convert_to_tensor(value=model_to_eye_matrix) perspective_matrix = tf.convert_to_tensor(value=perspective_matrix) shape.check_static( tensor=vertices, tensor_name="vertices", has_rank_greater_than=1, has_dim_equals=((-1, 3))) shape.check_static( tensor=triangles, tensor_name="triangles", has_rank=2, has_dim_equals=((-1, 3))) shape.check_static( tensor=model_to_eye_matrix, tensor_name="model_to_eye_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) shape.check_static( tensor=perspective_matrix, tensor_name="perspective_matrix", has_dim_equals=(((-2, 4), (-1, 4)))) image_size_float = (float(image_size[0]), float(image_size[1])) image_size_backend = (int(image_size[1]), int(image_size[0])) input_batch_shape = vertices.shape[:-2] perspective_matrix = _merge_batch_dims(perspective_matrix, last_axis=-2) model_to_eye_matrix = _merge_batch_dims(model_to_eye_matrix, last_axis=-2) view_projection_matrix = tf.linalg.matmul(perspective_matrix, model_to_eye_matrix) vertices = _merge_batch_dims(vertices, last_axis=-2) rasterized = rasterization_backend.rasterize(vertices, triangles, view_projection_matrix, image_size_backend, backend) outputs = { "mask": _restore_batch_dims(rasterized.foreground_mask, input_batch_shape), "triangle_indices": _restore_batch_dims(rasterized.triangle_id, input_batch_shape) } # Extract batch shape in order to make sure it is preserved after `gather` # operation. batch_shape = rasterized.triangle_id.shape[:-3] batch_shape = [_dim_value(dim) for dim in batch_shape] vertices_per_pixel = tf.gather( vertices, rasterized.vertex_ids, batch_dims=len(batch_shape)) barycentrics = _perspective_correct_barycentrics(vertices_per_pixel, model_to_eye_matrix, perspective_matrix, image_size_float) mask_float = tf.cast(rasterized.foreground_mask, vertices.dtype) outputs["barycentrics"] = _restore_batch_dims(mask_float * barycentrics, input_batch_shape) for key, attribute in attributes.items(): attribute = tf.convert_to_tensor(value=attribute) attribute = _merge_batch_dims(attribute, last_axis=-2) masked_attribute = mask_float * _perspective_correct_attributes( attribute, barycentrics, triangles, rasterized.triangle_id[..., 0], len(batch_shape)) masked_attribute = _restore_batch_dims(masked_attribute, input_batch_shape) outputs[key] = masked_attribute return outputs # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/reflectance/lambertian.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Lambertian reflectance.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo, name=None): """Evaluates the brdf of a Lambertian surface. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. name: A name for this op. Defaults to "lambertian_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of reflected light in any outgoing direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "lambertian_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) common_shape = shape.get_broadcasted_shape(min_dot.shape, albedo.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) albedo = tf.broadcast_to(albedo, common_shape) return tf.compat.v1.where(condition, albedo / math.pi, tf.zeros_like(albedo)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Lambertian reflectance.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, albedo, name=None): """Evaluates the brdf of a Lambertian surface. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. name: A name for this op. Defaults to "lambertian_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of reflected light in any outgoing direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "lambertian_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) common_shape = shape.get_broadcasted_shape(min_dot.shape, albedo.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) albedo = tf.broadcast_to(albedo, common_shape) return tf.compat.v1.where(condition, albedo / math.pi, tf.zeros_like(albedo)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/geometry/representation/mesh/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/math/vector.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow vector utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def cross(vector1, vector2, axis=-1, name=None): """Computes the cross product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. vector2: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. axis: The dimension along which to compute the cross product. name: A name for this op which defaults to "vector_cross". Returns: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents the result of the cross product. """ with tf.compat.v1.name_scope(name, "vector_cross", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(axis, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(axis, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) vector1_x, vector1_y, vector1_z = tf.unstack(vector1, axis=axis) vector2_x, vector2_y, vector2_z = tf.unstack(vector2, axis=axis) n_x = vector1_y * vector2_z - vector1_z * vector2_y n_y = vector1_z * vector2_x - vector1_x * vector2_z n_z = vector1_x * vector2_y - vector1_y * vector2_x return tf.stack((n_x, n_y, n_z), axis=axis) def dot(vector1, vector2, axis=-1, keepdims=True, name=None): """Computes the dot product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. vector2: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. axis: The dimension along which to compute the dot product. keepdims: If True, retains reduced dimensions with length 1. name: A name for this op which defaults to "vector_dot". Returns: A tensor of shape `[A1, ..., Ai = 1, ..., An]`, where the dimension i = axis represents the result of the dot product. """ with tf.compat.v1.name_scope(name, "vector_dot", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) shape.compare_dimensions( tensors=(vector1, vector2), axes=axis, tensor_names=("vector1", "vector2")) return tf.reduce_sum( input_tensor=vector1 * vector2, axis=axis, keepdims=keepdims) def reflect(vector, normal, axis=-1, name=None): r"""Computes the reflection direction for an incident vector. For an incident vector \\(\mathbf{v}\\) and normal $$\mathbf{n}$$ this function computes the reflected vector as \\(\mathbf{r} = \mathbf{v} - 2(\mathbf{n}^T\mathbf{v})\mathbf{n}\\). Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. normal: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a normal around which the vector needs to be reflected. The normal vector needs to be normalized. axis: The dimension along which to compute the reflection. name: A name for this op which defaults to "vector_reflect". Returns: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a reflected vector. """ with tf.compat.v1.name_scope(name, "vector_reflect", [vector, normal]): vector = tf.convert_to_tensor(value=vector) normal = tf.convert_to_tensor(value=normal) shape.compare_dimensions( tensors=(vector, normal), axes=axis, tensor_names=("vector", "normal")) shape.compare_batch_dimensions( tensors=(vector, normal), last_axes=-1, broadcast_compatible=True) normal = asserts.assert_normalized(normal, axis=axis) dot_product = dot(vector, normal, axis=axis) return vector - 2.0 * dot_product * normal # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tensorflow vector utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def cross(vector1, vector2, axis=-1, name=None): """Computes the cross product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. vector2: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents a 3d vector. axis: The dimension along which to compute the cross product. name: A name for this op which defaults to "vector_cross". Returns: A tensor of shape `[A1, ..., Ai = 3, ..., An]`, where the dimension i = axis represents the result of the cross product. """ with tf.compat.v1.name_scope(name, "vector_cross", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.check_static( tensor=vector1, tensor_name="vector1", has_dim_equals=(axis, 3)) shape.check_static( tensor=vector2, tensor_name="vector2", has_dim_equals=(axis, 3)) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) vector1_x, vector1_y, vector1_z = tf.unstack(vector1, axis=axis) vector2_x, vector2_y, vector2_z = tf.unstack(vector2, axis=axis) n_x = vector1_y * vector2_z - vector1_z * vector2_y n_y = vector1_z * vector2_x - vector1_x * vector2_z n_z = vector1_x * vector2_y - vector1_y * vector2_x return tf.stack((n_x, n_y, n_z), axis=axis) def dot(vector1, vector2, axis=-1, keepdims=True, name=None): """Computes the dot product between two tensors along an axis. Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector1: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. vector2: Tensor of rank R and shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. axis: The dimension along which to compute the dot product. keepdims: If True, retains reduced dimensions with length 1. name: A name for this op which defaults to "vector_dot". Returns: A tensor of shape `[A1, ..., Ai = 1, ..., An]`, where the dimension i = axis represents the result of the dot product. """ with tf.compat.v1.name_scope(name, "vector_dot", [vector1, vector2]): vector1 = tf.convert_to_tensor(value=vector1) vector2 = tf.convert_to_tensor(value=vector2) shape.compare_batch_dimensions( tensors=(vector1, vector2), last_axes=-1, broadcast_compatible=True) shape.compare_dimensions( tensors=(vector1, vector2), axes=axis, tensor_names=("vector1", "vector2")) return tf.reduce_sum( input_tensor=vector1 * vector2, axis=axis, keepdims=keepdims) def reflect(vector, normal, axis=-1, name=None): r"""Computes the reflection direction for an incident vector. For an incident vector \\(\mathbf{v}\\) and normal $$\mathbf{n}$$ this function computes the reflected vector as \\(\mathbf{r} = \mathbf{v} - 2(\mathbf{n}^T\mathbf{v})\mathbf{n}\\). Note: In the following, A1 to An are optional batch dimensions, which should be broadcast compatible. Args: vector: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a vector. normal: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a normal around which the vector needs to be reflected. The normal vector needs to be normalized. axis: The dimension along which to compute the reflection. name: A name for this op which defaults to "vector_reflect". Returns: A tensor of shape `[A1, ..., Ai, ..., An]`, where the dimension i = axis represents a reflected vector. """ with tf.compat.v1.name_scope(name, "vector_reflect", [vector, normal]): vector = tf.convert_to_tensor(value=vector) normal = tf.convert_to_tensor(value=normal) shape.compare_dimensions( tensors=(vector, normal), axes=axis, tensor_names=("vector", "normal")) shape.compare_batch_dimensions( tensors=(vector, normal), last_axes=-1, broadcast_compatible=True) normal = asserts.assert_normalized(normal, axis=axis) dot_product = dot(vector, normal, axis=axis) return vector - 2.0 * dot_product * normal # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name="assert_rotation_matrix_normalized"): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.debugging.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name="rotation_matrix_3d_from_axis_angle"): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name="rotation_matrix_3d_from_euler"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_3d_from_euler_with_small_angles"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler_with_small_angles". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name="rotation_matrix_3d_from_quaternion"): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_3d_inverse"): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_3d_is_valid"): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_3d_rotate"): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements TensorFlow 3d rotation matrix utility functions. More details rotation matrices can be found on [this page.] (https://en.wikipedia.org/wiki/Rotation_matrix) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags import tensorflow as tf from tensorflow_graphics.geometry.transformation import rotation_matrix_common from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape from tensorflow_graphics.util import tfg_flags FLAGS = flags.FLAGS def _build_matrix_from_sines_and_cosines(sin_angles, cos_angles): """Builds a rotation matrix from sines and cosines of Euler angles. Note: In the following, A1 to An are optional batch dimensions. Args: sin_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the sine of the Euler angles. cos_angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the cosine of the Euler angles. Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. """ sin_angles.shape.assert_is_compatible_with(cos_angles.shape) sx, sy, sz = tf.unstack(sin_angles, axis=-1) cx, cy, cz = tf.unstack(cos_angles, axis=-1) m00 = cy * cz m01 = (sx * sy * cz) - (cx * sz) m02 = (cx * sy * cz) + (sx * sz) m10 = cy * sz m11 = (sx * sy * sz) + (cx * cz) m12 = (cx * sy * sz) - (sx * cz) m20 = -sy m21 = sx * cy m22 = cx * cy matrix = tf.stack((m00, m01, m02, m10, m11, m12, m20, m21, m22), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=sin_angles)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def assert_rotation_matrix_normalized(matrix, eps=1e-3, name="assert_rotation_matrix_normalized"): """Checks whether a matrix is a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. eps: The absolute tolerance parameter. name: A name for this op that defaults to 'assert_rotation_matrix_normalized'. Returns: The input matrix, with dependence on the assertion operator in the graph. Raises: tf.errors.InvalidArgumentError: If rotation_matrix_3d is not normalized. """ if not FLAGS[tfg_flags.TFG_ADD_ASSERTS_TO_GRAPH].value: return matrix with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) is_matrix_normalized = is_valid(matrix, atol=eps) with tf.control_dependencies([ tf.debugging.assert_equal( is_matrix_normalized, tf.ones_like(is_matrix_normalized, dtype=tf.bool)) ]): return tf.identity(matrix) def from_axis_angle(axis, angle, name="rotation_matrix_3d_from_axis_angle"): """Convert an axis-angle representation to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: axis: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized axis. angle: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a normalized axis. name: A name for this op that defaults to "rotation_matrix_3d_from_axis_angle". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represents a 3d rotation matrix. Raises: ValueError: If the shape of `axis` or `angle` is not supported. """ with tf.name_scope(name): axis = tf.convert_to_tensor(value=axis) angle = tf.convert_to_tensor(value=angle) shape.check_static(tensor=axis, tensor_name="axis", has_dim_equals=(-1, 3)) shape.check_static( tensor=angle, tensor_name="angle", has_dim_equals=(-1, 1)) shape.compare_batch_dimensions( tensors=(axis, angle), tensor_names=("axis", "angle"), last_axes=-2, broadcast_compatible=True) axis = asserts.assert_normalized(axis) sin_axis = tf.sin(angle) * axis cos_angle = tf.cos(angle) cos1_axis = (1.0 - cos_angle) * axis _, axis_y, axis_z = tf.unstack(axis, axis=-1) cos1_axis_x, cos1_axis_y, _ = tf.unstack(cos1_axis, axis=-1) sin_axis_x, sin_axis_y, sin_axis_z = tf.unstack(sin_axis, axis=-1) tmp = cos1_axis_x * axis_y m01 = tmp - sin_axis_z m10 = tmp + sin_axis_z tmp = cos1_axis_x * axis_z m02 = tmp + sin_axis_y m20 = tmp - sin_axis_y tmp = cos1_axis_y * axis_z m12 = tmp - sin_axis_x m21 = tmp + sin_axis_x diag = cos1_axis * axis + cos_angle diag_x, diag_y, diag_z = tf.unstack(diag, axis=-1) matrix = tf.stack((diag_x, m01, m02, m10, diag_y, m12, m20, m21, diag_z), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=axis)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def from_euler(angles, name="rotation_matrix_3d_from_euler"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = tf.sin(angles) cos_angles = tf.cos(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_euler_with_small_angles_approximation( angles, name="rotation_matrix_3d_from_euler_with_small_angles"): r"""Convert an Euler angle representation to a rotation matrix. The resulting matrix is $$\mathbf{R} = \mathbf{R}_z\mathbf{R}_y\mathbf{R}_x$$. Under the small angle assumption, $$\sin(x)$$ and $$\cos(x)$$ can be approximated by their second order Taylor expansions, where $$\sin(x) \approx x$$ and $$\cos(x) \approx 1 - \frac{x^2}{2}$$. In the current implementation, the smallness of the angles is not verified. Note: In the following, A1 to An are optional batch dimensions. Args: angles: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the three small Euler angles. `[A1, ..., An, 0]` is the angle about `x` in radians, `[A1, ..., An, 1]` is the angle about `y` in radians and `[A1, ..., An, 2]` is the angle about `z` in radians. name: A name for this op that defaults to "rotation_matrix_3d_from_euler_with_small_angles". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `angles` is not supported. """ with tf.name_scope(name): angles = tf.convert_to_tensor(value=angles) shape.check_static( tensor=angles, tensor_name="angles", has_dim_equals=(-1, 3)) sin_angles = angles cos_angles = 1.0 - 0.5 * tf.square(angles) return _build_matrix_from_sines_and_cosines(sin_angles, cos_angles) def from_quaternion(quaternion, name="rotation_matrix_3d_from_quaternion"): """Convert a quaternion to a rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: quaternion: A tensor of shape `[A1, ..., An, 4]`, where the last dimension represents a normalized quaternion. name: A name for this op that defaults to "rotation_matrix_3d_from_quaternion". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `quaternion` is not supported. """ with tf.name_scope(name): quaternion = tf.convert_to_tensor(value=quaternion) shape.check_static( tensor=quaternion, tensor_name="quaternion", has_dim_equals=(-1, 4)) quaternion = asserts.assert_normalized(quaternion) x, y, z, w = tf.unstack(quaternion, axis=-1) tx = 2.0 * x ty = 2.0 * y tz = 2.0 * z twx = tx * w twy = ty * w twz = tz * w txx = tx * x txy = ty * x txz = tz * x tyy = ty * y tyz = tz * y tzz = tz * z matrix = tf.stack((1.0 - (tyy + tzz), txy - twz, txz + twy, txy + twz, 1.0 - (txx + tzz), tyz - twx, txz - twy, tyz + twx, 1.0 - (txx + tyy)), axis=-1) # pyformat: disable output_shape = tf.concat((tf.shape(input=quaternion)[:-1], (3, 3)), axis=-1) return tf.reshape(matrix, shape=output_shape) def inverse(matrix, name="rotation_matrix_3d_inverse"): """Computes the inverse of a 3D rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_inverse". Returns: A tensor of shape `[A1, ..., An, 3, 3]`, where the last two dimensions represent a 3d rotation matrix. Raises: ValueError: If the shape of `matrix` is not supported. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) matrix = assert_rotation_matrix_normalized(matrix) ndims = matrix.shape.ndims perm = list(range(ndims - 2)) + [ndims - 1, ndims - 2] return tf.transpose(a=matrix, perm=perm) def is_valid(matrix, atol=1e-3, name="rotation_matrix_3d_is_valid"): """Determines if a matrix is a valid rotation matrix. Note: In the following, A1 to An are optional batch dimensions. Args: matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last two dimensions represent a matrix. atol: Absolute tolerance parameter. name: A name for this op that defaults to "rotation_matrix_3d_is_valid". Returns: A tensor of type `bool` and shape `[A1, ..., An, 1]` where False indicates that the input is not a valid rotation matrix. """ with tf.name_scope(name): matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) return rotation_matrix_common.is_valid(matrix, atol) def rotate(point, matrix, name="rotation_matrix_3d_rotate"): """Rotate a point using a rotation matrix 3d. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Args: point: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. matrix: A tensor of shape `[A1, ..., An, 3,3]`, where the last dimension represents a 3d rotation matrix. name: A name for this op that defaults to "rotation_matrix_3d_rotate". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a 3d point. Raises: ValueError: If the shape of `point` or `rotation_matrix_3d` is not supported. """ with tf.name_scope(name): point = tf.convert_to_tensor(value=point) matrix = tf.convert_to_tensor(value=matrix) shape.check_static( tensor=point, tensor_name="point", has_dim_equals=(-1, 3)) shape.check_static( tensor=matrix, tensor_name="matrix", has_rank_greater_than=1, has_dim_equals=((-2, 3), (-1, 3))) shape.compare_batch_dimensions( tensors=(point, matrix), tensor_names=("point", "matrix"), last_axes=(-2, -3), broadcast_compatible=True) matrix = assert_rotation_matrix_normalized(matrix) point = tf.expand_dims(point, axis=-1) common_batch_shape = shape.get_broadcasted_shape(point.shape[:-2], matrix.shape[:-2]) def dim_value(dim): return 1 if dim is None else tf.compat.dimension_value(dim) common_batch_shape = [dim_value(dim) for dim in common_batch_shape] point = tf.broadcast_to(point, common_batch_shape + [3, 1]) matrix = tf.broadcast_to(matrix, common_batch_shape + [3, 3]) rotated_point = tf.matmul(matrix, point) return tf.squeeze(rotated_point, axis=-1) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/projects/cvxnet/lib/resnet.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ResNet Architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf keras = tf.keras class Resnet18(keras.Model): """ResNet-18 (V1).""" def __init__(self, feature_dims): super(Resnet18, self).__init__() self.conv1 = keras.layers.Conv2D( 64, 7, strides=2, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.relu1 = keras.layers.ReLU() self.maxpool = keras.layers.MaxPooling2D(3, strides=2, padding='same') layers = [2, 2, 2, 2] self.layer1 = ResLayer(BasicBlock, 64, 64, layers[0]) self.layer2 = ResLayer(BasicBlock, 64, 128, layers[1], stride=2) self.layer3 = ResLayer(BasicBlock, 128, 256, layers[2], stride=2) self.layer4 = ResLayer(BasicBlock, 256, 512, layers[3], stride=2) self.fc = keras.layers.Dense(feature_dims, activation=None) def call(self, x, training=False): x = self.conv1(x) x = self.bn1(x, training=training) x = self.relu1(x) x = self.maxpool(x) x = self.layer1(x, training=training) x = self.layer2(x, training=training) x = self.layer3(x, training=training) x = self.layer4(x, training=training) x = tf.reduce_mean(x, axis=(1, 2)) x = self.fc(x) return x class ResLayer(keras.Model): """Residual Layer.""" def __init__(self, block, inplanes, planes, blocks, stride=1): super(ResLayer, self).__init__() if stride != 1 or inplanes != planes: downsample = True else: downsample = False self.conv_layers = [] self.conv_layers.append(block(planes, stride, downsample=downsample)) for unused_i in range(1, blocks): self.conv_layers.append(block(planes)) def call(self, x, training=True): for layer in self.conv_layers: x = layer(x, training=training) return x class BasicBlock(keras.Model): """Building block of resnet.""" def __init__(self, planes, stride=1, downsample=False): super(BasicBlock, self).__init__() self.conv1 = keras.layers.Conv2D( planes, 3, strides=stride, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.conv2 = keras.layers.Conv2D(planes, 3, padding='same', use_bias=False) self.bn2 = keras.layers.BatchNormalization() if downsample: self.downsample = downsample self.dconv1 = keras.layers.Conv2D( planes, 1, strides=stride, padding='same', use_bias=False) self.dbn1 = keras.layers.BatchNormalization() else: self.downsample = downsample def call(self, x, training=True): residual = x if self.downsample: residual = self.dconv1(residual) residual = self.dbn1(residual, training=training) x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x += residual x = tf.nn.relu(x) return x
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ResNet Architecture.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf keras = tf.keras class Resnet18(keras.Model): """ResNet-18 (V1).""" def __init__(self, feature_dims): super(Resnet18, self).__init__() self.conv1 = keras.layers.Conv2D( 64, 7, strides=2, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.relu1 = keras.layers.ReLU() self.maxpool = keras.layers.MaxPooling2D(3, strides=2, padding='same') layers = [2, 2, 2, 2] self.layer1 = ResLayer(BasicBlock, 64, 64, layers[0]) self.layer2 = ResLayer(BasicBlock, 64, 128, layers[1], stride=2) self.layer3 = ResLayer(BasicBlock, 128, 256, layers[2], stride=2) self.layer4 = ResLayer(BasicBlock, 256, 512, layers[3], stride=2) self.fc = keras.layers.Dense(feature_dims, activation=None) def call(self, x, training=False): x = self.conv1(x) x = self.bn1(x, training=training) x = self.relu1(x) x = self.maxpool(x) x = self.layer1(x, training=training) x = self.layer2(x, training=training) x = self.layer3(x, training=training) x = self.layer4(x, training=training) x = tf.reduce_mean(x, axis=(1, 2)) x = self.fc(x) return x class ResLayer(keras.Model): """Residual Layer.""" def __init__(self, block, inplanes, planes, blocks, stride=1): super(ResLayer, self).__init__() if stride != 1 or inplanes != planes: downsample = True else: downsample = False self.conv_layers = [] self.conv_layers.append(block(planes, stride, downsample=downsample)) for unused_i in range(1, blocks): self.conv_layers.append(block(planes)) def call(self, x, training=True): for layer in self.conv_layers: x = layer(x, training=training) return x class BasicBlock(keras.Model): """Building block of resnet.""" def __init__(self, planes, stride=1, downsample=False): super(BasicBlock, self).__init__() self.conv1 = keras.layers.Conv2D( planes, 3, strides=stride, padding='same', use_bias=False) self.bn1 = keras.layers.BatchNormalization() self.conv2 = keras.layers.Conv2D(planes, 3, padding='same', use_bias=False) self.bn2 = keras.layers.BatchNormalization() if downsample: self.downsample = downsample self.dconv1 = keras.layers.Conv2D( planes, 1, strides=stride, padding='same', use_bias=False) self.dbn1 = keras.layers.BatchNormalization() else: self.downsample = downsample def call(self, x, training=True): residual = x if self.downsample: residual = self.dconv1(residual) residual = self.dbn1(residual, training=training) x = self.conv1(x) x = self.bn1(x, training=training) x = tf.nn.relu(x) x = self.conv2(x) x = self.bn2(x, training=training) x += residual x = tf.nn.relu(x) return x
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/notebooks/mesh_viewer.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper class for viewing 3D meshes in Colab demos. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow_graphics.notebooks import threejs_visualization SEGMENTATION_COLORMAP = np.array( ((165, 242, 12), (89, 12, 89), (165, 89, 165), (242, 242, 165), (242, 165, 12), (89, 12, 12), (165, 12, 12), (165, 89, 242), (12, 12, 165), (165, 12, 89), (12, 89, 89), (165, 165, 89), (89, 242, 12), (12, 89, 165), (242, 242, 89), (165, 165, 165)), dtype=np.float32) / 255.0 class Viewer(object): """A ThreeJS based viewer class for viewing 3D meshes.""" def _mesh_from_data(self, data): """Creates a dictionary of ThreeJS mesh objects from numpy data.""" if 'vertices' not in data or 'faces' not in data: raise ValueError('Mesh Data must contain vertices and faces') vertices = np.asarray(data['vertices']) faces = np.asarray(data['faces']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.NoColors, 'side': self.context.THREE.DoubleSide, }) mesh = {'vertices': vertices, 'faces': faces} if 'vertex_colors' in data: mesh['vertex_colors'] = np.asarray(data['vertex_colors']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.VertexColors, 'side': self.context.THREE.DoubleSide, }) mesh['material'] = material return mesh def __init__(self, source_mesh_data): context = threejs_visualization.build_context() self.context = context light1 = context.THREE.PointLight.new_object(0x808080) light1.position.set(10., 10., 10.) light2 = context.THREE.AmbientLight.new_object(0x808080) lights = (light1, light2) camera = threejs_visualization.build_perspective_camera( field_of_view=30, position=(0.0, 0.0, 4.0)) mesh = self._mesh_from_data(source_mesh_data) geometries = threejs_visualization.triangular_mesh_renderer([mesh], lights=lights, camera=camera, width=400, height=400) self.geometries = geometries
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Helper class for viewing 3D meshes in Colab demos. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow_graphics.notebooks import threejs_visualization SEGMENTATION_COLORMAP = np.array( ((165, 242, 12), (89, 12, 89), (165, 89, 165), (242, 242, 165), (242, 165, 12), (89, 12, 12), (165, 12, 12), (165, 89, 242), (12, 12, 165), (165, 12, 89), (12, 89, 89), (165, 165, 89), (89, 242, 12), (12, 89, 165), (242, 242, 89), (165, 165, 165)), dtype=np.float32) / 255.0 class Viewer(object): """A ThreeJS based viewer class for viewing 3D meshes.""" def _mesh_from_data(self, data): """Creates a dictionary of ThreeJS mesh objects from numpy data.""" if 'vertices' not in data or 'faces' not in data: raise ValueError('Mesh Data must contain vertices and faces') vertices = np.asarray(data['vertices']) faces = np.asarray(data['faces']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.NoColors, 'side': self.context.THREE.DoubleSide, }) mesh = {'vertices': vertices, 'faces': faces} if 'vertex_colors' in data: mesh['vertex_colors'] = np.asarray(data['vertex_colors']) material = self.context.THREE.MeshLambertMaterial.new_object({ 'color': 0xfffacd, 'vertexColors': self.context.THREE.VertexColors, 'side': self.context.THREE.DoubleSide, }) mesh['material'] = material return mesh def __init__(self, source_mesh_data): context = threejs_visualization.build_context() self.context = context light1 = context.THREE.PointLight.new_object(0x808080) light1.position.set(10., 10., 10.) light2 = context.THREE.AmbientLight.new_object(0x808080) lights = (light1, light2) camera = threejs_visualization.build_perspective_camera( field_of_view=30, position=(0.0, 0.0, 4.0)) mesh = self._mesh_from_data(source_mesh_data) geometries = threejs_visualization.triangular_mesh_renderer([mesh], lights=lights, camera=camera, width=400, height=400) self.geometries = geometries
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/light/tests/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/datasets/features/trimesh_feature.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Triangle mesh feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six import tensorflow.compat.v2 as tf from tensorflow_datasets import features from tensorflow_graphics.io import triangle_mesh class TriangleMesh(features.FeaturesDict): """`FeatureConnector` for triangle meshes. During `_generate_examples`, the feature connector accepts as input any of: * `str`: path to a {obj,stl,ply,glb} triangle mesh. * `trimesh.Trimesh`: A triangle mesh object. * `trimesh.Scene`: A scene object containing multiple TriangleMesh objects. * `dict:` A dictionary containing the vertices and faces of the mesh (see output format below). Output: A dictionary containing: # TODO(b/156112246): Add additional attributes (vertex normals, colors, # texture coordinates). * 'vertices': A `float32` tensor with shape `[N, 3]` denoting the vertex coordinates, where N is the number of vertices in the mesh. * 'faces': An `int64` tensor with shape `[F, 3]` denoting the face vertex indices, where F is the number of faces in the mesh. Note: In case the input specifies a Scene (with multiple meshes), the output will be a single TriangleMesh which combines all the triangle meshes in the scene. """ def __init__(self): super(TriangleMesh, self).__init__({ 'vertices': features.Tensor(shape=(None, 3), dtype=tf.float32), 'faces': features.Tensor(shape=(None, 3), dtype=tf.uint64), }) def encode_example(self, path_or_trianglemesh): """Convert the given triangle mesh into a dict convertible to tf example.""" if isinstance(path_or_trianglemesh, six.string_types): # The parameter is a path. with tf.io.gfile.GFile(path_or_trianglemesh, 'rb') as tmesh_file: features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(tmesh_file)) elif hasattr(path_or_trianglemesh, 'read') and hasattr( path_or_trianglemesh, 'name') and hasattr(path_or_trianglemesh, 'seek'): # The parameter is a file object. path_or_trianglemesh.seek(0) # reset features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(path_or_trianglemesh)) elif isinstance(path_or_trianglemesh, dict): # The parameter is already a Trimesh dictionary. features_dict = path_or_trianglemesh else: # The parameter is a Trimesh or a Scene. features_dict = self._convert_to_trimesh_feature(path_or_trianglemesh) return super(TriangleMesh, self).encode_example(features_dict) def _convert_to_trimesh_feature(self, obj): if isinstance(obj, triangle_mesh.Trimesh): vertices = np.array(obj.vertices) faces = np.array(obj.faces, dtype=np.uint64) elif isinstance(obj, triangle_mesh.Scene): # Concatenate all the vertices and faces of the triangle meshes in the # scene. # TODO(b/156117488): Change to a different merging algorithm to avoid # duplicated vertices. vertices_list = [ np.array(mesh.vertices) for mesh in obj.geometry.values() ] faces_list = np.array([ np.array(mesh.faces, dtype=np.uint64) for mesh in obj.geometry.values() ]) faces_offset = np.cumsum( [vertices.shape[0] for vertices in vertices_list], dtype=np.uint64) faces_list[1:] += faces_offset[:-1] vertices = np.concatenate(vertices_list, axis=0) faces = np.concatenate(faces_list, axis=0) else: raise ValueError('obj should be either a Trimesh or a Scene') return { 'vertices': vertices.astype(np.float32), 'faces': faces, } @classmethod def from_json_content(cls, value) -> 'TriangleMesh': return cls() def to_json_content(self): return {}
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Triangle mesh feature.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import six import tensorflow.compat.v2 as tf from tensorflow_datasets import features from tensorflow_graphics.io import triangle_mesh class TriangleMesh(features.FeaturesDict): """`FeatureConnector` for triangle meshes. During `_generate_examples`, the feature connector accepts as input any of: * `str`: path to a {obj,stl,ply,glb} triangle mesh. * `trimesh.Trimesh`: A triangle mesh object. * `trimesh.Scene`: A scene object containing multiple TriangleMesh objects. * `dict:` A dictionary containing the vertices and faces of the mesh (see output format below). Output: A dictionary containing: # TODO(b/156112246): Add additional attributes (vertex normals, colors, # texture coordinates). * 'vertices': A `float32` tensor with shape `[N, 3]` denoting the vertex coordinates, where N is the number of vertices in the mesh. * 'faces': An `int64` tensor with shape `[F, 3]` denoting the face vertex indices, where F is the number of faces in the mesh. Note: In case the input specifies a Scene (with multiple meshes), the output will be a single TriangleMesh which combines all the triangle meshes in the scene. """ def __init__(self): super(TriangleMesh, self).__init__({ 'vertices': features.Tensor(shape=(None, 3), dtype=tf.float32), 'faces': features.Tensor(shape=(None, 3), dtype=tf.uint64), }) def encode_example(self, path_or_trianglemesh): """Convert the given triangle mesh into a dict convertible to tf example.""" if isinstance(path_or_trianglemesh, six.string_types): # The parameter is a path. with tf.io.gfile.GFile(path_or_trianglemesh, 'rb') as tmesh_file: features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(tmesh_file)) elif hasattr(path_or_trianglemesh, 'read') and hasattr( path_or_trianglemesh, 'name') and hasattr(path_or_trianglemesh, 'seek'): # The parameter is a file object. path_or_trianglemesh.seek(0) # reset features_dict = self._convert_to_trimesh_feature( triangle_mesh.load(path_or_trianglemesh)) elif isinstance(path_or_trianglemesh, dict): # The parameter is already a Trimesh dictionary. features_dict = path_or_trianglemesh else: # The parameter is a Trimesh or a Scene. features_dict = self._convert_to_trimesh_feature(path_or_trianglemesh) return super(TriangleMesh, self).encode_example(features_dict) def _convert_to_trimesh_feature(self, obj): if isinstance(obj, triangle_mesh.Trimesh): vertices = np.array(obj.vertices) faces = np.array(obj.faces, dtype=np.uint64) elif isinstance(obj, triangle_mesh.Scene): # Concatenate all the vertices and faces of the triangle meshes in the # scene. # TODO(b/156117488): Change to a different merging algorithm to avoid # duplicated vertices. vertices_list = [ np.array(mesh.vertices) for mesh in obj.geometry.values() ] faces_list = np.array([ np.array(mesh.faces, dtype=np.uint64) for mesh in obj.geometry.values() ]) faces_offset = np.cumsum( [vertices.shape[0] for vertices in vertices_list], dtype=np.uint64) faces_list[1:] += faces_offset[:-1] vertices = np.concatenate(vertices_list, axis=0) faces = np.concatenate(faces_list, axis=0) else: raise ValueError('obj should be either a Trimesh or a Scene') return { 'vertices': vertices.astype(np.float32), 'faces': faces, } @classmethod def from_json_content(cls, value) -> 'TriangleMesh': return cls() def to_json_content(self): return {}
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/projects/nasa/lib/datasets.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from os import path import tensorflow.compat.v1 as tf tf.disable_eager_execution() def get_dataset(split, hparams): return dataset_dict[hparams.dataset](split, hparams) def amass(split, hparams): """Construct an AMASS data loader.""" def _input_fn(params): # pylint: disable=unused-argument # Dataset constants. n_bbox = 100000 n_surf = 100000 n_points = n_bbox + n_surf n_vert = 6890 n_frames = 1 # Parse parameters for global configurations. n_dims = hparams.n_dims data_dir = hparams.data_dir sample_bbox = hparams.sample_bbox sample_surf = hparams.sample_surf batch_size = hparams.batch_size subject = hparams.subject motion = hparams.motion n_parts = hparams.n_parts def _parse_tfrecord(serialized_example): fs = tf.parse_single_example( serialized_example, features={ 'point': tf.FixedLenFeature([n_frames * n_points * n_dims], tf.float32), 'label': tf.FixedLenFeature([n_frames * n_points * 1], tf.float32), 'vert': tf.FixedLenFeature([n_frames * n_vert * n_dims], tf.float32), 'weight': tf.FixedLenFeature([n_frames * n_vert * n_parts], tf.float32), 'transform': tf.FixedLenFeature( [n_frames * n_parts * (n_dims + 1) * (n_dims + 1)], tf.float32), 'joint': tf.FixedLenFeature([n_frames * n_parts * n_dims], tf.float32), 'name': tf.FixedLenFeature([], tf.string), }) fs['point'] = tf.reshape(fs['point'], [n_frames, n_points, n_dims]) fs['label'] = tf.reshape(fs['label'], [n_frames, n_points, 1]) fs['vert'] = tf.reshape(fs['vert'], [n_frames, n_vert, n_dims]) fs['weight'] = tf.reshape(fs['weight'], [n_frames, n_vert, n_parts]) fs['transform'] = tf.reshape(fs['transform'], [n_frames, n_parts, n_dims + 1, n_dims + 1]) fs['joint'] = tf.reshape(fs['joint'], [n_frames, n_parts, n_dims]) return fs def _sample_frame_points(fs): feature = {} for k, v in fs.items(): feature[k] = v points = feature['point'][0] labels = feature['label'][0] sample_points = [] sample_labels = [] if sample_bbox > 0: indices_bbox = tf.random.uniform([sample_bbox], minval=0, maxval=n_bbox, dtype=tf.int32) bbox_samples = tf.gather(points[:n_bbox], indices_bbox, axis=0) bbox_labels = tf.gather(labels[:n_bbox], indices_bbox, axis=0) sample_points.append(bbox_samples) sample_labels.append(bbox_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=n_surf, dtype=tf.int32) surf_samples = tf.gather( points[n_bbox:n_bbox + n_surf], indices_surf, axis=0) surf_labels = tf.gather( labels[n_bbox:n_bbox + n_surf], indices_surf, axis=0) sample_points.append(surf_samples) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.concat(sample_labels, axis=0) feature['point'] = tf.expand_dims(points, axis=0) feature['label'] = tf.expand_dims(point_labels, axis=0) return feature def _sample_eval_points(fs): feature = {} feature['transform'] = fs['transform'] feature['points'] = fs['point'][:, :n_bbox] feature['labels'] = fs['label'][:, :n_bbox] feature['name'] = fs['name'] feature['vert'] = fs['vert'] feature['weight'] = fs['weight'] feature['joint'] = fs['joint'] return feature data_split = 'train' all_motions = list(x for x in range(10)) if split == 'train': file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, x)) for x in all_motions if x != motion ] else: file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, motion)) ] data_files = tf.gfile.Glob(file_pattern) if not data_files: raise IOError('{} did not match any files'.format(file_pattern)) filenames = tf.data.Dataset.list_files(file_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map( _parse_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache() if split == 'train': data = data.map( _sample_frame_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) else: data = data.map( _sample_eval_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == 'train': data = data.shuffle(int(batch_size * 2.5)).repeat(-1) else: batch_size = 1 return data.batch( batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE) return _input_fn dataset_dict = { 'amass': amass, }
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Dataset implementations.""" from os import path import tensorflow.compat.v1 as tf tf.disable_eager_execution() def get_dataset(split, hparams): return dataset_dict[hparams.dataset](split, hparams) def amass(split, hparams): """Construct an AMASS data loader.""" def _input_fn(params): # pylint: disable=unused-argument # Dataset constants. n_bbox = 100000 n_surf = 100000 n_points = n_bbox + n_surf n_vert = 6890 n_frames = 1 # Parse parameters for global configurations. n_dims = hparams.n_dims data_dir = hparams.data_dir sample_bbox = hparams.sample_bbox sample_surf = hparams.sample_surf batch_size = hparams.batch_size subject = hparams.subject motion = hparams.motion n_parts = hparams.n_parts def _parse_tfrecord(serialized_example): fs = tf.parse_single_example( serialized_example, features={ 'point': tf.FixedLenFeature([n_frames * n_points * n_dims], tf.float32), 'label': tf.FixedLenFeature([n_frames * n_points * 1], tf.float32), 'vert': tf.FixedLenFeature([n_frames * n_vert * n_dims], tf.float32), 'weight': tf.FixedLenFeature([n_frames * n_vert * n_parts], tf.float32), 'transform': tf.FixedLenFeature( [n_frames * n_parts * (n_dims + 1) * (n_dims + 1)], tf.float32), 'joint': tf.FixedLenFeature([n_frames * n_parts * n_dims], tf.float32), 'name': tf.FixedLenFeature([], tf.string), }) fs['point'] = tf.reshape(fs['point'], [n_frames, n_points, n_dims]) fs['label'] = tf.reshape(fs['label'], [n_frames, n_points, 1]) fs['vert'] = tf.reshape(fs['vert'], [n_frames, n_vert, n_dims]) fs['weight'] = tf.reshape(fs['weight'], [n_frames, n_vert, n_parts]) fs['transform'] = tf.reshape(fs['transform'], [n_frames, n_parts, n_dims + 1, n_dims + 1]) fs['joint'] = tf.reshape(fs['joint'], [n_frames, n_parts, n_dims]) return fs def _sample_frame_points(fs): feature = {} for k, v in fs.items(): feature[k] = v points = feature['point'][0] labels = feature['label'][0] sample_points = [] sample_labels = [] if sample_bbox > 0: indices_bbox = tf.random.uniform([sample_bbox], minval=0, maxval=n_bbox, dtype=tf.int32) bbox_samples = tf.gather(points[:n_bbox], indices_bbox, axis=0) bbox_labels = tf.gather(labels[:n_bbox], indices_bbox, axis=0) sample_points.append(bbox_samples) sample_labels.append(bbox_labels) if sample_surf > 0: indices_surf = tf.random.uniform([sample_surf], minval=0, maxval=n_surf, dtype=tf.int32) surf_samples = tf.gather( points[n_bbox:n_bbox + n_surf], indices_surf, axis=0) surf_labels = tf.gather( labels[n_bbox:n_bbox + n_surf], indices_surf, axis=0) sample_points.append(surf_samples) sample_labels.append(surf_labels) points = tf.concat(sample_points, axis=0) point_labels = tf.concat(sample_labels, axis=0) feature['point'] = tf.expand_dims(points, axis=0) feature['label'] = tf.expand_dims(point_labels, axis=0) return feature def _sample_eval_points(fs): feature = {} feature['transform'] = fs['transform'] feature['points'] = fs['point'][:, :n_bbox] feature['labels'] = fs['label'][:, :n_bbox] feature['name'] = fs['name'] feature['vert'] = fs['vert'] feature['weight'] = fs['weight'] feature['joint'] = fs['joint'] return feature data_split = 'train' all_motions = list(x for x in range(10)) if split == 'train': file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, x)) for x in all_motions if x != motion ] else: file_pattern = [ path.join(data_dir, '{0}-{1:02d}-{2:02d}-*'.format(data_split, subject, motion)) ] data_files = tf.gfile.Glob(file_pattern) if not data_files: raise IOError('{} did not match any files'.format(file_pattern)) filenames = tf.data.Dataset.list_files(file_pattern, shuffle=True) data = filenames.interleave( lambda x: tf.data.TFRecordDataset([x]), num_parallel_calls=tf.data.experimental.AUTOTUNE) data = data.map( _parse_tfrecord, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache() if split == 'train': data = data.map( _sample_frame_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) else: data = data.map( _sample_eval_points, num_parallel_calls=tf.data.experimental.AUTOTUNE) if split == 'train': data = data.shuffle(int(batch_size * 2.5)).repeat(-1) else: batch_size = 1 return data.batch( batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE) return _input_fn dataset_dict = { 'amass': amass, }
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/reflectance/phong.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to Eric P. Lafortune, and Yves D. Willems. "Using the modified phong reflectance model for physically based rendering". 1994. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" return (shininess + 2.0) / (2.0 * math.pi) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn specular model. name: A name for this op. Defaults to "phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) perfect_reflection_direction = vector.reflect(direction_incoming_light, surface_normal) perfect_reflection_direction = tf.math.l2_normalize( perfect_reflection_direction, axis=-1) cos_alpha = vector.dot( perfect_reflection_direction, direction_outgoing_light, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) phong_model = tf.broadcast_to(phong_model, common_shape) return tf.compat.v1.where(condition, phong_model, tf.zeros_like(phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to Eric P. Lafortune, and Yves D. Willems. "Using the modified phong reflectance model for physically based rendering". 1994. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" return (shininess + 2.0) / (2.0 * math.pi) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn specular model. name: A name for this op. Defaults to "phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) perfect_reflection_direction = vector.reflect(direction_incoming_light, surface_normal) perfect_reflection_direction = tf.math.l2_normalize( perfect_reflection_direction, axis=-1) cos_alpha = vector.dot( perfect_reflection_direction, direction_outgoing_light, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) phong_model = tf.broadcast_to(phong_model, common_shape) return tf.compat.v1.where(condition, phong_model, tf.zeros_like(phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/rendering/reflectance/blinn_phong.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module implements the Blinn-Phong specular reflectance. For a derivation of the normalization factor ensuring energy conservation, we refer the interested reader to: Fabian Giesen. "Derivation of Phong and Blinn-Phong BRDF normalization factors". 2009 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import tensorflow as tf from tensorflow_graphics.math import vector from tensorflow_graphics.util import asserts from tensorflow_graphics.util import export_api from tensorflow_graphics.util import safe_ops from tensorflow_graphics.util import shape def _brdf_normalization_factor(shininess): """Returns the normalization factor needed to ensure energy conservation.""" numerator = (shininess + 2.0) * (shininess + 4.0) denominator = 8.0 * math.pi * ( tf.pow(tf.constant(2.0, dtype=shininess.dtype), -shininess / 2.0) + shininess) return safe_ops.safe_signed_div(numerator, denominator) def brdf(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo, brdf_normalization=True, name=None): """Evaluates the specular brdf of the Blinn-Phong model. Note: In the following, A1 to An are optional batch dimensions, which must be broadcast compatible. Note: The gradient of this function is not smooth when the dot product of the normal with any light is 0.0. Args: direction_incoming_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized incoming light vector. direction_outgoing_light: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized outgoing light vector. surface_normal: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents a normalized surface normal. shininess: A tensor of shape `[A1, ..., An, 1]`, where the last dimension represents a non-negative shininess coefficient. albedo: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents albedo with values in [0,1]. brdf_normalization: A `bool` indicating whether normalization should be applied to enforce the energy conservation property of BRDFs. Note that `brdf_normalization` must be set to False in order to use the original Blinn-Phong specular model. name: A name for this op. Defaults to "blinn_phong_brdf". Returns: A tensor of shape `[A1, ..., An, 3]`, where the last dimension represents the amount of light reflected in the outgoing light direction. Raises: ValueError: if the shape of `direction_incoming_light`, `direction_outgoing_light`, `surface_normal`, `shininess` or `albedo` is not supported. InvalidArgumentError: if not all of shininess values are non-negative, or if at least one element of `albedo` is outside of [0,1]. """ with tf.compat.v1.name_scope(name, "blinn_phong_brdf", [ direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo ]): direction_incoming_light = tf.convert_to_tensor( value=direction_incoming_light) direction_outgoing_light = tf.convert_to_tensor( value=direction_outgoing_light) surface_normal = tf.convert_to_tensor(value=surface_normal) shininess = tf.convert_to_tensor(value=shininess) albedo = tf.convert_to_tensor(value=albedo) shape.check_static( tensor=direction_incoming_light, tensor_name="direction_incoming_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=direction_outgoing_light, tensor_name="direction_outgoing_light", has_dim_equals=(-1, 3)) shape.check_static( tensor=surface_normal, tensor_name="surface_normal", has_dim_equals=(-1, 3)) shape.check_static( tensor=shininess, tensor_name="shininess", has_dim_equals=(-1, 1)) shape.check_static( tensor=albedo, tensor_name="albedo", has_dim_equals=(-1, 3)) shape.compare_batch_dimensions( tensors=(direction_incoming_light, direction_outgoing_light, surface_normal, shininess, albedo), tensor_names=("direction_incoming_light", "direction_outgoing_light", "surface_normal", "shininess", "albedo"), last_axes=-2, broadcast_compatible=True) direction_incoming_light = asserts.assert_normalized( direction_incoming_light) direction_outgoing_light = asserts.assert_normalized( direction_outgoing_light) surface_normal = asserts.assert_normalized(surface_normal) albedo = asserts.assert_all_in_range(albedo, 0.0, 1.0, open_bounds=False) shininess = asserts.assert_all_above(shininess, 0.0, open_bound=False) # Checks whether the incoming or outgoing light point behind the surface. dot_incoming_light_surface_normal = vector.dot(-direction_incoming_light, surface_normal) dot_outgoing_light_surface_normal = vector.dot(direction_outgoing_light, surface_normal) min_dot = tf.minimum(dot_incoming_light_surface_normal, dot_outgoing_light_surface_normal) difference_outgoing_incoming = ( direction_outgoing_light - direction_incoming_light) difference_outgoing_incoming = tf.math.l2_normalize( difference_outgoing_incoming, axis=-1) cos_alpha = vector.dot( surface_normal, difference_outgoing_incoming, axis=-1) cos_alpha = tf.maximum(cos_alpha, tf.zeros_like(cos_alpha)) blinn_phong_model = albedo * tf.pow(cos_alpha, shininess) if brdf_normalization: blinn_phong_model *= _brdf_normalization_factor(shininess) common_shape = shape.get_broadcasted_shape(min_dot.shape, blinn_phong_model.shape) d_val = lambda dim: 1 if dim is None else tf.compat.v1.dimension_value(dim) common_shape = [d_val(dim) for dim in common_shape] condition = tf.broadcast_to(tf.greater_equal(min_dot, 0.0), common_shape) blinn_phong_model = tf.broadcast_to(blinn_phong_model, common_shape) return tf.compat.v1.where(condition, blinn_phong_model, tf.zeros_like(blinn_phong_model)) # API contains all public functions and classes. __all__ = export_api.get_functions_and_classes()
-1
tensorflow/graphics
489
Enforce `Framebuffer` to accept only tensors with single batch dimension.
Enforce `Framebuffer` to accept only tensors with single batch dimension.
copybara-service[bot]
"2021-02-03T21:06:22Z"
"2021-02-12T23:59:48Z"
3a4f1952ed967fb884dc031eeda6dac3fbefbe52
b7a2bf260d6fcf924fddcbb6dba36c72ece66990
Enforce `Framebuffer` to accept only tensors with single batch dimension.. Enforce `Framebuffer` to accept only tensors with single batch dimension.
./tensorflow_graphics/datasets/shapenet/__init__.py
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """`tensorflow_graphics.datasets.shapenet` module.""" from tensorflow_graphics.datasets.shapenet.shapenet import Shapenet __all__ = [ "Shapenet", ]
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """`tensorflow_graphics.datasets.shapenet` module.""" from tensorflow_graphics.datasets.shapenet.shapenet import Shapenet __all__ = [ "Shapenet", ]
-1