├── README.md ├── Dockerfile ├── resize.py ├── LICENSE └── generate.network.py /README.md: -------------------------------------------------------------------------------- 1 | # super-resolution 2 | 3 | https://medium.com/the-downlinq/super-resolution-on-satellite-imagery-using-deep-learning-part-1-ec5c5cd3cd2 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM comsiqworks/spacenet-utilites-gpu 2 | 3 | MAINTAINER Patrick Hagerty 4 | 5 | RUN apt-get update && apt-get install -y --no-install-recommends \ 6 | build-essential \ 7 | curl \ 8 | git \ 9 | libcurl3-dev \ 10 | libfreetype6-dev \ 11 | libpng12-dev \ 12 | libzmq3-dev \ 13 | pkg-config \ 14 | python-dev \ 15 | rsync \ 16 | software-properties-common \ 17 | unzip \ 18 | vim \ 19 | wget \ 20 | eog \ 21 | zip \ 22 | zlib1g-dev \ 23 | libopencv-dev \ 24 | python-opencv \ 25 | build-essential autoconf libtool libcunit1-dev \ 26 | libproj-dev libgdal-dev libgeos-dev libjson0-dev vim python-gdal \ 27 | && \ 28 | apt-get clean && \ 29 | rm -rf /var/lib/apt/lists/* 30 | 31 | RUN curl -fSsL -O https://bootstrap.pypa.io/get-pip.py && \ 32 | python get-pip.py && \ 33 | rm get-pip.py 34 | 35 | RUN pip --no-cache-dir install \ 36 | ipykernel \ 37 | jupyter \ 38 | matplotlib \ 39 | numpy \ 40 | scipy \ 41 | sklearn \ 42 | tensorflow-gpu \ 43 | && \ 44 | python -m ipykernel.kernelspec 45 | 46 | ENV GIT_BASE=/opt/ 47 | WORKDIR $GIT_BASE 48 | # Set up our notebook config. 49 | RUN git clone --depth 1 https://github.com/CosmiQ/super-resolution.git 50 | 51 | WORKDIR /workspace 52 | 53 | # TensorBoard 54 | RUN ["/bin/bash"] 55 | -------------------------------------------------------------------------------- /resize.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from osgeo import gdal,osr 3 | import cv2 4 | import tensorflow as tf 5 | 6 | 7 | 8 | flags = tf.app.flags 9 | FLAGS = flags.FLAGS 10 | flags.DEFINE_float('zooming', 4.0, 'Amount to rescale original image.') 11 | flags.DEFINE_string('input_image','in.tif','Input image.') 12 | flags.DEFINE_string('output_image','out.tif','Output image.') 13 | 14 | # open training data and compute initial cost function averaged over the entire image 15 | ds = gdal.Open(FLAGS.input_image) 16 | im_raw = np.swapaxes(np.swapaxes(ds.ReadAsArray(),0,1), 1,2) 17 | im_small = cv2.resize(im_raw, (int(im_raw.shape[1]/FLAGS.zooming), int(im_raw.shape[0]/FLAGS.zooming))) 18 | im_blur = np.round(cv2.resize(im_small, (im_raw.shape[1], im_raw.shape[0]))) 19 | 20 | numberOfBands = ds.RasterCount 21 | 22 | raster = im_blur 23 | driver = gdal.GetDriverByName('GTiff') 24 | geotransform = ds.GetGeoTransform() 25 | 26 | dataset = driver.Create( 27 | FLAGS.output_image, 28 | im_blur.shape[1], 29 | im_blur.shape[0], 30 | numberOfBands, 31 | ds.GetRasterBand(1).DataType,) 32 | dataset.SetGeoTransform(geotransform) 33 | datasetSRS = osr.SpatialReference() 34 | datasetSRS.ImportFromWkt(ds.GetProjectionRef()) 35 | dataset.SetProjection(datasetSRS.ExportToWkt()) 36 | for i in range(numberOfBands): 37 | outBand = dataset.GetRasterBand(i+1) 38 | outBand.WriteArray(raster[:,:,i]) #write ith-band to the raster 39 | dataset.FlushCache() # write to disk 40 | dataset = None 41 | 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /generate.network.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import random 3 | from osgeo import gdal 4 | import cv2 5 | import tensorflow as tf 6 | 7 | 8 | 9 | flags = tf.app.flags 10 | FLAGS = flags.FLAGS 11 | flags.DEFINE_float('zooming', 4.0, 'Amount to rescale original image.') 12 | flags.DEFINE_float('learning_rate', 0.0002, 'Initial learning rate for ADAM solver.') 13 | flags.DEFINE_integer('ws', 28, 'Window size for image clip.') 14 | flags.DEFINE_integer('filter_size', 9, 'Filter size for convolution layer.') 15 | flags.DEFINE_integer('filters', 32, 'Number of filters in convolution layer.') 16 | flags.DEFINE_integer('batch_size', 64, 'Mini-batch size.') 17 | flags.DEFINE_integer('max_runup_steps', 100001, 'Maximum number of steps with deconvolution tied to convolution.') 18 | flags.DEFINE_integer('max_layer_steps', 100001, 'Maximum number of steps per layer.') 19 | flags.DEFINE_integer('total_layers', 5, 'Number of perturbative layers in generative network.') 20 | flags.DEFINE_integer('gpu',0,'GPU index.') 21 | flags.DEFINE_bool('save',True,'Save output network') 22 | flags.DEFINE_integer('numberOfBands',3,'Number of bands in training image.') 23 | flags.DEFINE_float('delta',2.0,' Minimum dB improvement for new layer measured in PSNR.') 24 | flags.DEFINE_float('min_alpha',0.0001,'Minimum value of perturbative layer parameter.') 25 | flags.DEFINE_integer('layers_trained',0,'Number of layers previously trained.') 26 | flags.DEFINE_string('training_image','training_image.png','Training image.') 27 | flags.DEFINE_integer('precision',8,'Number of bits per bands.') 28 | flags.DEFINE_integer('convolutions_per_layer',2,'Number of convolutional layers in each perturbative layer.') 29 | 30 | 31 | cpu = "/cpu:0" 32 | gpu = "/gpu:"+str(FLAGS.gpu) 33 | prefix = str(FLAGS.numberOfBands)+'-band' 34 | numberOfBands = FLAGS.numberOfBands 35 | maxp = 2.0**(1.0*FLAGS.precision) - 1.0 36 | 37 | 38 | # Define the path for saving the neural network 39 | summary_name = prefix + "." +str(FLAGS.total_layers) +"." 40 | layer_name = './checkpoints/'+prefix+'/'+summary_name 41 | 42 | 43 | 44 | # open training data and compute initial cost function averaged over the entire image 45 | ds = gdal.Open(FLAGS.training_image) 46 | im_raw = np.swapaxes(np.swapaxes(ds.ReadAsArray(),0,1), 1,2) 47 | im_small = cv2.resize(im_raw, (int(im_raw.shape[1]/FLAGS.zooming), int(im_raw.shape[0]/FLAGS.zooming))) 48 | im_blur_cubic = cv2.resize(im_small, (im_raw.shape[1], im_raw.shape[0]), interpolation = cv2.INTER_CUBIC) 49 | im_blur = cv2.resize(im_small, (im_raw.shape[1], im_raw.shape[0])) 50 | initial_MSE = np.sum( np.square( (im_raw[:,:,0:numberOfBands]/maxp - im_blur[:,:,0:numberOfBands]/maxp) ) ) / (im_raw.shape[0] * im_raw.shape[1] * numberOfBands * 1.0 ) 51 | initial_PSNR = -10.0*np.log(initial_MSE)/np.log(10.0) 52 | 53 | 54 | 55 | 56 | 57 | 58 | # Define CosmiQNet 59 | # since the number of layers is determined at runtime, we initialize variables as arrays 60 | sr = range(FLAGS.total_layers) 61 | sr_cost = range(FLAGS.total_layers) 62 | optimizer_layer = range(FLAGS.total_layers) 63 | optimizer_all = range(FLAGS.total_layers) 64 | W = range(FLAGS.total_layers) 65 | Wo = range(FLAGS.total_layers) 66 | b = range(FLAGS.total_layers) 67 | bo = range(FLAGS.total_layers) 68 | conv = range(FLAGS.total_layers) 69 | inlayer = range(FLAGS.total_layers) 70 | outlayer = range(FLAGS.total_layers) 71 | alpha = range(FLAGS.total_layers) 72 | beta = range(FLAGS.total_layers) 73 | for i in range(FLAGS.total_layers): 74 | W[i] = range(FLAGS.convolutions_per_layer) 75 | b[i] = range(FLAGS.convolutions_per_layer) 76 | conv[i] = range(FLAGS.convolutions_per_layer) 77 | deconv = range(FLAGS.total_layers) 78 | MSE_sr = range(FLAGS.total_layers) 79 | PSNR_sr = range(FLAGS.total_layers) 80 | 81 | 82 | 83 | # The NN 84 | with tf.device(gpu): 85 | # Input is has numberOfBands for the pre-processed image and numberOfBands for the original image 86 | xy = tf.placeholder(tf.float32, shape=[None, FLAGS.ws, FLAGS.ws, 2*numberOfBands]) 87 | with tf.name_scope("split") as scope: 88 | x = tf.slice(xy, [0,0,0,0], [-1,-1,-1,numberOfBands]) # low res image 89 | y = tf.slice(xy, [0,0,0,numberOfBands], [-1,-1,-1,-1]) # high res image 90 | 91 | with tf.name_scope("initial_costs") as scope: 92 | # used as a measure of improvement not for optimization 93 | cost_initial = tf.reduce_sum ( tf.pow( x-y,2)) 94 | MSE_initial = cost_initial/(FLAGS.ws*FLAGS.ws*(1.0*numberOfBands)*FLAGS.batch_size) 95 | PSNR_initial = -10.0*tf.log(MSE_initial)/np.log(10.0) 96 | 97 | 98 | for i in range(FLAGS.total_layers): 99 | with tf.name_scope("layer"+str(i)) as scope: 100 | # alpha and beta are pertubation layer bypass parameters that determine a convex combination of a input layer and output layer 101 | alpha[i] = tf.Variable(0.1, name='alpha_'+str(i)) 102 | beta[i] = tf.maximum( FLAGS.min_alpha , tf.minimum ( 1.0 , alpha[i] ), name='beta_'+str(i)) 103 | if (0 == i) : 104 | inlayer[i] = x 105 | else : 106 | inlayer[i] = outlayer[i-1] 107 | # we build a list of variables to optimize per layer 108 | vars_layer = [alpha[i]] 109 | 110 | # Convolutional layers 111 | W[i][0] = tf.Variable(tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,numberOfBands,FLAGS.filters], stddev=0.1), name='W'+str(i)+'.'+str(0)) 112 | b[i][0] = tf.Variable(tf.constant(0.0,shape=[FLAGS.filters]), name='b'+str(i)+'.'+str(0)) 113 | conv[i][0] = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d( inlayer[i], W[i][0], strides=[1,1,1,1], padding='SAME'), b[i][0], name='conv'+str(i)+'.'+str(0))) 114 | for j in range(1,FLAGS.convolutions_per_layer): 115 | W[i][j] = tf.Variable(tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,FLAGS.filters,FLAGS.filters], stddev=0.1), name='W'+str(i)+'.'+str(j)) 116 | b[i][j] = tf.Variable(tf.constant(0.0,shape=[FLAGS.filters]), name='b'+str(i)+'.'+str(j)) 117 | vars_layer = vars_layer + [W[i][j],b[i][j]] 118 | conv[i][j] = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d( conv[i][j-1], W[i][j], strides=[1,1,1,1], padding='SAME'), b[i][j], name='conv'+str(i)+'.'+str(j))) 119 | 120 | # Deconvolutional layer 121 | Wo[i] = tf.Variable(tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,numberOfBands,FLAGS.filters], stddev=0.1), name='Wo'+str(i)) 122 | bo[i] = tf.Variable(tf.constant(0.0,shape=[FLAGS.filters]), name='bo'+str(i)) 123 | deconv[i] = tf.nn.relu( 124 | tf.nn.conv2d_transpose( 125 | tf.nn.bias_add( conv[i][FLAGS.convolutions_per_layer-1], bo[i]), Wo[i], [FLAGS.batch_size,FLAGS.ws,FLAGS.ws,numberOfBands] ,strides=[1,1,1,1], padding='SAME')) 126 | vars_layer = vars_layer + [Wo[i],bo[i]] 127 | 128 | # Convex combination of input and output layer 129 | outlayer[i] = tf.nn.relu( tf.add( tf.scalar_mul( beta[i] , deconv[i]), tf.scalar_mul(1.0-beta[i], inlayer[i]))) 130 | 131 | 132 | # sr is the super-resolution process. It really only has enhancement meaning during the current layer of training. 133 | sr[i] = tf.slice(outlayer[i],[0,0,0,0],[-1,-1,-1,numberOfBands]) 134 | # The cost funtion to optimize. This is not PSNR but monotonically related 135 | sr_cost[i] = tf.reduce_sum ( tf.pow( sr[i]-y,2)) 136 | MSE_sr[i] = sr_cost[i]/(FLAGS.ws*FLAGS.ws*numberOfBands*1.0*FLAGS.batch_size) 137 | PSNR_sr[i] = -10.0*tf.log(MSE_sr[i])/np.log(10.0) 138 | 139 | # ADAM optimizers seem to work well 140 | optimizer_layer[i] = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate).minimize(sr_cost[i], var_list=vars_layer) 141 | optimizer_all[i] = tf.train.AdamOptimizer(learning_rate=FLAGS.learning_rate).minimize(sr_cost[i]) 142 | ginit = tf.global_variables_initializer() 143 | gsaver = tf.train.Saver() 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | # define sampling functions as random areas of the larger image this could be preprocess in the future 153 | def GetRandomSubset( batch_size, im_raw, im_blur, ws): 154 | fullinput = np.zeros(( batch_size,ws,ws,2*numberOfBands), dtype=np.dtype(float)) 155 | for n in range ( batch_size ): 156 | i = random.randint( 0, im_raw.shape[0] - ws) 157 | j = random.randint( 0, im_raw.shape[1] - ws) 158 | fullinput[n,:,:,0:numberOfBands] = im_blur[i:i+ws,j:j+ws,0:numberOfBands] 159 | fullinput[n,:,:,numberOfBands:] = im_raw[i:i+ws,j:j+ws,0:numberOfBands] 160 | return fullinput/maxp 161 | 162 | def GetRandomSubset_cubic( batch_size, im_raw, im_blur, im_blur_cubic, ws): 163 | return GetRandomSubset( batch_size, im_raw, im_blur, ws), GetRandomSubset( batch_size, im_raw, im_blur_cubic, ws) 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | # Training strategy 175 | # The goal is to find a good starting point. This is more critical with more convolutional layers 176 | # Then we train a layer at a time 177 | # Then we train all previous layers 178 | 179 | with tf.Session(config=tf.ConfigProto(log_device_placement=False)) as sess: 180 | if FLAGS.layers_trained > 0 : 181 | print "restoring previously layers" 182 | gsaver.restore(sess, layer_name+str(FLAGS.layers_trained-1)) 183 | else: 184 | print "initializing variables" 185 | sess.run(ginit) 186 | 187 | global_step = 0 188 | for layer in range(FLAGS.layers_trained, FLAGS.total_layers): 189 | PSNReval = 0 190 | PSNReval_cubic = 0 191 | 192 | 193 | # Find a good start OR reroll the initial weights 194 | while PSNReval < PSNReval_cubic + FLAGS.delta: 195 | for step in range(FLAGS.max_runup_steps): 196 | global_step += 1 197 | random_subset = GetRandomSubset( FLAGS.batch_size, im_raw, im_blur, FLAGS.ws) 198 | sess.run(optimizer_layer[layer],feed_dict={xy: random_subset}) 199 | if 0 == step%100: 200 | random_subset, random_subset_cubic = GetRandomSubset_cubic( FLAGS.batch_size, im_raw, im_blur, im_blur_cubic, FLAGS.ws) 201 | PSNReval = PSNR_sr[layer].eval(feed_dict={xy: random_subset}) 202 | PSNReval_linear = PSNR_initial.eval(feed_dict={xy: random_subset}) 203 | PSNReval_cubic = PSNR_initial.eval(feed_dict={xy: random_subset_cubic}) 204 | print 'generative layer:', layer,step, '\tPSNR:', PSNReval-PSNReval_cubic, PSNReval-PSNReval_linear,PSNReval,initial_PSNR, beta[layer].eval() 205 | if PSNReval > PSNReval_cubic + FLAGS.delta: 206 | print "good start identity after %d step"%step 207 | break 208 | if step > FLAGS.max_runup_steps/10 or alpha[layer].eval() < FLAGS.min_alpha: 209 | print "restart layer" 210 | ra1 = W[layer][0].assign( tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,numberOfBands,FLAGS.filters], stddev=0.1), use_locking=True) 211 | ra2 = b[layer][0].assign(tf.constant(0.0,shape=[FLAGS.filters]), use_locking=True) 212 | sess.run([ra1,ra2]) 213 | for j in range(1,FLAGS.convolutions_per_layer): 214 | ra1 = W[layer][j].assign( tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,FLAGS.filters,FLAGS.filters], stddev=0.1), use_locking=True) 215 | ra2 = b[layer][j].assign(tf.constant(0.0,shape=[FLAGS.filters]), use_locking=True) 216 | sess.run([ra1,ra2]) 217 | ra3 = Wo[layer].assign(tf.truncated_normal([FLAGS.filter_size,FLAGS.filter_size,numberOfBands,FLAGS.filters], stddev=0.1), use_locking=True) 218 | ra4 = bo[layer].assign(tf.constant(0.0,shape=[FLAGS.filters]), use_locking=True) 219 | ra5 = alpha[layer].assign( 0.1) 220 | sess.run([ra3,ra4,ra5]) 221 | break 222 | 223 | # optimize one layer 224 | for step in range(FLAGS.max_layer_steps): 225 | global_step += 1 226 | random_subset = GetRandomSubset( FLAGS.batch_size, im_raw, im_blur, FLAGS.ws) 227 | sess.run(optimizer_layer[layer],feed_dict={xy: random_subset }) 228 | if 0 == step%100: 229 | random_subset, random_subset_cubic = GetRandomSubset_cubic( FLAGS.batch_size, im_raw, im_blur, im_blur_cubic, FLAGS.ws) 230 | PSNReval = PSNR_sr[layer].eval(feed_dict={xy: random_subset}) 231 | PSNReval_linear = PSNR_initial.eval(feed_dict={xy: random_subset}) 232 | PSNReval_cubic = PSNR_initial.eval(feed_dict={xy: random_subset_cubic}) 233 | print 'Optimize current layer:', layer,step, '\tPSNR:',PSNReval-PSNReval_cubic, PSNReval-PSNReval_linear,PSNReval,initial_PSNR, beta[layer].eval() 234 | for l in range(layer+1): 235 | print l,beta[l].eval(),PSNR_sr[l].eval(feed_dict={xy: random_subset}) 236 | # optimize all previous layers too 237 | for step in range(FLAGS.max_layer_steps): 238 | global_step += 1 239 | random_subset = GetRandomSubset( FLAGS.batch_size, im_raw, im_blur, FLAGS.ws) 240 | sess.run(optimizer_all[layer],feed_dict={xy: random_subset }) 241 | if 0 == step%100: 242 | random_subset, random_subset_cubic = GetRandomSubset_cubic( FLAGS.batch_size, im_raw, im_blur, im_blur_cubic, FLAGS.ws) 243 | PSNReval = PSNR_sr[layer].eval(feed_dict={xy: random_subset}) 244 | PSNReval_linear = PSNR_initial.eval(feed_dict={xy: random_subset}) 245 | PSNReval_cubic = PSNR_initial.eval(feed_dict={xy: random_subset_cubic}) 246 | print 'Optimize all previous layers:', layer,step, '\tPSNR:',PSNReval-PSNReval_cubic, PSNReval-PSNReval_linear,PSNReval,initial_PSNR, beta[layer].eval() 247 | for l in range(layer+1): 248 | print l,beta[l].eval(),PSNR_sr[l].eval(feed_dict={xy: random_subset}) 249 | if FLAGS.save: 250 | gsaver.save(sess, layer_name+str(layer)) 251 | if FLAGS.save: 252 | gsaver.save(sess, layer_name) 253 | sess.close() 254 | --------------------------------------------------------------------------------