Repository: YeeU/InverseRenderNet Branch: master Commit: af96b366ffda Files: 40 Total size: 71.8 KB Directory structure: gitextract_qj_wnxju/ ├── Data/ │ ├── 037/ │ │ ├── 037_0000.pk │ │ ├── 037_0001.pk │ │ ├── 037_0002.pk │ │ ├── 037_0003.pk │ │ ├── 037_0004.pk │ │ ├── 037_0005.pk │ │ ├── 037_0006.pk │ │ ├── 037_0007.pk │ │ ├── 037_0008.pk │ │ └── 037_0009.pk │ └── 038/ │ ├── 038_0000.pk │ ├── 038_0001.pk │ ├── 038_0002.pk │ ├── 038_0003.pk │ ├── 038_0004.pk │ ├── 038_0005.pk │ ├── 038_0006.pk │ ├── 038_0007.pk │ ├── 038_0008.pk │ └── 038_0009.pk ├── LICENSE ├── README.md ├── iiw_test_ids.npy ├── illu_pca/ │ ├── mean.npy │ ├── pcaMean.npy │ ├── pcaVariance.npy │ └── pcaVector.npy ├── model/ │ ├── SfMNet.py │ ├── dataloader.py │ ├── lambSH_layer.py │ ├── loss_layer.py │ ├── pred_illuDecomp_layer.py │ ├── reproj_layer.py │ └── sup_illuDecomp_layer.py ├── pre_train_model/ │ └── .keep ├── test_demo.py ├── test_iiw.py ├── train.py └── utils/ ├── render_sphere_nm.py └── whdr.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ # InverseRenderNet: Learning single image inverse rendering ***!! Check out our new work InverseRenderNet++ [paper](https://arxiv.org/abs/2102.06591) and [code](https://github.com/YeeU/InverseRenderNet_v2), which improves the inverse rendering results and shadow handling.*** This is the implementation of the paper "InverseRenderNet: Learning single image inverse rendering". The model is implemented in tensorflow. If you use our code, please cite the following paper: @inproceedings{yu19inverserendernet, title={InverseRenderNet: Learning single image inverse rendering}, author={Yu, Ye and Smith, William AP}, booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, year={2019} } ## Evaluation #### Dependencies To run our evaluation code, please create your environment based on following dependencies: tensorflow 1.12.0 python 3.6 skimage cv2 numpy #### Pretrained model * Download our pretrained model from: [Link](https://drive.google.com/uc?export=download&id=1VKeByvprmWWXSig-7-fxfXs3KA-HG_-P) * Unzip the downloaded file * Make sure the model files are placed in a folder named "irn_model" #### Test on demo image You can perform inverse rendering on random RGB image by our pretrained model. To run the demo code, you need to specify the path to pretrained model, path to RGB image and corresponding mask which masked out sky in the image. The mask can be generated by PSPNet, which you can find on https://github.com/hszhao/PSPNet. Finally inverse rendering results will be saved to the output folder named by your argument. ```bash python3 test_demo.py --model /PATH/TO/irn_model --image demo.jpg --mask demo_mask.jpg --output test_results ``` #### Test on IIW * IIW dataset should be downloaded firstly from http://opensurfaces.cs.cornell.edu/publications/intrinsic/#download * Run testing code where you need to specify the path to model and IIW data: ```bash python3 test_iiw.py --model /PATH/TO/irn_model --iiw /PATH/TO/iiw-dataset ``` ## Training #### Train from scratch The training for InverseRenderNet contains two stages: pre-train and self-train. * To begin with pre-train stage, you need to use training command specifying option `-m` to `pre-train`. * After finishing pre-train stage, you can run self-train by specifying option `-m` to `self-train`. In addition, you can control the size of batch in training, and the path to training data should be specified. An example for training command: ```bash python3 train.py -n 2 -p Data -m pre-train ``` #### Data for training To directly use our code for training, you need to pre-process the training data to match the data format as shown in examples in `Data` folder. In particular, we pre-process the data before training, such that five images with great overlaps are bundled up into one mini-batch, and images are resized and cropped to a shape of 200 * 200 pixels. Along with input images associated depth maps, camera parameters, sky masks and normal maps are stored in the same mini-batch. For efficiency, every mini-batch containing all training elements for 5 involved images are saved as a pickle file. While training the data feeding thread directly load each mini-batch from corresponding pickle file. ================================================ FILE: model/SfMNet.py ================================================ import importlib import tensorflow as tf import numpy as np import tensorflow.contrib.layers as layers def SfMNet(inputs, height, width, name='', n_layers=12, n_pools=2, is_training=True, depth_base=64): conv_layers = np.int32(n_layers/2) -1 deconv_layers = np.int32(n_layers/2) # number of layers before perform pooling nlayers_befPool = np.int32(np.ceil((conv_layers-1)/n_pools)-1) max_depth = 512 if depth_base*2**n_pools < max_depth: tail = conv_layers - nlayers_befPool*n_pools tail_deconv = deconv_layers - nlayers_befPool*n_pools else: maxNum_pool = np.log2(max_depth / depth_base) tail = np.int32(conv_layers - nlayers_befPool * maxNum_pool) tail_deconv = np.int32(deconv_layers - nlayers_befPool * maxNum_pool) f_in_conv = [3] + [np.int32(depth_base*2**(np.ceil(i/nlayers_befPool)-1)) for i in range(1, conv_layers-tail+1)] + [np.int32(depth_base*2**maxNum_pool) for i in range(conv_layers-tail+1, conv_layers+1)] f_out_conv = [64] + [np.int32(depth_base*2**(np.floor(i/nlayers_befPool))) for i in range(1, conv_layers-tail+1)] + [np.int32(depth_base*2**maxNum_pool) for i in range(conv_layers-tail+1, conv_layers+1)] f_in_deconv = f_out_conv[:0:-1] + [64] f_out_amDeconv = f_in_conv[:0:-1] + [3] f_out_MaskDeconv = f_in_conv[:0:-1] + [2] f_out_nmDeconv = f_in_conv[:0:-1] + [2] batch_norm_params = {'decay':0.9, 'center':True, 'scale':True, 'epsilon':1e-4, 'param_initializers':{'beta_initializer':tf.zeros_initializer(),'gamma_initializer':tf.ones_initializer(),'moving_variance_initializer':tf.ones_initializer(),'moving_average_initializer':tf.zeros_initializer()}, 'param_regularizers':{'beta_regularizer':None,'gamma_regularizer':layers.l2_regularizer(scale=1e-5)},'is_training':is_training,'trainable':is_training} ### contractive conv_layer block conv_out = inputs conv_out_list = [] for i,f_in,f_out in zip(range(1,conv_layers+2),f_in_conv,f_out_conv): scope = name+'conv'+str(i) if np.mod(i-1,nlayers_befPool)==0 and i<=n_pools*nlayers_befPool+1 and i != 1: conv_out_list.append(conv_out) conv_out = layers.conv2d(conv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope, trainable=is_training) conv_out = tf.nn.max_pool(conv_out, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME') else: conv_out = layers.conv2d(conv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope, trainable=is_training) ### expanding deconv_layer block succeeding conv_layer block am_deconv_out = conv_out for i,f_in,f_out in zip(range(1,deconv_layers+1),f_in_deconv,f_out_amDeconv): scope = name+'am/am_deconv'+str(i) # expand resolution every after nlayers_befPool deconv_layer if np.mod(i,nlayers_befPool)==0 and i<=n_pools*nlayers_befPool: with tf.variable_scope(scope): W = tf.get_variable(regularizer=layers.l2_regularizer(scale=1e-5),initializer=get_bilinear_filter([3,3,f_out,f_in],2),shape=[3,3,f_out,f_in],name='filter', trainable=is_training) # import ipdb; ipdb.set_trace() # attach previous convolutional output to upsampling/deconvolutional output tmp = conv_out_list[-np.int32(i/nlayers_befPool)] output_shape = tf.shape(tmp) am_deconv_out = tf.nn.conv2d_transpose(am_deconv_out,filter=W,output_shape=output_shape,strides=[1,2,2,1],padding='SAME') am_deconv_out = layers.batch_norm(scope=scope,activation_fn=tf.nn.relu,inputs=am_deconv_out,decay=0.9, center=True, scale=True, param_initializers={'beta_initializer':tf.zeros_initializer(),'gamma_initializer':tf.ones_initializer(),'moving_variance_initializer':tf.ones_initializer(),'moving_average_initializer':tf.zeros_initializer()}, param_regularizers={'beta_regularizer':None,'gamma_regularizer':layers.l2_regularizer(scale=1e-5)},is_training=is_training,trainable=is_training) tmp = layers.conv2d(tmp,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope,trainable=is_training) am_deconv_out = tmp + am_deconv_out elif i==deconv_layers: am_deconv_out = layers.conv2d(am_deconv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=None,activation_fn=None,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),scope=scope,trainable=is_training) else: am_deconv_out = layers.conv2d(am_deconv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope,trainable=is_training) ### deconvolution net for nm estimates nm_deconv_out = conv_out for i,f_in,f_out in zip(range(1,deconv_layers+1),f_in_deconv,f_out_nmDeconv): scope = name+'nm/nm'+str(i) # expand resolution every after nlayers_befPool deconv_layer if np.mod(i,nlayers_befPool)==0 and i<=n_pools*nlayers_befPool: with tf.variable_scope(scope): W = tf.get_variable(regularizer=layers.l2_regularizer(scale=1e-5),initializer=get_bilinear_filter([3,3,f_out,f_in],2),shape=[3,3,f_out,f_in],name='filter',trainable=is_training) # attach previous convolutional output to upsampling/deconvolutional output tmp = conv_out_list[-np.int32(i/nlayers_befPool)] output_shape = tf.shape(tmp) nm_deconv_out = tf.nn.conv2d_transpose(nm_deconv_out,filter=W,output_shape=output_shape,strides=[1,2,2,1],padding='SAME') nm_deconv_out = layers.batch_norm(scope=scope,activation_fn=tf.nn.relu,inputs=nm_deconv_out,decay=0.9, center=True, scale=True, epsilon=1e-4, param_initializers={'beta_initializer':tf.zeros_initializer(),'gamma_initializer':tf.ones_initializer(),'moving_variance_initializer':tf.ones_initializer(),'moving_average_initializer':tf.zeros_initializer()}, param_regularizers={'beta_regularizer':None,'gamma_regularizer':layers.l2_regularizer(scale=1e-5)},is_training=is_training,trainable=is_training) tmp = layers.conv2d(tmp,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope,trainable=is_training) nm_deconv_out = tmp + nm_deconv_out elif i==deconv_layers: nm_deconv_out = layers.conv2d(nm_deconv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=None,activation_fn=None,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope,trainable=is_training) else: nm_deconv_out = layers.conv2d(nm_deconv_out,num_outputs=f_out,kernel_size=[3,3],stride=[1,1],padding='SAME',normalizer_fn=layers.batch_norm, normalizer_params=batch_norm_params,weights_initializer=tf.random_normal_initializer(mean=0,stddev=np.sqrt(2/9/f_in)),weights_regularizer=layers.l2_regularizer(scale=1e-5),biases_initializer=None,scope=scope,trainable=is_training) return am_deconv_out, nm_deconv_out def get_bilinear_filter(filter_shape, upscale_factor): ##filter_shape is [width, height, num_in_channels, num_out_channels] kernel_size = filter_shape[1] ### Centre location of the filter for which value is calculated if kernel_size % 2 == 1: centre_location = upscale_factor - 1 else: centre_location = upscale_factor - 0.5 x,y = np.meshgrid(np.arange(kernel_size),np.arange(kernel_size)) bilinear = (1 - abs((x - centre_location)/ upscale_factor)) * (1 - abs((y - centre_location)/ upscale_factor)) weights = np.tile(bilinear[:,:,None,None],(1,1,filter_shape[2],filter_shape[3])) return tf.constant_initializer(weights) ================================================ FILE: model/dataloader.py ================================================ import pickle as pk import os import numpy as np import tensorflow as tf import skimage.transform as imgTform import glob from scipy import io def megaDepth_dataPipeline(num_subbatch_input, dir): # import ipdb; ipdb.set_trace() # locate all scenes data_scenes1 = np.array(sorted(glob.glob(os.path.join(dir, '*')))) # scan scenes # sort scenes by number of training images in each scenes_size1 = np.array([len(os.listdir(i)) for i in data_scenes1]) scenes_sorted1 = np.argsort(scenes_size1) # define scenes for training and testing train_scenes = data_scenes1[scenes_sorted1] # load data from each scene # locate each data minibatch in each sorted sc train_scenes_items = [sorted(glob.glob(os.path.join(sc, '*.pk'))) for sc in train_scenes] train_scenes_items = np.concatenate(train_scenes_items, axis=0) train_items = train_scenes_items ### contruct training data pipeline # remove residual data over number of data in one epoch res_train_items = len(train_items) - (len(train_items) % num_subbatch_input) train_items = train_items[:res_train_items] train_data = md_construct_inputPipeline(train_items, flag_shuffle=True, batch_size=num_subbatch_input) # define re-initialisable iterator iterator = tf.data.Iterator.from_structure(train_data.output_types, train_data.output_shapes) next_element = iterator.get_next() # define initialisation for each iterator trainData_init_op = iterator.make_initializer(train_data) return next_element, trainData_init_op, len(train_items) def _read_pk_function(filename): with open(filename, 'rb') as f: batch_data = pk.load(f) input = np.float32(batch_data['input']) dm = batch_data['dm'] nm = np.float32(batch_data['nm']) cam = np.float32(batch_data['cam']) scaleX= batch_data['scaleX'] scaleY = batch_data['scaleY'] mask = np.float32(batch_data['mask']) return input, dm, nm, cam, scaleX, scaleY, mask def md_read_func(filename): input, dm, nm, cam, scaleX, scaleY, mask = tf.py_func(_read_pk_function, [filename], [tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32, tf.float32]) input = tf.data.Dataset.from_tensor_slices(input[None]) dm = tf.data.Dataset.from_tensor_slices(dm[None]) nm = tf.data.Dataset.from_tensor_slices(nm[None]) cam = tf.data.Dataset.from_tensor_slices(cam[None]) scaleX = tf.data.Dataset.from_tensor_slices(scaleX[None]) scaleY = tf.data.Dataset.from_tensor_slices(scaleY[None]) mask = tf.data.Dataset.from_tensor_slices(mask[None]) return tf.data.Dataset.zip((input, dm, nm, cam, scaleX, scaleY, mask)) def md_preprocess_func(input, dm, nm, cam, scaleX, scaleY, mask): input = input/255. nm = nm/127 return input, dm, nm, cam, scaleX, scaleY, mask def md_construct_inputPipeline(items, batch_size, flag_shuffle=True): data = tf.data.Dataset.from_tensor_slices(items) if flag_shuffle: data = data.apply(tf.contrib.data.shuffle_and_repeat(buffer_size=100000)) else: data = data.repeat() data = data.apply(tf.contrib.data.parallel_interleave(md_read_func, cycle_length=batch_size, block_length=1, sloppy=False )) data = data.map(md_preprocess_func, num_parallel_calls=8 ) data = data.batch(batch_size).prefetch(4) return data ================================================ FILE: model/lambSH_layer.py ================================================ import tensorflow as tf # am is the albedo map, which has shape (batch, height, width, 3[rgb]) # nm is the sparse normal map, which has shape (batch, height, width, 3[x,y,z]) # L_SHcoeff contains the SH coefficients for environment illumination, using 2nd order SH. L_SHcoeff has shape (batch, 9, 3[rgb]) def lambSH_layer(am, nm, L_SHcoeffs, gamma): """ i = albedo * irradiance the multiplication is elementwise albedo is given irraidance = n.T * M * n, where n is (x,y,z,1) M is contructed from some precomputed constants and L_SHcoeff, where M contains information about illuminations, clamped cosine and SH basis """ # M is only related with lighting c1 = tf.constant(0.429043,dtype=tf.float32) c2 = tf.constant(0.511664,dtype=tf.float32) c3 = tf.constant(0.743125,dtype=tf.float32) c4 = tf.constant(0.886227,dtype=tf.float32) c5 = tf.constant(0.247708,dtype=tf.float32) # each row have shape (batch, 4, 3) M_row1 = tf.stack([c1*L_SHcoeffs[:,8,:], c1*L_SHcoeffs[:,4,:], c1*L_SHcoeffs[:,7,:], c2*L_SHcoeffs[:,3,:]],axis=1) M_row2 = tf.stack([c1*L_SHcoeffs[:,4,:], -c1*L_SHcoeffs[:,8,:], c1*L_SHcoeffs[:,5,:], c2*L_SHcoeffs[:,1,:]],axis=1) M_row3 = tf.stack([c1*L_SHcoeffs[:,7,:], c1*L_SHcoeffs[:,5,:], c3*L_SHcoeffs[:,6,:], c2*L_SHcoeffs[:,2,:]],axis=1) M_row4 = tf.stack([c2*L_SHcoeffs[:,3,:], c2*L_SHcoeffs[:,1,:], c2*L_SHcoeffs[:,2,:], c4*L_SHcoeffs[:,0,:]-c5*L_SHcoeffs[:,6,:]],axis=1) # M is a 5d tensot with shape (batch,4,4,3[rgb]), the axis 1 and 2 are transposely equivalent M = tf.stack([M_row1,M_row2,M_row3,M_row4], axis=1) # find batch-spatial three dimensional mask of defined normals over nm # mask = tf.logical_not(tf.is_nan(nm[:,:,:,0])) mask = tf.not_equal(tf.reduce_sum(nm,axis=-1),0) # extend Cartesian to homogeneous coords and extend its last for rgb individual multiplication dimension, nm_homo have shape (total_npix, 4) total_npix = tf.shape(nm)[:3] ones = tf.ones(total_npix) nm_homo = tf.concat([nm,tf.expand_dims(ones,axis=-1)], axis=-1) # contruct batch-wise flatten M corresponding with nm_homo, such that multiplication between them is batch-wise M = tf.expand_dims(tf.expand_dims(M,axis=1),axis=1) # expand M for broadcasting, such that M has shape (npix,4,4,3) # expand nm_homo, such that nm_homo has shape (npix,4,1,1) nm_homo = tf.expand_dims(tf.expand_dims(nm_homo,axis=-1),axis=-1) # tmp have shape (npix, 4, 3[rgb]) tmp = tf.reduce_sum(nm_homo*M,axis=-3) # E has shape (npix, 3[rbg]) E = tf.reduce_sum(tmp*nm_homo[:,:,:,:,0,:],axis=-2) # compute intensity by product between irradiance and albedo i = E*am # gamma correction i = tf.clip_by_value(i, 0., 1.) + tf.constant(1e-4) i = tf.pow(i,1./gamma) return i, mask ================================================ FILE: model/loss_layer.py ================================================ # formulate loss function based on supplied ground truth and outputs from network import importlib import tensorflow as tf import numpy as np import os from model import SfMNet, lambSH_layer, pred_illuDecomp_layer, sup_illuDecomp_layer, reproj_layer def loss_formulate(albedos, nm_pred, am_sup, nm_gt, inputs, dms, cams, scale_xs, scale_ys, masks, pair_label, preTrain_flag, am_smt_w_var, reproj_w_var, reg_loss_flag=True): # define gamma nonlinear mapping factor gamma = tf.constant(2.2) albedos = tf.nn.sigmoid(albedos) * masks + tf.constant(1e-4) ### pre-process nm_pred such that in range (-1,1) nm_pred_norm = tf.sqrt(tf.reduce_sum(nm_pred**2, axis=-1, keepdims=True)+tf.constant(1.)) nm_pred_xy = nm_pred / nm_pred_norm nm_pred_z = tf.constant(1.) / nm_pred_norm nm_pred_xyz = tf.concat([nm_pred_xy, nm_pred_z], axis=-1) * masks # selete normal map used in rendering - gt or pred normals = nm_gt if preTrain_flag else nm_pred_xyz # reconstruct SH lightings from predicted statistical SH lighting model lighting_model = '../hdr_illu_pca' lighting_vectors = tf.constant(np.load(os.path.join(lighting_model,'pcaVector.npy')),dtype=tf.float32) lighting_means = tf.constant(np.load(os.path.join(lighting_model,'mean.npy')),dtype=tf.float32) lightings_var = tf.constant(np.load(os.path.join(lighting_model,'pcaVariance.npy')),dtype=tf.float32) if preTrain_flag: lightings = sup_illuDecomp_layer.illuDecomp(inputs,albedos,nm_gt,gamma) else: lightings =pred_illuDecomp_layer.illuDecomp(inputs,albedos,nm_pred_xyz,gamma,masks) lightings_pca = tf.matmul((lightings - lighting_means), pinv(lighting_vectors)) # recompute lightings from lightins_pca which could add weak constraint on lighting reconstruction lightings = tf.matmul(lightings_pca,lighting_vectors) + lighting_means # reshape 27-D lightings to 9*3 lightings lightings = tf.reshape(lightings,[tf.shape(lightings)[0],9,3]) ### lighting prior loss var = tf.reduce_mean(lightings_pca**2,axis=0) illu_prior_loss = tf.losses.absolute_difference(var, lightings_var) illu_prior_loss = tf.log(illu_prior_loss + 1.) ### stereo supervision based on albedos reprojection consistancy reproj_tb = tf.to_float(tf.equal(pair_label,tf.transpose(pair_label))) reproj_tb = tf.cast(tf.matrix_set_diag(reproj_tb, tf.zeros([tf.shape(inputs)[0]])),tf.bool) reproj_list = tf.where(reproj_tb) img1_inds = tf.expand_dims(reproj_list[:,0],axis=-1) img2_inds = tf.expand_dims(reproj_list[:,1],axis=-1) albedo1 = tf.gather_nd(albedos,img1_inds) dms1 = tf.gather_nd(dms,img1_inds) cams1 = tf.gather_nd(cams,img1_inds) albedo2 = tf.gather_nd(albedos,img2_inds) cams2 = tf.gather_nd(cams,img2_inds) scale_xs1 = tf.gather_nd(scale_xs, img1_inds) scale_xs2 = tf.gather_nd(scale_xs, img2_inds) scale_ys1 = tf.gather_nd(scale_ys, img1_inds) scale_ys2 = tf.gather_nd(scale_ys, img2_inds) input1 = tf.gather_nd(inputs, img1_inds) # mask_indices contains indices for image index inside batch and spatial locations, and ignores the rgb channel index reproj_albedo1, reproj_mask = reproj_layer.map_reproj(dms1,albedo2,cams1,cams2,scale_xs1,scale_xs2,scale_ys1,scale_ys2) reproj_albedo1 = reproj_albedo1+tf.constant(1e-4) # numerical stable constant ### scale intensities for each image num_imgs = tf.shape(reproj_mask)[0] im_ = tf.constant(0) output = tf.TensorArray(dtype=tf.float32,size=num_imgs) def body(im_, output): reproj_mask_ = reproj_mask[im_] albedo1_ = tf.boolean_mask(albedo1[im_],reproj_mask_) reproj_albedo1_ = tf.boolean_mask(reproj_albedo1[im_],reproj_mask_) k = tf.reduce_sum(albedo1_*reproj_albedo1_,keepdims=True)/(tf.reduce_sum(reproj_albedo1_**2,keepdims=True)+tf.constant(1e-4)) output = output.write(im_,k) im_ += tf.constant(1) return im_, output def condition(im_, output): return tf.less(im_,num_imgs) _,output = tf.while_loop(condition, body, loop_vars=[im_, output]) ks = tf.expand_dims(output.stack(), axis=-1) albedo1_pixels = tf.boolean_mask(albedo1, reproj_mask) reproj_albedo1_pixels = tf.boolean_mask(reproj_albedo1*ks, reproj_mask) reproj_err = tf.losses.mean_squared_error(cvtLab(albedo1_pixels), cvtLab(reproj_albedo1_pixels)) ### formulate loss based on paired batches ### # self-supervision based on intensity reconstruction shadings, renderings_mask = lambSH_layer.lambSH_layer(tf.ones_like(albedos), normals, lightings, 1.) # compare rendering intensity by Lab inputs_pixels = cvtLab(tf.boolean_mask(inputs,renderings_mask)) renderings = cvtLab(tf.boolean_mask(tf.pow(albedos*shadings,1./gamma),renderings_mask)) render_err = tf.losses.mean_squared_error(inputs_pixels,renderings) ### compute rendering loss from cross-projected alebdo map cross_shadings = tf.gather_nd(shadings, img1_inds) inputs_pixels = cvtLab(tf.boolean_mask(input1,reproj_mask)) cross_renderings = cvtLab(tf.boolean_mask(tf.pow(tf.nn.relu(cross_shadings*reproj_albedo1*ks), 1./gamma),reproj_mask)) cross_render_err = tf.losses.mean_squared_error(inputs_pixels,cross_renderings) ### measure smoothness of albedo map Gx = tf.constant(1/2)*tf.expand_dims(tf.expand_dims(tf.constant([[-1,1]], dtype=tf.float32), axis=-1), axis=-1) Gy = tf.constant(1/2)*tf.expand_dims(tf.expand_dims(tf.constant([[-1],[1]], dtype=tf.float32), axis=-1), axis=-1) Gx_3 = tf.tile(Gx, multiples=(1,1,3,1)) Gy_3 = tf.tile(Gy, multiples=(1,1,3,1)) albedo_lab = tf.reshape(cvtLab(tf.reshape(albedos,[-1,3])),[-1,200,200,3]) aGx = tf.nn.conv2d(albedos, Gx_3, padding='SAME', strides=(1,1,1,1)) aGy = tf.nn.conv2d(albedos, Gy_3, padding='SAME', strides=(1,1,1,1)) aGxy = tf.concat([aGx,aGy], axis=-1) # compute pixel-wise smoothness weights by angle distance between neighbour pixels' chromaticities inputs_pad = tf.pad(inputs, paddings=tf.constant([[0,0], [0,1], [0,1], [0,0]])) chroma_pad = tf.nn.l2_normalize(inputs_pad, axis=-1) chroma = chroma_pad[:,:-1,:-1,:] chroma_X = chroma_pad[:,:-1,1:,:] chroma_Y = chroma_pad[:,1:,:-1,:] chroma_Gx = tf.reduce_sum(chroma*chroma_X, axis=-1, keepdims=True)**tf.constant(2.) - tf.constant(1.) chroma_Gy = tf.reduce_sum(chroma*chroma_Y, axis=-1, keepdims=True)**tf.constant(2.) - tf.constant(1.) chroma_Gx = tf.exp(chroma_Gx / tf.constant(0.0001)) chroma_Gy = tf.exp(chroma_Gy / tf.constant(0.0001)) chroma_Gxy = tf.concat([chroma_Gx, chroma_Gy], axis=-1) int_pad = tf.reduce_sum(inputs_pad**tf.constant(2.), axis=-1, keepdims=True) int = int_pad[:,:-1,:-1,:] int_X = int_pad[:,:-1,1:,:] int_Y = int_pad[:,1:,:-1,:] int_Gx = tf.where(condition=int < int_X, x=int, y=int_X) int_Gy = tf.where(condition=int < int_Y, x=int, y=int_Y) int_Gx = tf.constant(1.) + tf.exp(- int_Gx / tf.constant(.8)) int_Gy = tf.constant(1.) + tf.exp(- int_Gy / tf.constant(.8)) int_Gxy = tf.concat([int_Gx, int_Gy], axis=-1) Gxy_weights = int_Gxy * chroma_Gxy albedo_smt_error = tf.reduce_mean(tf.abs(aGxy)*Gxy_weights) ### albedo map pseudo-supervision loss if preTrain_flag: am_loss = tf.constant(0.) else: amSup_mask = tf.not_equal(tf.reduce_sum(nm_gt,axis=-1),0) am_sup_pixel = cvtLab(tf.boolean_mask(am_sup, amSup_mask)) albedos_pixel = cvtLab(tf.boolean_mask(albedos, amSup_mask)) am_loss = tf.losses.mean_squared_error(am_sup_pixel, albedos_pixel) ### regualarisation loss reg_loss = sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) ### compute nm_pred error nmSup_mask = tf.not_equal(tf.reduce_sum(nm_gt,axis=-1),0) nm_gt_pixel = tf.boolean_mask(nm_gt, nmSup_mask) nm_pred_pixel = tf.boolean_mask(nm_pred_xyz, nmSup_mask) nm_prod = tf.reduce_sum(nm_pred_pixel * nm_gt_pixel, axis=-1, keepdims=True) nm_cosValue = tf.constant(0.9999) nm_prod = tf.clip_by_value(nm_prod, -nm_cosValue, nm_cosValue) nm_angle = tf.acos(nm_prod) + tf.constant(1e-4) nm_loss = tf.reduce_mean(nm_angle**2) ### compute gradient loss nm_pred_Gx = conv2d_nosum(nm_pred_xyz, Gx) nm_pred_Gy = conv2d_nosum(nm_pred_xyz, Gy) nm_pred_Gxy = tf.concat([nm_pred_Gx, nm_pred_Gy], axis=-1) normals_Gx = conv2d_nosum(nm_gt, Gx) normals_Gy = conv2d_nosum(nm_gt, Gy) normals_Gxy = tf.concat([normals_Gx, normals_Gy], axis=-1) nm_pred_smt_error = tf.losses.mean_squared_error(nm_pred_Gxy, normals_Gxy) ### total loss render_err *= tf.constant(.1) reproj_err *= tf.constant(.05) * reproj_w_var cross_render_err *= tf.constant(.1) am_loss *= tf.constant(.1) illu_prior_loss *= tf.constant(.01) albedo_smt_error *= tf.constant(50.) * am_smt_w_var nm_pred_smt_error *= tf.constant(1.) nm_loss *= tf.constant(1.) if reg_loss_flag == True: loss = render_err + reproj_err + cross_render_err + reg_loss + illu_prior_loss + albedo_smt_error + nm_pred_smt_error + nm_loss + am_loss else: loss = render_err + reproj_err + cross_render_err + illu_prior_loss + albedo_smt_error + nm_pred_smt_error + nm_loss + am_loss return lightings, albedos, nm_pred_xyz, loss, render_err, reproj_err, cross_render_err, reg_loss, illu_prior_loss, albedo_smt_error, nm_pred_smt_error, nm_loss, am_loss # input RGB is 2d tensor with shape (n_pix, 3) def cvtLab(RGB): # threshold definition T = tf.constant(0.008856) # matrix for converting RGB to LUV color space cvt_XYZ = tf.constant([[0.412453,0.35758,0.180423],[0.212671,0.71516,0.072169],[0.019334,0.119193,0.950227]]) # convert RGB to XYZ XYZ = tf.matmul(RGB,tf.transpose(cvt_XYZ)) # normalise for D65 white point XYZ /= tf.constant([[0.950456, 1., 1.088754]])*100 mask = tf.to_float(tf.greater(XYZ,T)) fXYZ = XYZ**(1/3)*mask + (1.-mask)*(tf.constant(7.787)*XYZ + tf.constant(0.137931)) M_cvtLab = tf.constant([[0., 116., 0.], [500., -500., 0.], [0., 200., -200.]]) Lab = tf.matmul(fXYZ, tf.transpose(M_cvtLab)) + tf.constant([[-16., 0., 0.]]) mask = tf.to_float(tf.equal(Lab, tf.constant(0.))) Lab += mask * tf.constant(1e-4) return Lab # compute pseudo inverse for input matrix def pinv(A, reltol=1e-6): # compute SVD of input A s, u, v = tf.svd(A) # invert s and clear entries lower than reltol*s_max atol = tf.reduce_max(s) * reltol s = tf.where(s>atol, s, atol*tf.ones_like(s)) s_inv = tf.diag(1./s) # compute v * s_inv * u_t as psuedo inverse return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u))) # compute regular 2d convolution on 3d data def conv2d_nosum(input, kernel): input_x = input[:,:,:,0:1] input_y = input[:,:,:,1:2] input_z = input[:,:,:,2:3] output_x = tf.nn.conv2d(input_x, kernel, strides=(1,1,1,1), padding='SAME') output_y = tf.nn.conv2d(input_y, kernel, strides=(1,1,1,1), padding='SAME') output_z = tf.nn.conv2d(input_z, kernel, strides=(1,1,1,1), padding='SAME') return tf.concat([output_x,output_y,output_z], axis=-1) # compute regular 2d convolution on 3d data def conv2d_nosum_2ch(input, kernel): input_x = input[:,:,:,0:1] input_y = input[:,:,:,1:2] output_x = tf.nn.conv2d(input_x, kernel, strides=(1,1,1,1), padding='SAME') output_y = tf.nn.conv2d(input_y, kernel, strides=(1,1,1,1), padding='SAME') return tf.concat([output_x,output_y], axis=-1) ================================================ FILE: model/pred_illuDecomp_layer.py ================================================ import tensorflow as tf # am is the albedo map, which has shape (batch, height, width, 3[rgb]) # nm is the sparse normal map, which has shape (batch, height, width, 3[x,y,z]) # L_SHcoeff contains the SH coefficients for environment illumination, using 2nd order SH. L_SHcoeff has shape (batch, 9, 3[rgb]) def illuDecomp(input, am, nm, gamma, masks): """ i = albedo * irradiance the multiplication is elementwise albedo is given irraidance = n.T * M * n, where n is (x,y,z,1) M is contructed from some precomputed constants and L_SHcoeff, where M contains information about illuminations, clamped cosine and SH basis """ # compute shading by dividing input by albedo shadings = tf.pow(input,gamma)/am # perform clamping on resulted shading to guarantee its numerical range shadings = (tf.clip_by_value(shadings, 0., 1.) + tf.constant(1e-4)) * masks # compute shading by linear equation regarding nm and L_SHcoeffs # E(n) = c1*L22*(x**2-y**2) + (c3*z**2 - c5)*L20 + c4*L00 + 2*c1*L2-2*x*y + 2*c1*L21*x*z + 2*c1*L2-1*y*z + 2*c2*L11*x + 2*c2*L1-1*y + 2*c2*L10*z # E(n) = c4*L00 + 2*c2*y*L1-1 + 2*c2*z*L10 + 2*c2*x*L11 + 2*c1*x*y*L2-2 + 2*c1*y*z*L2-1 + (c3*z**2 - c5)*L20 + 2*c1*x*z*L21 + c1*(x**2-y**2)*L22 c1 = tf.constant(0.429043,dtype=tf.float32) c2 = tf.constant(0.511664,dtype=tf.float32) c3 = tf.constant(0.743125,dtype=tf.float32) c4 = tf.constant(0.886227,dtype=tf.float32) c5 = tf.constant(0.247708,dtype=tf.float32) # find defined pixels num_iter = tf.shape(nm)[0] output = tf.TensorArray(dtype=tf.float32, size=num_iter) i = tf.constant(0) def condition(i, output): return iatol) s_inv = tf.diag(1./s) # compute v * s_inv * u_t as psuedo inverse return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u))) ================================================ FILE: model/reproj_layer.py ================================================ # apply error mask in albedo reprojection # no rotation involved #### directly output flatten reprojected pixels and the reconstruction mask # the differentiable layer performing reprojection import tensorflow as tf import numpy as np # pc is n-by-3 matrix containing point could three locations # cam is the new camera parameters, whose f and p_a have shape (batch) and c has shape (batch, 2) # dm1 is the depth map associated with cam1 that is camera for output image, which has shape (batch, height, width) # img2 is the input image that acts as source image for reprojection, which has shape (batch, height, width, 3) def map_reproj(dm1,map2,cam1,cam2,scale_x1,scale_x2,scale_y1,scale_y2): batch_size = tf.shape(dm1)[0] # read camera parameters c1 = cam1[:,2:4] f1 = cam1[:,0] p_a1 = cam1[:,1] # ratio is width divided by height R1 = tf.reshape(cam1[:,4:13],[-1,3,3]) t1 = cam1[:,13:] c2 = cam2[:,2:4] f2 = cam2[:,0] p_a2 = cam2[:,1] R2 = tf.reshape(cam2[:,4:13],[-1,3,3]) t2 = cam2[:,13:] # project pixel points back to camera coords # u is the height and v is the width # u and v are scalars u1 = tf.shape(dm1)[1] v1 = tf.shape(dm1)[2] # convert u1 and v1 to float, convenient for computation u1 = tf.to_float(u1) v1 = tf.to_float(v1) ### regular grid in output image # x increase towards right, y increase toward down vm,um = tf.meshgrid(tf.range(1.,v1+1.), tf.range(1.,u1+1.)) # apply scaling factors on f # f1 = f1/(scale_x1+scale_y1)*2 # f1 = tf.stack([f1, f1*p_a1],axis=-1) f1 = tf.stack([f1/scale_x1, f1/scale_y1*p_a1],axis=-1) # expand f1 (batch,2,1,1), to be consistant with dm f1 = tf.expand_dims(tf.expand_dims(f1,axis=-1),axis=-1) # expand c1 dimension (batch,2,1,1) c1 = tf.expand_dims(tf.expand_dims(c1,axis=-1),axis=-1) # expand vm and um to have shape (1,height,width) vm = tf.expand_dims(vm,axis=0) um = tf.expand_dims(um,axis=0) # compute 3D point x and y coordinates # Xm and Ym have shape (batch, height, width) Xm = (vm-c1[:,0])/f1[:,0]*dm1 Ym = (um-c1[:,1])/f1[:,1]*dm1 # the point cloud is (batch, 3, npix) matrix, each row is XYZ cam coords for one point pc = tf.stack([tf.contrib.layers.flatten(Xm), tf.contrib.layers.flatten(Ym), tf.contrib.layers.flatten(dm1)], axis=1) ### transfer pc from coords of cam1 to cam2 # construct homogeneous point cloud with shape batch-4-by-num_pix num_pix = tf.shape(pc)[-1] homo_pc_c1 = tf.concat([pc, tf.ones((batch_size,1,num_pix), dtype=tf.float32)], axis=1) # both transformation matrix have shape batch-by-4-by-4, valid for multiplication with defined homogeneous point cloud last_row = tf.tile(tf.constant([[[0,0,0,1]]],dtype=tf.float32), multiples=[batch_size,1,1]) W_C_R_t1 = tf.concat([R1,tf.expand_dims(t1,axis=2)],axis=2) W_C_trans1 = tf.concat([W_C_R_t1, last_row], axis=1) W_C_R_t2 = tf.concat([R2,tf.expand_dims(t2,axis=2)],axis=2) W_C_trans2 = tf.concat([W_C_R_t2, last_row], axis=1) # batch dot product, output has shape (batch, 4, npix) homo_pc_c2 = tf.matmul(W_C_trans2, tf.matmul(tf.matrix_inverse(W_C_trans1), homo_pc_c1)) ### project point cloud to cam2 pixel coordinates # u in vertical and v in horizontal u2 = tf.shape(map2)[1] v2 = tf.shape(map2)[2] # convert u2 and v2 to float u2 = tf.to_float(u2) v2 = tf.to_float(v2) # f2 = f2/(scale_x2+scale_y2)*2 # f2 = tf.stack([f2, f2*p_a2],axis=-1) f2 = tf.stack([f2/scale_x2, f2/scale_y2*p_a2],axis=-1) # construct intrics matrics, which has shape (batch, 3, 4) zeros = tf.zeros_like(f2[:,0],dtype=tf.float32) ones = tf.ones_like(f2[:,0],tf.float32) k2 = tf.stack([tf.stack([f2[:,0],zeros,c2[:,0],zeros],axis=1), tf.stack([zeros,f2[:,1],c2[:,1],zeros],axis=1), tf.stack([zeros,zeros,ones,zeros],axis=1)],axis=1) ## manual batch dot product k2 = tf.expand_dims(k2,axis=-1) homo_pc_c2 = tf.expand_dims(homo_pc_c2,axis=1) # homo_uv2 has shape (batch, 3, npix) homo_uv2 = tf.reduce_sum(k2*homo_pc_c2,axis=2) # the reprojected locations of regular grid in output image # both have shape (batch, npix) v_reproj = homo_uv2[:,0,:]/homo_uv2[:,2,:] u_reproj = homo_uv2[:,1,:]/homo_uv2[:,2,:] # u and v are flatten vector containing reprojected pixel locations # the u and v on same index compose one pixel u_valid = tf.logical_and(tf.logical_and(tf.logical_not(tf.is_nan(u_reproj)), u_reproj>0), u_reproj0), v_reprojatol) s_inv = tf.diag(1./s) # compute v * s_inv * u_t as psuedo inverse return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u))) ================================================ FILE: pre_train_model/.keep ================================================ ================================================ FILE: test_demo.py ================================================ import os import numpy as np import tensorflow as tf import cv2 from skimage import io import argparse from model import SfMNet, lambSH_layer, pred_illuDecomp_layer from utils import render_sphere_nm parser = argparse.ArgumentParser(description='InverseRenderNet') parser.add_argument('--image', help='Path to test image') parser.add_argument('--mask', help='Path to image mask') parser.add_argument('--model', help='Path to trained model') parser.add_argument('--output', help='Folder saving outputs') args = parser.parse_args() img_path = args.image mask_path = args.mask img = io.imread(img_path) mask = io.imread(mask_path) dst_dir = args.output os.makedirs(dst_dir) input_height = 200 input_width = 200 ori_height, ori_width = img.shape[:2] if ori_height / ori_width >1: scale = ori_width / 200 input_height = np.int32(scale * 200) else: scale = ori_height / 200 input_width = np.int32(scale * 200) # compute pseudo inverse for input matrix def pinv(A, reltol=1e-6): # compute SVD of input A s, u, v = tf.svd(A) # invert s and clear entries lower than reltol*s_max atol = tf.reduce_max(s) * reltol s = tf.boolean_mask(s, s>atol) s_inv = tf.diag(1./s) # compute v * s_inv * u_t as psuedo inverse return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u))) import ipdb; ipdb.set_trace() inputs_var = tf.placeholder(tf.float32, (None, input_height, input_width, 3)) masks_var = tf.placeholder(tf.float32, (None, input_height, input_width, 1)) am_deconvOut, nm_deconvOut = SfMNet.SfMNet(inputs=inputs_var,is_training=False, height=input_height, width=input_width, n_layers=30, n_pools=4, depth_base=32) # separate albedo, error mask and shadow mask from deconvolutional output albedos = am_deconvOut nm_pred = nm_deconvOut gamma = tf.constant(2.2) # post-process on raw albedo and nm_pred albedos = tf.nn.sigmoid(albedos) * masks_var + tf.constant(1e-4) nm_pred_norm = tf.sqrt(tf.reduce_sum(nm_pred**2, axis=-1, keepdims=True)+tf.constant(1.)) nm_pred_xy = nm_pred / nm_pred_norm nm_pred_z = tf.constant(1.) / nm_pred_norm nm_pred_xyz = tf.concat([nm_pred_xy, nm_pred_z], axis=-1) * masks_var # compute illumination lighting_model = 'illu_pca' lighting_vectors = tf.constant(np.load(os.path.join(lighting_model,'pcaVector.npy')),dtype=tf.float32) lighting_means = tf.constant(np.load(os.path.join(lighting_model,'mean.npy')),dtype=tf.float32) lightings = pred_illuDecomp_layer.illuDecomp(inputs_var, albedos, nm_pred_xyz, gamma, masks_var) lightings_pca = tf.matmul((lightings - lighting_means), pinv(lighting_vectors)) lightings = tf.matmul(lightings_pca,lighting_vectors) + lighting_means # reshape 27-D lightings to 9*3 lightings lightings = tf.reshape(lightings,[tf.shape(lightings)[0],9,3]) # visualisations shading, _ = lambSH_layer.lambSH_layer(tf.ones_like(albedos), nm_pred_xyz, lightings, 1.) nm_sphere = tf.constant(render_sphere_nm.render_sphere_nm(100,1),dtype=tf.float32) nm_sphere = tf.tile(nm_sphere, (tf.shape(inputs_var)[0],1,1,1)) lighting_recon, _ = lambSH_layer.lambSH_layer(tf.ones_like(nm_sphere), nm_sphere, lightings, 1.) irn_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='conv') + tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='am') + tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='nm') model_path = tf.train.get_checkpoint_state(args.model).model_checkpoint_path total_loss = 0 sess = tf.InteractiveSession() saver = tf.train.Saver(irn_vars) saver.restore(sess, model_path) # evaluation ori_img = img ori_height, ori_width = ori_img.shape[:2] img = cv2.resize(img, (input_width, input_height)) img = np.float32(img)/255. img = img[None, :, :, :] mask = cv2.resize(mask, (input_width, input_height), cv2.INTER_NEAREST) mask = np.float32(mask==255)[None,:,:,None] [albedos_val, nm_pred_val, lighting_recon_val, shading_val] = sess.run([albedos, nm_pred_xyz, lighting_recon, shading], feed_dict={inputs_var:img, masks_var:mask}) # post-process results nm_pred_val = (nm_pred_val+1.)/2. albedos_val = cv2.resize(albedos_val[0], (ori_width, ori_height)) shading_val = cv2.resize(shading_val[0], (ori_width, ori_height)) lighting_recon_val = lighting_recon_val[0] nm_pred_val = cv2.resize(nm_pred_val[0], (ori_width, ori_height)) albedos_val = (albedos_val-albedos_val.min()) / (albedos_val.max()-albedos_val.min()) albedos_val = np.uint8(albedos_val*255.) shading_val = np.uint8(shading_val*255.) lighting_recon_val = np.uint8(lighting_recon_val*255.) nm_pred_val = np.uint8(nm_pred_val*255.) input_path = os.path.join(dst_dir, 'img.png') io.imsave(input_path, ori_img) albedo_path = os.path.join(dst_dir, 'albedo.png') io.imsave(albedo_path, albedos_val) shading_path = os.path.join(dst_dir, 'shading.png') io.imsave(shading_path, shading_val) nm_pred_path = os.path.join(dst_dir, 'nm_pred.png') io.imsave(nm_pred_path, nm_pred_val) lighting_path = os.path.join(dst_dir, 'lighting.png') io.imsave(lighting_path, lighting_recon_val) ================================================ FILE: test_iiw.py ================================================ import json import os import numpy as np import tensorflow as tf import importlib import cv2 from skimage import io import argparse from model import SfMNet, lambSH_layer, pred_illuDecomp_layer from glob import glob from utils.whdr import compute_whdr parser = argparse.ArgumentParser(description='InverseRenderNet') parser.add_argument('--iiw', help='Root directory for iiw-dataset') parser.add_argument('--model', help='Path to trained model') args = parser.parse_args() iiw = args.iiw test_ids = np.load('iiw_test_ids.npy') input_height = 200 input_width = 200 # compute pseudo inverse for input matrix def pinv(A, reltol=1e-6): # compute SVD of input A s, u, v = tf.svd(A) # invert s and clear entries lower than reltol*s_max atol = tf.reduce_max(s) * reltol s = tf.boolean_mask(s, s>atol) s_inv = tf.diag(1./s) # compute v * s_inv * u_t as psuedo inverse return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u))) inputs_var = tf.placeholder(tf.float32, (None, input_height, input_width, 3)) masks_var = tf.placeholder(tf.float32, (None, input_height, input_width, 1)) train_flag = tf.placeholder(tf.bool, ()) am_deconvOut, _ = SfMNet.SfMNet(inputs=inputs_var,is_training=train_flag, height=input_height, width=input_width, n_layers=30, n_pools=4, depth_base=32) # separate albedo, error mask and shadow mask from deconvolutional output albedos = am_deconvOut # post-process on raw albedo and nm_pred albedos = tf.nn.sigmoid(albedos) * masks_var + tf.constant(1e-4) irn_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='conv') + tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='am') + tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='nm') model_path = tf.train.get_checkpoint_state(args.model).model_checkpoint_path total_loss = 0 sess = tf.InteractiveSession() saver = tf.train.Saver(irn_vars) saver.restore(sess, model_path) for counter, test_id in enumerate(test_ids): img_file = str(test_id)+'.png' judgement_file = str(test_id)+'.json' img_path = os.path.join(iiw, 'data', img_file) judgement_path = os.path.join(iiw, 'data', judgement_file) img = io.imread(img_path) judgement = json.load(open(judgement_path)) ori_width, ori_height = img.shape[:2] img = cv2.resize(img, (input_width, input_height)) img = np.float32(img)/255. img = img[None, :, :, :] mask = np.ones((1, input_height, input_width, 1), np.bool) [albedos_val] = sess.run([albedos], feed_dict={train_flag:False, inputs_var:img, masks_var:mask}) albedos_val = cv2.resize(albedos_val[0], (ori_width, ori_height)) albedos_val = (albedos_val-albedos_val.min()) / (albedos_val.max()-albedos_val.min()) albedos_val = albedos_val/2+.5 loss = compute_whdr(albedos_val, judgement) total_loss += loss print('whdr:{:f}\twhdr_avg:{:f}'.format(loss, total_loss/(counter+1))) print("IIW TEST WHDR %f"%(total_loss/len(test_ids))) ================================================ FILE: train.py ================================================ # also predict shadow mask and error mask # no rotation #### compute albedo reproj loss only on reprojection available area; compute reconstruction and its loss only based on defined area import tensorflow as tf import importlib import os import pickle as pk import sys import numpy as np import time import argparse from PIL import Image import glob from model import SfMNet, lambSH_layer, pred_illuDecomp_layer, loss_layer, dataloader parser = argparse.ArgumentParser(description='InverseRenderNet') parser.add_argument('--n_batch', '-n', help='number of minibatch', type=int) parser.add_argument('--data_path', '-p', help='Path to training data') parser.add_argument('--train_mode', '-m', help='specify the phase for training (pre-train/self-train)', choices={'pre-train', 'self-train'}) args = parser.parse_args() def main(): inputs_shape = (5,200,200,3) next_element, trainData_init_op, num_train_batches = dataloader.megaDepth_dataPipeline(args.n_batch, args.data_path) inputs_var = tf.reshape(next_element[0], (-1, inputs_shape[1], inputs_shape[2], inputs_shape[3])) dms_var = tf.reshape(next_element[1], (-1, inputs_shape[1], inputs_shape[2])) nms_var = tf.reshape(next_element[2], (-1, inputs_shape[1], inputs_shape[2], 3)) cams_var = tf.reshape(next_element[3], (-1, 16)) scaleXs_var = tf.reshape(next_element[4], (-1,)) scaleYs_var = tf.reshape(next_element[5], (-1,)) masks_var = tf.reshape(next_element[6], (-1, inputs_shape[1], inputs_shape[2])) # var helping cross projection pair_label_var = tf.constant(np.repeat(np.arange(args.n_batch),inputs_shape[0])[:,None], dtype=tf.float32) # weights for smooth loss and am_consistency loss am_smt_w_var = tf.placeholder(tf.float32, ()) reproj_w_var = tf.placeholder(tf.float32, ()) # mask out sky in inputs and nms masks_var_4d = tf.expand_dims(masks_var, axis=-1) inputs_var *= masks_var_4d nms_var *= masks_var_4d # inverserendernet if args.train_mode == 'pre-train': am_deconvOut, nm_deconvOut = SfMNet.SfMNet(inputs=inputs_var,is_training=True, height=inputs_shape[1], width=inputs_shape[2], name='pre_train_IRN/', n_layers=30, n_pools=4, depth_base=32) am_sup = tf.zeros_like(am_deconvOut) preTrain_flag = True elif args.train_mode == 'self-train': am_deconvOut, nm_deconvOut = SfMNet.SfMNet(inputs=inputs_var,is_training=True, height=inputs_shape[1], width=inputs_shape[2], name='IRN/', n_layers=30, n_pools=4, depth_base=32) am_sup, _ = SfMNet.SfMNet(inputs=inputs_var,is_training=False, height=inputs_shape[1], width=inputs_shape[2], name='pre_train_IRN/', n_layers=30, n_pools=4, depth_base=32) am_sup = tf.nn.sigmoid(am_sup) * masks_var_4d + tf.constant(1e-4) preTrain_flag = False # separate albedo, error mask and shadow mask from deconvolutional output albedoMaps = am_deconvOut[:,:,:,:3] # formulate loss light_SHCs, albedoMaps, nm_preds, loss, render_err, reproj_err, cross_render_err, reg_loss, illu_prior_loss, albedo_smt_error, nm_smt_loss, nm_loss, am_loss = loss_layer.loss_formulate(albedoMaps, nm_deconvOut, am_sup, nms_var, inputs_var, dms_var, cams_var, scaleXs_var, scaleYs_var, masks_var_4d, pair_label_var, True, am_smt_w_var, reproj_w_var, reg_loss_flag=True) # defined traning loop epochs = 30 num_batches = num_train_batches num_subbatch = args.n_batch num_iters = np.int32(np.ceil(num_batches/num_subbatch)) # training op global_step = tf.Variable(1,name='global_step',trainable=False) train_step = tf.contrib.layers.optimize_loss(loss, optimizer=tf.train.AdamOptimizer(learning_rate=.05, epsilon=1e-1), learning_rate=None, global_step=global_step) # define saver for saving and restoring irn_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='IRN') if args.train_mode == 'self-train' else tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='pre_train_IRN') saver = tf.train.Saver(irn_vars) # define session config = tf.ConfigProto(allow_soft_placement=True) config.gpu_options.allow_growth = True sess = tf.InteractiveSession(config=config) # train from scratch or keep training trained model tf.local_variables_initializer().run() tf.global_variables_initializer().run() assignOps = [] if args.train_mode == 'self-train': # load am_sup net preTrain_irn_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='pre_train_IRN') saver_loadOldVar = tf.train.Saver(preTrain_irn_vars) saver_loadOldVar.restore(sess, 'pre_train_model/model.ckpt') # import ipdb; ipdb.set_trace() # duplicate pre_train model with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): vars = tf.contrib.framework.list_variables('pre_train_model') for var_name, _ in vars: var = tf.contrib.framework.load_variable('pre_train_model', var_name) new_var_name = var_name.replace('pre_train_IRN', 'IRN') new_var = tf.get_variable(name=new_var_name) assignOps += [new_var.assign(var)] sess.run(assignOps) # start training trainData_init_op.run() dst_dir = 'irn_model' if args.train_mode == 'self-train' else 'pre_train_model' for i in range(1,epochs+1): loss_avg = 0 f = open('cost.txt','a') # graduately update weights if pre-training reproj_weight = .2 + np.clip(.8 * (i-16)/14, 0., .8) if args.train_mode == 'pre-train' else 1. am_smt_weight = .2 + np.clip(.8 * (i-1)/14, 0., .8) if args.train_mode == 'pre-train' else 1. for j in range(1,num_iters+1): start_time = time.time() # train [loss_val, reg_loss_val, render_err_val, reproj_err_val, cross_render_err_val, illu_prior_val, albedo_smt_error_val, nm_smt_loss_val, nm_loss_val, am_loss_val] = sess.run([train_step, reg_loss, render_err, reproj_err, cross_render_err, illu_prior_loss, albedo_smt_error, nm_smt_loss, nm_loss, am_loss], feed_dict={am_smt_w_var:am_smt_weight, reproj_w_var:reproj_weight}) loss_avg += loss_val # log if j % 1 == 0: print('iter %d/%d loop %d/%d took %.3fs' % (i,epochs,j,num_iters,time.time()-start_time)) print('\tloss_avg = %f, loss = %f' % (loss_avg / j,loss_val)) print('\t\treg_loss = %f, render_err = %f, reproj_err = %f, cross_render_err = %f, illu_prior = %f, albedo_smt_error = %f, nm_smt_loss = %f, nm_loss = %f, am_loss = %f' % (reg_loss_val, render_err_val, reproj_err_val, cross_render_err_val, illu_prior_val, albedo_smt_error_val, nm_smt_loss_val, nm_loss_val, am_loss_val)) f.write('iter %d/%d loop %d/%d took %.3fs\n\tloss_avg = %f, loss = %f\n\t\treg_loss = %f, render_err = %f, reproj_err = %f, cross_render_err = %f, illu_prior = %f, albedo_smt_error = %f, nm_smt_loss = %f, nm_loss = %f, am_loss = %f\n' % (i,epochs,j,num_iters,time.time()-start_time,loss_avg/j, loss_val, reg_loss_val, render_err_val, reproj_err_val, cross_render_err_val, illu_prior_val, albedo_smt_error_val, nm_smt_loss_val, nm_loss_val, am_loss_val)) f.close() # save model every 10 iterations saver.save(sess,os.path.join(dst_dir, 'model.ckpt')) if __name__ == '__main__': main() ================================================ FILE: utils/render_sphere_nm.py ================================================ import numpy as np def render_sphere_nm(radius, num): # nm is a batch of normal maps nm = [] for i in range(num): ### hemisphere height = 2*radius width = 2*radius centre = radius x_grid, y_grid = np.meshgrid(np.arange(1.,2*radius+1), np.arange(1.,2*radius+1)) # grids are (-radius, radius) x_grid -= centre # y_grid -= centre y_grid = centre - y_grid # scale range of h and w grid in (-1,1) x_grid /= radius y_grid /= radius dist = 1 - (x_grid**2+y_grid**2) mask = dist > 0 z_grid = np.ones_like(mask) * np.nan z_grid[mask] = np.sqrt(dist[mask]) # remove xs and ys by masking out nans in zs x_grid[~(mask)] = np.nan y_grid[~(mask)] = np.nan # concatenate normal map nm.append(np.stack([x_grid,y_grid,z_grid],axis=2)) ### sphere # span the regular grid for computing azimuth and zenith angular map # height = 2*radius # width = 2*radius # centre = radius # h_grid, v_grid = np.meshgrid(np.arange(1.,2*radius+1), np.arange(1.,2*radius+1)) # # grids are (-radius, radius) # h_grid -= centre # # v_grid -= centre # v_grid = centre - v_grid # # scale range of h and v grid in (-1,1) # h_grid /= radius # v_grid /= radius # # z_grid is linearly spread along theta/zenith in range (0,pi) # dist_grid = np.sqrt(h_grid**2+v_grid**2) # dist_grid[dist_grid>1] = np.nan # theta_grid = dist_grid * np.pi # z_grid = np.cos(theta_grid) # rho_grid = np.arctan2(v_grid,h_grid) # x_grid = np.sin(theta_grid)*np.cos(rho_grid) # y_grid = np.sin(theta_grid)*np.sin(rho_grid) # # concatenate normal map # nm.append(np.stack([x_grid,y_grid,z_grid],axis=2)) # construct batch nm = np.stack(nm,axis=0) return nm ================================================ FILE: utils/whdr.py ================================================ #!/usr/bin/env python2.7 # # This is an implementation of the WHDR metric proposed in this paper: # # Sean Bell, Kavita Bala, Noah Snavely. "Intrinsic Images in the Wild". ACM # Transactions on Graphics (SIGGRAPH 2014). http://intrinsic.cs.cornell.edu. # # Please cite the above paper if you find this code useful. This code is # released under the MIT license (http://opensource.org/licenses/MIT). # import sys import json import argparse import numpy as np from PIL import Image def compute_whdr(reflectance, judgements, delta=0.10): """ Return the WHDR score for a reflectance image, evaluated against human judgements. The return value is in the range 0.0 to 1.0, or None if there are no judgements for the image. See section 3.5 of our paper for more details. :param reflectance: a numpy array containing the linear RGB reflectance image. :param judgements: a JSON object loaded from the Intrinsic Images in the Wild dataset. :param delta: the threshold where humans switch from saying "about the same" to "one point is darker." """ points = judgements['intrinsic_points'] comparisons = judgements['intrinsic_comparisons'] id_to_points = {p['id']: p for p in points} rows, cols = reflectance.shape[0:2] error_sum = 0.0 weight_sum = 0.0 for c in comparisons: # "darker" is "J_i" in our paper darker = c['darker'] if darker not in ('1', '2', 'E'): continue # "darker_score" is "w_i" in our paper weight = c['darker_score'] if weight <= 0 or weight is None: continue point1 = id_to_points[c['point1']] point2 = id_to_points[c['point2']] if not point1['opaque'] or not point2['opaque']: continue # convert to grayscale and threshold l1 = max(1e-10, np.mean(reflectance[ int(point1['y'] * rows), int(point1['x'] * cols), ...])) l2 = max(1e-10, np.mean(reflectance[ int(point2['y'] * rows), int(point2['x'] * cols), ...])) # convert algorithm value to the same units as human judgements if l2 / l1 > 1.0 + delta: alg_darker = '1' elif l1 / l2 > 1.0 + delta: alg_darker = '2' else: alg_darker = 'E' if darker != alg_darker: error_sum += weight weight_sum += weight if weight_sum: return error_sum / weight_sum else: return None def load_image(filename, is_srgb=True): """ Load an image that is either linear or sRGB-encoded. """ if not filename: raise ValueError("Empty filename") image = np.asarray(Image.open(filename)).astype(np.float) / 255.0 if is_srgb: return srgb_to_rgb(image) else: return image def srgb_to_rgb(srgb): """ Convert an sRGB image to a linear RGB image """ ret = np.zeros_like(srgb) idx0 = srgb <= 0.04045 idx1 = srgb > 0.04045 ret[idx0] = srgb[idx0] / 12.92 ret[idx1] = np.power((srgb[idx1] + 0.055) / 1.055, 2.4) return ret if __name__ == "__main__": parser = argparse.ArgumentParser( description=( 'Evaluate an intrinsic image decomposition using the WHDR metric presented in:\n' ' Sean Bell, Kavita Bala, Noah Snavely. "Intrinsic Images in the Wild".\n' ' ACM Transactions on Graphics (SIGGRAPH 2014).\n' ' http://intrinsic.cs.cornell.edu.\n' '\n' 'The output is in the range 0.0 to 1.0.' ) ) parser.add_argument( 'reflectance', metavar='', help='reflectance image to be evaluated') parser.add_argument( 'judgements', metavar='', help='human judgements JSON file') parser.add_argument( '-l', '--linear', action='store_true', required=False, help='assume the reflectance image is linear, otherwise assume sRGB') parser.add_argument( '-d', '--delta', metavar='', type=float, required=False, default=0.10, help='delta threshold (default 0.10)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() reflectance = load_image(filename=args.reflectance, is_srgb=(not args.linear)) judgements = json.load(open(args.judgements)) whdr = compute_whdr(reflectance, judgements, args.delta) print(whdr)