├── LICENSE ├── README.md ├── demo ├── 1_results.gif ├── 2_results.gif └── 3_results.gif ├── test.lua ├── train.lua ├── trained_models ├── S2S_AR_cpu.t7 └── S2S_dil_AR_ft_cpu.t7 └── utils ├── dataset.lua ├── metrics.lua ├── model.lua └── utils.lua /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. Copyright and Similar Rights means copyright and/or similar rights 88 | closely related to copyright including, without limitation, 89 | performance, broadcast, sound recording, and Sui Generis Database 90 | Rights, without regard to how the rights are labeled or 91 | categorized. For purposes of this Public License, the rights 92 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 93 | Rights. 94 | d. Effective Technological Measures means those measures that, in the 95 | absence of proper authority, may not be circumvented under laws 96 | fulfilling obligations under Article 11 of the WIPO Copyright 97 | Treaty adopted on December 20, 1996, and/or similar international 98 | agreements. 99 | 100 | e. Exceptions and Limitations means fair use, fair dealing, and/or 101 | any other exception or limitation to Copyright and Similar Rights 102 | that applies to Your use of the Licensed Material. 103 | 104 | f. Licensed Material means the artistic or literary work, database, 105 | or other material to which the Licensor applied this Public 106 | License. 107 | 108 | g. Licensed Rights means the rights granted to You subject to the 109 | terms and conditions of this Public License, which are limited to 110 | all Copyright and Similar Rights that apply to Your use of the 111 | Licensed Material and that the Licensor has authority to license. 112 | 113 | h. Licensor means the individual(s) or entity(ies) granting rights 114 | under this Public License. 115 | 116 | i. NonCommercial means not primarily intended for or directed towards 117 | commercial advantage or monetary compensation. For purposes of 118 | this Public License, the exchange of the Licensed Material for 119 | other material subject to Copyright and Similar Rights by digital 120 | file-sharing or similar means is NonCommercial provided there is 121 | no payment of monetary compensation in connection with the 122 | exchange. 123 | 124 | j. Share means to provide material to the public by any means or 125 | process that requires permission under the Licensed Rights, such 126 | as reproduction, public display, public performance, distribution, 127 | dissemination, communication, or importation, and to make material 128 | available to the public including in ways that members of the 129 | public may access the material from a place and at a time 130 | individually chosen by them. 131 | 132 | k. Sui Generis Database Rights means rights other than copyright 133 | resulting from Directive 96/9/EC of the European Parliament and of 134 | the Council of 11 March 1996 on the legal protection of databases, 135 | as amended and/or succeeded, as well as other essentially 136 | equivalent rights anywhere in the world. 137 | 138 | l. You means the individual or entity exercising the Licensed Rights 139 | under this Public License. Your has a corresponding meaning. 140 | 141 | 142 | Section 2 -- Scope. 143 | 144 | a. License grant. 145 | 146 | 1. Subject to the terms and conditions of this Public License, 147 | the Licensor hereby grants You a worldwide, royalty-free, 148 | non-sublicensable, non-exclusive, irrevocable license to 149 | exercise the Licensed Rights in the Licensed Material to: 150 | 151 | a. reproduce and Share the Licensed Material, in whole or 152 | in part, for NonCommercial purposes only; and 153 | 154 | b. produce, reproduce, and Share Adapted Material for 155 | NonCommercial purposes only. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. No downstream restrictions. You may not offer or impose 186 | any additional or different terms or conditions on, or 187 | apply any Effective Technological Measures to, the 188 | Licensed Material if doing so restricts exercise of the 189 | Licensed Rights by any recipient of the Licensed 190 | Material. 191 | 192 | 6. No endorsement. Nothing in this Public License constitutes or 193 | may be construed as permission to assert or imply that You 194 | are, or that Your use of the Licensed Material is, connected 195 | with, or sponsored, endorsed, or granted official status by, 196 | the Licensor or others designated to receive attribution as 197 | provided in Section 3(a)(1)(A)(i). 198 | 199 | b. Other rights. 200 | 201 | 1. Moral rights, such as the right of integrity, are not 202 | licensed under this Public License, nor are publicity, 203 | privacy, and/or other similar personality rights; however, to 204 | the extent possible, the Licensor waives and/or agrees not to 205 | assert any such rights held by the Licensor to the limited 206 | extent necessary to allow You to exercise the Licensed 207 | Rights, but not otherwise. 208 | 209 | 2. Patent and trademark rights are not licensed under this 210 | Public License. 211 | 212 | 3. To the extent possible, the Licensor waives any right to 213 | collect royalties from You for the exercise of the Licensed 214 | Rights, whether directly or through a collecting society 215 | under any voluntary or waivable statutory or compulsory 216 | licensing scheme. In all other cases the Licensor expressly 217 | reserves any right to collect such royalties, including when 218 | the Licensed Material is used other than for NonCommercial 219 | purposes. 220 | 221 | 222 | Section 3 -- License Conditions. 223 | 224 | Your exercise of the Licensed Rights is expressly made subject to the 225 | following conditions. 226 | 227 | a. Attribution. 228 | 229 | 1. If You Share the Licensed Material (including in modified 230 | form), You must: 231 | 232 | a. retain the following if it is supplied by the Licensor 233 | with the Licensed Material: 234 | 235 | i. identification of the creator(s) of the Licensed 236 | Material and any others designated to receive 237 | attribution, in any reasonable manner requested by 238 | the Licensor (including by pseudonym if 239 | designated); 240 | 241 | ii. a copyright notice; 242 | 243 | iii. a notice that refers to this Public License; 244 | 245 | iv. a notice that refers to the disclaimer of 246 | warranties; 247 | 248 | v. a URI or hyperlink to the Licensed Material to the 249 | extent reasonably practicable; 250 | 251 | b. indicate if You modified the Licensed Material and 252 | retain an indication of any previous modifications; and 253 | 254 | c. indicate the Licensed Material is licensed under this 255 | Public License, and include the text of, or the URI or 256 | hyperlink to, this Public License. 257 | 258 | 2. You may satisfy the conditions in Section 3(a)(1) in any 259 | reasonable manner based on the medium, means, and context in 260 | which You Share the Licensed Material. For example, it may be 261 | reasonable to satisfy the conditions by providing a URI or 262 | hyperlink to a resource that includes the required 263 | information. 264 | 265 | 3. If requested by the Licensor, You must remove any of the 266 | information required by Section 3(a)(1)(A) to the extent 267 | reasonably practicable. 268 | 269 | 4. If You Share Adapted Material You produce, the Adapter's 270 | License You apply must not prevent recipients of the Adapted 271 | Material from complying with this Public License. 272 | 273 | 274 | Section 4 -- Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that 277 | apply to Your use of the Licensed Material: 278 | 279 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 280 | to extract, reuse, reproduce, and Share all or a substantial 281 | portion of the contents of the database for NonCommercial purposes 282 | only; 283 | 284 | b. if You include all or a substantial portion of the database 285 | contents in a database in which You have Sui Generis Database 286 | Rights, then the database in which You have Sui Generis Database 287 | Rights (but not its individual contents) is Adapted Material; and 288 | 289 | c. You must comply with the conditions in Section 3(a) if You Share 290 | all or a substantial portion of the contents of the database. 291 | 292 | For the avoidance of doubt, this Section 4 supplements and does not 293 | replace Your obligations under this Public License where the Licensed 294 | Rights include other Copyright and Similar Rights. 295 | 296 | 297 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 298 | 299 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 300 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 301 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 302 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 303 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 304 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 305 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 306 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 307 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 308 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 309 | 310 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 311 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 312 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 313 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 314 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 315 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 316 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 317 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 318 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 319 | 320 | c. The disclaimer of warranties and limitation of liability provided 321 | above shall be interpreted in a manner that, to the extent 322 | possible, most closely approximates an absolute disclaimer and 323 | waiver of all liability. 324 | 325 | 326 | Section 6 -- Term and Termination. 327 | 328 | a. This Public License applies for the term of the Copyright and 329 | Similar Rights licensed here. However, if You fail to comply with 330 | this Public License, then Your rights under this Public License 331 | terminate automatically. 332 | 333 | b. Where Your right to use the Licensed Material has terminated under 334 | Section 6(a), it reinstates: 335 | 336 | 1. automatically as of the date the violation is cured, provided 337 | it is cured within 30 days of Your discovery of the 338 | violation; or 339 | 340 | 2. upon express reinstatement by the Licensor. 341 | 342 | For the avoidance of doubt, this Section 6(b) does not affect any 343 | right the Licensor may have to seek remedies for Your violations 344 | of this Public License. 345 | 346 | c. For the avoidance of doubt, the Licensor may also offer the 347 | Licensed Material under separate terms or conditions or stop 348 | distributing the Licensed Material at any time; however, doing so 349 | will not terminate this Public License. 350 | 351 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 352 | License. 353 | 354 | 355 | Section 7 -- Other Terms and Conditions. 356 | 357 | a. The Licensor shall not be bound by any additional or different 358 | terms or conditions communicated by You unless expressly agreed. 359 | 360 | b. Any arrangements, understandings, or agreements regarding the 361 | Licensed Material not stated herein are separate from and 362 | independent of the terms and conditions of this Public License. 363 | 364 | 365 | Section 8 -- Interpretation. 366 | 367 | a. For the avoidance of doubt, this Public License does not, and 368 | shall not be interpreted to, reduce, limit, restrict, or impose 369 | conditions on any use of the Licensed Material that could lawfully 370 | be made without permission under this Public License. 371 | 372 | b. To the extent possible, if any provision of this Public License is 373 | deemed unenforceable, it shall be automatically reformed to the 374 | minimum extent necessary to make it enforceable. If the provision 375 | cannot be reformed, it shall be severed from this Public License 376 | without affecting the enforceability of the remaining terms and 377 | conditions. 378 | 379 | c. No term or condition of this Public License will be waived and no 380 | failure to comply consented to unless expressly agreed to by the 381 | Licensor. 382 | 383 | d. Nothing in this Public License constitutes or may be interpreted 384 | as a limitation upon, or waiver of, any privileges and immunities 385 | that apply to the Licensor or You, including from the legal 386 | processes of any jurisdiction or authority. 387 | 388 | ======================================================================= 389 | 390 | Creative Commons is not a party to its public 391 | licenses. Notwithstanding, Creative Commons may elect to apply one of 392 | its public licenses to material it publishes and in those instances 393 | will be considered the “Licensor.” The text of the Creative Commons 394 | public licenses is dedicated to the public domain under the CC0 Public 395 | Domain Dedication. Except for the limited purpose of indicating that 396 | material is shared under a Creative Commons public license or as 397 | otherwise permitted by the Creative Commons policies published at 398 | creativecommons.org/policies, Creative Commons does not authorize the 399 | use of the trademark "Creative Commons" or any other trademark or logo 400 | of Creative Commons without its prior written consent including, 401 | without limitation, in connection with any unauthorized modifications 402 | to any of its public licenses or any other arrangements, 403 | understandings, or agreements concerning use of licensed material. For 404 | the avoidance of doubt, this paragraph does not form part of the 405 | public licenses. 406 | 407 | Creative Commons may be contacted at creativecommons.org. 408 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NextSegmPredICCV17 2 | This repository contains an implementation of the following paper: 3 | 4 | Pauline Luc*, Natalia Neverova*, Camille Couprie, Jakob Verbeek, Yann LeCun, [Predicting Deeper into the Future of Semantic Segmentation](https://arxiv.org/abs/1703.07684). ICCV, 2017. 5 | 6 | It reproduces the results obtained with the S2S (segmentation to segmentation) model described in the paper (shown below). Frames with no border correspond to the input while red borders indicate predicted frames. 7 | 8 | ![sample 1](demo/1_results.gif) 9 | ![sample 2](demo/2_results.gif) 10 | ![sample 3](demo/3_results.gif)
11 | 12 | To run the code, you will need to install lua torch and the following torch packages: cutorch, cunn, cudnn, nnx, nngraph, paths, display, torchnet. 13 | 14 | ### Training/validation data 15 | [Download data](https://dl.fbaipublicfiles.com/segmpred/sample_data.zip) and save in the "Data" directory. It contains soft segmentations produced by the Dilation10 network applied to the Cityscapes dataset and has two subdirectories: 16 | - **train** contains 99 sample training batches of 4 sequences x 5 frames (4 inputs + 1 target) x 64 x 64. Please note that this is only a small part of the whole training set, provided for the reference, and it is not sufficient for training the network from scratch; 17 | - **val** contains 500 test sequences from Cityscapes: 125 batches of 4 sequences x 7 frames (4 inputs + 3 targets) x 256 x 128 (contains both RGB images and their segmentations). 18 | 19 | ### Pretrained models 20 | We provide two pretrained models described in the paper: model S2S, AR (trained_models/S2S_AR_cpu.t7) and model S2S-dil, AR, fine-tune (trained_models/S2S_dil_AR_ft_cpu.t7) giving the following results on the cityscapes validation dataset (set nRecFrames to 0 for short term and to 2 for midterm predictions): 21 | 22 | | Method | Short term IoU SEG | Mid term IoU SEG | 23 | | ------ | ------------------ | ------------- | 24 | | Model S2S, AR | 63.53 | 47.23 | 25 | | Model S2S-dil, AR, fine-tune | 65.30 | 50.42 | 26 | 27 | 28 | ### Train/Test scripts 29 | 30 | - **train.lua** - training script allowing to train the "S2S, AR" from scratch on a provided subset of training batches; 31 | - **test.lua** - test script reproducing model performance on the validation set. 32 | The same script with the "--save" option allows to dump obtained results on the disk and create gif animations. 33 | 34 | ### Bibtex 35 | 36 | If you find this code useful in your research then please cite: 37 | 38 | ``` 39 | @article{NextSegmPredICCV17, 40 | title={Predicting Deeper into the Future of Semantic Segmentation}, 41 | author={Luc, Pauline and Neverova, Natalia and Couprie, Camille and Verbeek, Jacob and LeCun, Yann}, 42 | journal={ICCV}, 43 | year={2017} 44 | } 45 | ``` 46 | 47 | ### Contact 48 | For all questions and comments, please contact us at [paulineluc, nneverova or coupriec]@fb.com. 49 | -------------------------------------------------------------------------------- /demo/1_results.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/SegmPred/e0c7a8775bb3bc728199c7fa7237ea346ce99110/demo/1_results.gif -------------------------------------------------------------------------------- /demo/2_results.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/SegmPred/e0c7a8775bb3bc728199c7fa7237ea346ce99110/demo/2_results.gif -------------------------------------------------------------------------------- /demo/3_results.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/SegmPred/e0c7a8775bb3bc728199c7fa7237ea346ce99110/demo/3_results.gif -------------------------------------------------------------------------------- /test.lua: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- 2 | -- Testing a multiscale convnet to predict next frame from some previous images 3 | -- and semantic segmentations 4 | -- Written by Camille Couprie, Pauline Luc, Natalia Neverova 5 | -------------------------------------------------------------------------------- 6 | -- Copyright 2017-present, Facebook, Inc. 7 | -- All rights reserved. 8 | -- This source code is licensed under the license found in the 9 | -- LICENSE file in the root directory of this source tree. 10 | 11 | require 'torch' 12 | require 'cutorch' 13 | require 'cunn' 14 | require 'cudnn' 15 | require 'nngraph' 16 | require 'paths' 17 | local display = require 'display' 18 | local tnt = require 'torchnet' 19 | paths.dofile('utils/metrics.lua') 20 | paths.dofile('utils/dataset.lua') 21 | paths.dofile('utils/utils.lua') 22 | 23 | -- set options ----------------------------------------------------------------- 24 | local cmd = torch.CmdLine() 25 | cmd:option('--modelID', 'AR_dil_ft', 'AR_dil_ft or AR') 26 | cmd:option('--nRecFrames', 0, 'N of recurrent frames (0 short term, 2 midterm)') 27 | cmd:option('--save', false, 'saving generated predictions') 28 | cmd:option('--saveDir', 'results', 'directory for exporting predictions') 29 | cmd:option('--dataDir', 'Data/', 'directory with the dataset') 30 | cmd:option('--nseq', 0, 'amount of test sequences (0 - all in Data/val/)') 31 | cmd:option('--delaygif', 50, 'speed of the generated animation') 32 | local opttest = cmd:parse(arg) 33 | print('Running with test options:', opttest) 34 | 35 | -- load and set model parameters ----------------------------------------------- 36 | modelPaths = {} 37 | modelPaths['AR_dil_ft'] = 'trained_models/S2S_dil_AR_ft_cpu.t7' 38 | modelPaths['AR'] = 'trained_models/S2S_AR_cpu.t7' 39 | if modelPaths[opttest.modelID]==nil then 40 | modelPaths[opttest.modelID] = opttest.modelID 41 | end 42 | print('Loading a pretrained model from ' .. modelPaths[opttest.modelID]) 43 | assert(paths.filep(modelPaths[opttest.modelID]), "Pretrained model not found") 44 | local loaded = torch.load(modelPaths[opttest.modelID]) 45 | opt = loaded.opt 46 | for k,v in pairs(opttest) do opt[k] = opttest[k] end 47 | opt.nTargetFrames = 1 48 | opt.datasetFrameRate = 3 49 | print('Input frames: ' .. opt.nInputFrames) 50 | print('Target frames: ' .. opt.nTargetFrames) 51 | print('Recurrent steps ' .. opt.nRecFrames) 52 | 53 | -- load and check the data ----------------------------------------------------- 54 | local batchList = getNBatches(opt.dataDir,'val') 55 | if opt.nseq == 0 then opt.nseq = #batchList end 56 | assert(opt.nseq<=#batchList and opt.nseq>0, 57 | "Found "..#batchList.." batches out of "..opt.nseq) 58 | print('Number of test sequences: ' .. opt.nseq) 59 | 60 | -- create directories ---------------------------------------------------------- 61 | if opt.save and paths.filep(opt.saveDir) or paths.dirp(opt.saveDir) then 62 | if paths.dirp(opt.saveDir .. '.bkp') then 63 | os.execute('sudo rm -R ' .. opt.saveDir .. '.bkp') 64 | end 65 | os.execute('sudo mv ' .. opt.saveDir .. ' ' .. opt.saveDir .. '.bkp') 66 | print('Copied existing '..opt.saveDir..' into '..opt.saveDir..'.bkp') 67 | end 68 | 69 | -- load the model -------------------------------------------------------------- 70 | paths.dofile('utils/model.lua') 71 | local model = loaded.generator:cuda() 72 | local preprocessInput = getPyrPreprocessor(opt) 73 | 74 | -- allocate variables ---------------------------------------------------------- 75 | local ob = opt.batchSize 76 | local tf = opt.nTargetFrames 77 | local inpf = opt.nInputFrames 78 | local rf = opt.nRecFrames 79 | 80 | local confusion = tnt.SemSegmMeter{classes = classes, skipClass = 20} 81 | local segmInputE = torch.CudaTensor(ob, inpf, nclasses, oh, ow) 82 | local predS = torch.CudaTensor(ob, rf + 1, nclasses * tf, oh, ow):fill(0) 83 | local sinputF, spredF, inputF 84 | 85 | for jt = 1,#batchList do -- iterating over batches 86 | xlua.progress(jt, opt.nseq) 87 | local frames, segmE = getBatch(batchList[jt]) -- loading new batch 88 | local inputF = frames[{{},{1,inpf}}]:clone():view(ob, inpf, oc, oh, ow) 89 | local framesTarget = frames[{{},{inpf + 1, inpf + tf + rf}}]:clone() 90 | 91 | local sinputF = squeeze_segm_map(segmE[{{},{1,inpf}}]:clone(),nclasses,ob,oh,ow) 92 | local segmTargetE = segmE[{{},{inpf + 1, inpf + tf + rf}}]:clone() 93 | segmTargetE:resize(ob, (tf + rf) * nclasses, oh, ow) 94 | local segmTarget = squeeze_segm_map(segmTargetE, nclasses, ob, oh, ow):cuda() 95 | 96 | for k = 1, rf+1 do -- autoregressive inference 97 | if k1 then 99 | segmInputE[{{},{math.max(inpf-k+2,1),inpf}}] = predS[{{},{math.max(k-inpf-1,1),k-1}}] 100 | end 101 | local input = preprocessInput:forward(resize_batch(segmInputE):cuda()) 102 | if #input<2 then input[2] = input[1] end 103 | local pred = model:forward(input) 104 | if type(pred)=='table' then pred = pred[opt.nscales] end 105 | predS[{{},k}] = pred[{{},{1,nclasses}}]:clone() 106 | end 107 | 108 | -- assess quality ----------------------------------------------------------- 109 | local targetF = framesTarget:view(ob, tf+rf, oc, oh, ow) 110 | local stargetF = segmTarget:view(ob, tf+rf, 1, oh, ow) 111 | local spredF = squeeze_segm_map(predS:double(),nclasses,ob,oh,ow) 112 | spredF = spredF:view(ob, tf+rf, 1, oh, ow) 113 | for i = 1,ob do confusion:add(spredF[i][tf+rf][1],stargetF[i][tf+rf][1]) end 114 | 115 | -- dump predictions ---------------------------------------------------------- 116 | if opt.save then 117 | local filename_out = opt.saveDir .. '/' .. jt 118 | os.execute('sudo mkdir -p ' .. filename_out) 119 | os.execute('sudo chmod 777 ' .. filename_out) 120 | display_segm(sinputF, 0, (filename_out..'/spred'), inputF, colormap) 121 | display_segm(spredF, inpf, (filename_out..'/spred'), targetF, colormap, true) 122 | os.execute('sudo convert $(for ((a=1; a<='..(inpf + tf + rf).. 123 | '; a++)); do printf -- "-delay '..opt.delaygif..' '..filename_out.. 124 | '/spred_%s.png " $a; done;) '..filename_out..'/results.gif') 125 | end 126 | end 127 | 128 | print('========== PERFORMANCE: ALL CLASSES ==========') 129 | print('IoU SEG ' ..' = ' ..confusion:value('map')..' ' 130 | ..'; per class acc. SEG = '..confusion:value('pc') 131 | ..'; per pixel acc. SEG = '..confusion:value('pp')) 132 | print('========== PERFORMANCE: MOVING OBJECTS ==========') 133 | print('IoU SEG ' ..' = ' ..confusion:valueOver('iou', movingObjects)..' ' 134 | ..'; per class acc. SEG = '..confusion:valueOver('pc', movingObjects) 135 | ..'; per pixel acc. SEG = '..confusion:valueOver('pp', movingObjects)) 136 | -------------------------------------------------------------------------------- /train.lua: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- 2 | -- Training a multiscale convnet to predict next frame from some previous images 3 | -- and semantic segmentations 4 | -- Written by Camille Couprie, Pauline Luc, Natalia Neverova 5 | -------------------------------------------------------------------------------- 6 | -- Copyright 2017-present, Facebook, Inc. 7 | -- All rights reserved. 8 | -- This source code is licensed under the license found in the 9 | -- LICENSE file in the root directory of this source tree. 10 | 11 | require 'torch' 12 | require 'optim' 13 | require 'cutorch' 14 | require 'cunn' 15 | require 'cudnn' 16 | require 'nngraph' 17 | require 'paths' 18 | local display = require 'display' 19 | local tnt = require 'torchnet' 20 | paths.dofile('utils/metrics.lua') 21 | paths.dofile('utils/dataset.lua') 22 | paths.dofile('utils/utils.lua') 23 | 24 | -- setting options ------------------------------------------------------------- 25 | local cmd = torch.CmdLine() 26 | cmd:option('--devid', 1, 'GPU id') 27 | cmd:option('--saveDir','saves','Directory to save the data') 28 | cmd:option('--dataDir','Data/', 'dataset path') 29 | cmd:option('--optim', 'sgd', 'Optim scheme') 30 | cmd:option('--nEpoches', 5000, 'Number of epoches') 31 | cmd:option('--nIters', 1000, 'Number of training iterations per epoch') 32 | cmd:option('--nItersTest', 25, 'Number of testing iterations per epoch') 33 | cmd:option('--lr', 0.01, 'Learning rate of the frame generator') 34 | cmd:option('--batchSize', 4, 'Minibatch size') 35 | cmd:option('--nInputFrames', 4, 'Number of input frames (excluding prediction)') 36 | cmd:option('--nTargetFrames', 1, 'Number of predicted frames') 37 | cmd:option('--hInput', 64, 'Frame height') 38 | cmd:option('--wInput', 64, 'Frame width') 39 | cmd:option('--crit', 'gdll1', 'loss : Abs, MSE, GDL, gdll1, SpatialClassNLL') 40 | cmd:option('--saveFreq', 40, 'saving after this number of iterations') 41 | opt = cmd:parse(arg) 42 | print('Running with training options:', opt) 43 | 44 | opt.modelConfig = {learningRate = opt.lr} 45 | opt.nscales = 2 46 | opt.segm = 1 47 | torch.setnumthreads(1) 48 | torch.manualSeed(1) 49 | cutorch.setDevice(opt.devid) 50 | 51 | if paths.filep(opt.saveDir) or paths.dirp(opt.saveDir) then 52 | os.execute('rm -r ' .. opt.saveDir .. '.bkp') 53 | os.execute('mv ' .. opt.saveDir .. ' ' .. opt.saveDir .. '.bkp') 54 | print('Copied existing '..opt.saveDir..' into '..opt.saveDir..'.bkp') 55 | end 56 | os.execute('mkdir -p ' .. opt.saveDir) 57 | 58 | opt.nChannels = nclasses 59 | opt.nclasses = nclasses 60 | 61 | local trainBatchList = getNBatches(opt.dataDir,'train') 62 | local valBatchList = getNBatches(opt.dataDir,'val') 63 | if opt.nItersTest>#valBatchList then 64 | print('Only '..#valBatchList..' test batches available') 65 | end 66 | if opt.nItersTest==0 then opt.nItersTest=#valBatchList end 67 | print('Training on '..#trainBatchList..' batches') 68 | print('Validation on '..#valBatchList..' batches') 69 | 70 | -- creating the model ---------------------------------------------------------- 71 | paths.dofile("utils/model.lua") 72 | local model = getPyrModel(opt) 73 | local preprocessInput = getPyrPreprocessor(opt) 74 | local preprocessTarget = getPyrPreprocessor(opt) 75 | local modelW, modelDW = model:getParameters() 76 | 77 | -- defining the loss ----------------------------------------------------------- 78 | local lossPixel = nn.ParallelCriterion() 79 | for i = 1, opt.nscales do 80 | if not opt.crit=='gdll1' then 81 | lossPixel:add(nn[opt.crit .. 'Criterion']()) 82 | else 83 | local crit = nn.MultiCriterion() 84 | lossPixel:add(crit:add(nn.AbsCriterion(),1):add(nn.GDLCriterion(1))) 85 | end 86 | end 87 | lossPixel:cuda() 88 | 89 | -- shortcuts ------------------------------------------------------------------- 90 | local ob = opt.batchSize 91 | local tf = opt.nTargetFrames 92 | local inpf = opt.nInputFrames 93 | local hi, wi = opt.hInput, opt.wInput 94 | local ch = opt.nChannels 95 | local confusion = tnt.SemSegmMeter{classes = classes} 96 | 97 | -- basic routines -------------------------------------------------------------- 98 | function getBatch(set, iIter) 99 | if set == 'train' then iIter = math.random(1, #trainBatchList) end 100 | local sample = torch.load(paths.concat(opt.dataDir, set, 'batch_'..iIter..'.t7')) 101 | local segmInputE, segmTargetE 102 | if set == 'train' then 103 | segmInputE = sample.R8s[{{},{1,inpf}}]:cuda() 104 | segmTargetE = sample.R8s[{{},{inpf+1,inpf+tf}}]:cuda() 105 | else 106 | local RGBs = sample.RGBs 107 | local h = math.random(1, oh-hi) 108 | local w = math.random(1, ow-wi) 109 | segmInputE = sample.R8s[{{},{1,inpf},{},{h, h+hi-1},{w,w+wi-1}}]:cuda() 110 | segmTargetE = sample.R8s[{{},{inpf+1, inpf+tf},{},{h, h+hi-1},{w,w+wi-1}}]:cuda() 111 | end 112 | segmTargetE:resize(ob, tf*ch, wi, hi) 113 | segmInputE:resize(ob, inpf*ch, wi, hi) 114 | return preprocessInput:forward(segmInputE), preprocessTarget:forward(segmTargetE) 115 | end 116 | 117 | function training(iIter) 118 | local input, target = getBatch('train', iIter) 119 | local err = 0 120 | local feval = function(x) 121 | assert(x == modelW) 122 | model:zeroGradParameters() 123 | local output = model:forward(input) 124 | local l2err = lossPixel:forward(output, target) 125 | derr_dpred = lossPixel:backward(output, target) 126 | model:backward(input,derr_dpred) 127 | err = l2err 128 | return l2err, modelDW 129 | end 130 | optim.sgd(feval, modelW, opt.modelConfig, modelState) 131 | return err 132 | end 133 | 134 | function testing(iEpoch) 135 | confusion:reset() 136 | for j = 1, opt.nItersTest do 137 | xlua.progress(j, opt.nItersTest) 138 | local input, target = getBatch('val', j) 139 | local pred = model:forward(input) 140 | 141 | local spredF = squeeze_segm_map(pred[opt.nscales]:clone(),opt.nclasses,ob,hi,wi) 142 | spredF = spredF:view(ob, tf, 1, hi, wi) 143 | local stargetF = squeeze_segm_map(target[opt.nscales]:clone(),opt.nclasses,ob,hi,wi) 144 | stargetF = stargetF:view(ob, tf, 1, hi, wi) 145 | for i = 1,ob do 146 | confusion:add(spredF[i][1][1], stargetF[i][1][1]) 147 | end 148 | end 149 | end 150 | 151 | -- main training loop ---------------------------------------------------------- 152 | for iEpoch = 1, opt.nEpoches do 153 | local sumGenErr = 0 154 | for iIter = 1, opt.nIters do 155 | xlua.progress(iIter, opt.nIters) 156 | sumGenErr = sumGenErr + training(iIter) 157 | end 158 | local avgGenErr = sumGenErr / (opt.nIters * opt.batchSize) 159 | print("Epoch "..iEpoch..'/'..opt.nEpoches.."; Generator error = ".. avgGenErr) 160 | torch.save(paths.concat(opt.saveDir,'model.t7'),{generator=model, opt=opt}) 161 | if iEpoch % opt.saveFreq == 0 then 162 | print('Saving the model...') 163 | model:clearState() 164 | torch.save(paths.concat(opt.saveDir, 'model_'..iEpoch..'epochs.t7'), 165 | {generator=model, opt=opt}) 166 | collectgarbage() 167 | end 168 | testing(iEpoch) 169 | print('Validation [IoU] '..confusion:value('map')) 170 | end 171 | -------------------------------------------------------------------------------- /trained_models/S2S_AR_cpu.t7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/SegmPred/e0c7a8775bb3bc728199c7fa7237ea346ce99110/trained_models/S2S_AR_cpu.t7 -------------------------------------------------------------------------------- /trained_models/S2S_dil_AR_ft_cpu.t7: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/facebookresearch/SegmPred/e0c7a8775bb3bc728199c7fa7237ea346ce99110/trained_models/S2S_dil_AR_ft_cpu.t7 -------------------------------------------------------------------------------- /utils/dataset.lua: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- 2 | -- Parameters of the preprocessed Cityscapes dataset 3 | -- Written by Camille Couprie, Pauline Luc, Natalia Neverova 4 | -------------------------------------------------------------------------------- 5 | -- Copyright 2017-present, Facebook, Inc. 6 | -- All rights reserved. 7 | -- This source code is licensed under the license found in the 8 | -- LICENSE file in the root directory of this source tree. 9 | 10 | classes = {'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 11 | 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 12 | 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 13 | 'bicycle', 'unlabeled'} 14 | 15 | nclasses = #classes-1 16 | 17 | colormap = {[1] = {0.5, 0.25, 0.5}, -- road 18 | [2] = {0.95, 0.14, 0.91}, -- sidewalk 19 | [3] = {0.27, 0.27, 0.27}, -- building 20 | [4] = {0.4, 0.4, 0.61}, -- wall 21 | [5] = {0.745, 0.6, 0.6}, -- fence 22 | [6] = {0.6, 0.6, 0.6}, -- pole 23 | [7] = {0.98, 0.66, 0.11}, -- traffic light 24 | [8] = {0.86, 0.86, 0}, -- traffic sign 25 | [9] = {0.41, 0.55, 0.14}, -- vegetation 26 | [10] = {0.59, 0.98, 0.59}, -- terrain 27 | [11] = {0.27, 0.51, 0.71}, -- sky 28 | [12] = {0.86, 0.27, 0.23}, -- person 29 | [13] = {1, 0, 0}, -- rider 30 | [14] = {0, 0, 0.55}, -- car 31 | [15] = {0, 0, 0.27}, -- truck 32 | [16] = {0, 0.55, 0.39}, -- bus 33 | [17] = {0, 0.31, 0.39}, -- train 34 | [18] = {0, 0, 0.9}, -- motorcycle 35 | [19] = {0.46, 0.04, 0.13}, -- bicycle 36 | [20] = {0, 0, 0}} -- unevaluated 37 | 38 | movingObjects = {12, 13, 14, 15, 16, 17, 18, 19} 39 | 40 | oh, ow, oc = 128, 256, 3 41 | -------------------------------------------------------------------------------- /utils/metrics.lua: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- 2 | -- Evaluation metrics 3 | -- Written by Camille Couprie, Pauline Luc, Natalia Neverova 4 | -------------------------------------------------------------------------------- 5 | -- Copyright 2017-present, Facebook, Inc. 6 | -- All rights reserved. 7 | -- This source code is licensed under the license found in the 8 | -- LICENSE file in the root directory of this source tree. 9 | 10 | require 'optim' 11 | local tnt = require 'torchnet' 12 | local argcheck = require 'argcheck' 13 | require 'sys' 14 | local SemSegmMeter = torch.class('tnt.SemSegmMeter','tnt.Meter',tnt) 15 | 16 | 17 | SemSegmMeter.__init = argcheck{ 18 | noordered = true, 19 | {name='self', type='tnt.SemSegmMeter'}, 20 | {name='classes', type='table'}, 21 | {name='skipClass', type='number', opt=true}, 22 | {name='movingobject', type='number', opt=true}, 23 | call = 24 | function(self, classes, skipClass, movingobject) 25 | self.classes = classes 26 | self.conf = optim.ConfusionMatrix(#self.classes) 27 | if movingobject then 28 | self.movingobject = true 29 | end 30 | if skipClass then 31 | self.sc = skipClass 32 | end 33 | self:reset() 34 | end 35 | } 36 | 37 | 38 | SemSegmMeter.reset = argcheck{ 39 | {name="self", type="tnt.SemSegmMeter"}, 40 | call = function(self) 41 | self.conf:zero() 42 | end 43 | } 44 | 45 | 46 | SemSegmMeter.add = argcheck{ 47 | {name="self", type="tnt.SemSegmMeter"}, 48 | {name="output", type="torch.*Tensor"}, 49 | {name="target", type="torch.*Tensor"}, 50 | call = 51 | function(self, output, target) 52 | if output:dim()==2 and target:dim()==2 then 53 | output = output:reshape(1, output:size(1), output:size(2)):long() 54 | target = target:reshape(1, target:size(1), target:size(2)) 55 | end 56 | 57 | target = target:squeeze() 58 | output = output:squeeze() 59 | 60 | if type(output) == 'number' then 61 | print(output) 62 | print(target) 63 | self.conf:add(output, target) 64 | else 65 | assert(output:nElement() == target:nElement(), 66 | 'target and output do not match') 67 | 68 | local N = output:nElement() 69 | output, target = output:view(N):view(-1,1), target:view(N):view(-1,1) 70 | 71 | local C = #self.classes 72 | local Mout, Mtar 73 | if torch.type(output)== 'torch.CudaLongTensor' then 74 | Mout = torch.CudaTensor(N, C):zero() 75 | Mtar = torch.CudaTensor(N, C):zero() 76 | else 77 | Mout = torch.Tensor(N, C):type(output:type()):zero() 78 | Mtar = torch.Tensor(N, C):long():zero() 79 | target = target:long() 80 | end 81 | Mout:scatter(2, output, 1) 82 | Mtar:scatter(2, target, 1) 83 | Mtar = Mtar:transpose(1,2) 84 | -- multiply and add to mc 85 | local tmp 86 | -- Avoid transferring to GPU 87 | if torch.type(output)== 'torch.CudaLongTensor' then 88 | tmp = torch.CudaTensor(C,C):zero() 89 | else 90 | tmp = torch.Tensor(C, C):type(Mout:type()):zero() 91 | end 92 | tmp:mm(Mtar, Mout) 93 | if self.movingobject then 94 | for i=1, 11 do 95 | tmp[i]:fill(0) 96 | end 97 | end 98 | if self.sc then tmp[self.sc]:fill(0) end 99 | tmp = tmp:type(self.conf.mat:type()) 100 | 101 | self.conf.mat:add(tmp:contiguous()) 102 | local saveMC = optim.ConfusionMatrix(#self.classes) 103 | saveMC.mat = tmp:long() 104 | return saveMC 105 | end 106 | end 107 | } 108 | 109 | 110 | SemSegmMeter.value = argcheck{ 111 | {name="self", type="tnt.SemSegmMeter"}, 112 | {name="s", type="string"}, 113 | call = 114 | function(self, s) 115 | if s == 'map' then 116 | self.conf:updateValids() 117 | return self.conf.averageUnionValid*100 118 | elseif s == 'pp' then 119 | self.conf:updateValids() 120 | return self.conf.totalValid*100 121 | elseif s == 'pc' then 122 | self.conf:updateValids() 123 | return self.conf.averageValid*100 124 | else 125 | error('Only map, pp and pc available.') 126 | end 127 | end 128 | } 129 | 130 | 131 | SemSegmMeter.valueOver = argcheck{ 132 | {name="self", type = "tnt.SemSegmMeter"}, 133 | {name="s", type = "string"}, 134 | {name="classesToAverageOver", type = "table"}, 135 | call = 136 | function(self, s, classesToAverageOver) 137 | local ctao = classesToAverageOver 138 | -- Make corresponding mask 139 | local mctao = torch.ByteTensor(#self.classes):zero() 140 | for _, c in ipairs(classesToAverageOver) do mctao[c] = 1 end 141 | local clval, D = self:values(s) 142 | local mn, ct = 0, 0 143 | for i = 1, clval:nElement() do 144 | if clval[i] == clval[i] then 145 | mn = mn + clval[i] 146 | ct = ct +1 147 | end 148 | end 149 | local notnan_mask = clval:eq(clval) 150 | local clval2 = clval[notnan_mask] 151 | local rem = clval[mctao] 152 | local notnan_mask = rem:eq(rem) 153 | rem = rem[notnan_mask] 154 | 155 | if s == 'pp' then 156 | remD = D[mctao]:sum() 157 | return 100*remD/rem:sum() 158 | end 159 | 160 | if rem:nElement() == 0 then return 0/0, 0 161 | else 162 | return rem:mean()*100, rem:nElement() 163 | end 164 | end 165 | } 166 | 167 | 168 | SemSegmMeter.values = argcheck{ 169 | {name="self", type="tnt.SemSegmMeter"}, 170 | {name="s", type="string"}, 171 | call = 172 | function(self, s) 173 | if s == 'iou' then 174 | self.conf:updateValids() 175 | local unionvalids = self.conf.unionvalids:clone() 176 | -- Do not count IOU for absent classes, should this happen 177 | local nanval_pc = self.conf.valids:ne(self.conf.valids) 178 | unionvalids[nanval_pc] = unionvalids[nanval_pc]:fill(0/0) 179 | return unionvalids 180 | elseif s == 'pc' then 181 | self.conf:updateValids() 182 | return self.conf.valids:clone() 183 | elseif s == 'pp' then 184 | self.conf:updateValids() 185 | R = torch.sum(self.conf.mat,2):float():squeeze() 186 | D = torch.diag(self.conf.mat) 187 | return R,D 188 | else 189 | error('Only iou and pc available.') 190 | end 191 | end 192 | } 193 | 194 | 195 | SemSegmMeter.print = argcheck{ 196 | {name="self", type="tnt.SemSegmMeter"}, 197 | call = 198 | function(self) 199 | self.conf:updateValids() 200 | print(self.conf) 201 | end 202 | } 203 | 204 | return SemSegmMeter 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- 228 | -- Not needed anymore 229 | 230 | -- If several untagged classes needed 231 | -- SemSegmMeter.severalUntaggedAdd = argcheck{ 232 | -- {name="self", type="tnt.SemSegmMeter"}, 233 | -- {name="output", type="torch.*Tensor"}, 234 | -- {name="target", type="torch.*Tensor"}, 235 | -- call = 236 | -- function(self, output, target) 237 | -- assert(output:dim()==4) 238 | -- assert(target:dim()==3) 239 | 240 | -- -- Hard predictions 241 | -- local _,hp = torch.max(output, 2) 242 | -- hp = hp:squeeze(2) 243 | -- print(hp:size()) 244 | 245 | -- -- Unfold predictions in contiguous memory 246 | -- local szp, szt = hp:size(), target:size() 247 | -- local uout, utar = hp:view(szp[1]*szp[2]*szp[3]):contiguous():float(), 248 | -- target:view(szt[1]*szt[2]*szt[3]):contiguous():float() 249 | -- assert(uout:nElement()==utar:nElement()) 250 | -- -- Update 251 | -- local N = uout:nElement() 252 | -- local uoutPtr, utarPtr = uout:data(), utar:data() 253 | 254 | -- for n=0,N-1 do 255 | -- if not torch.any(torch.eq(self.sc, utarPtr[n])) then 256 | -- self.conf:add(uoutPtr[n], utarPtr[n]) 257 | -- end 258 | -- end 259 | -- end 260 | -- } 261 | 262 | -- pcall(loadstring("sct = torch.FloatTensor({" .. skipClasses .."})")) 263 | -- self.sc = sct:clone() 264 | -- sct=nil 265 | -- if self.sc:size(1)==1 then self.sc = self.sc[1] end -- to optimize 266 | -------------------------------------------------------------------------------- /utils/model.lua: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- 2 | -- Model definition 3 | -- Written by Camille Couprie, Michael Mathieu, Pauline Luc, Natalia Neverova 4 | -------------------------------------------------------------------------------- 5 | -- Copyright 2017-present, Facebook, Inc. 6 | -- All rights reserved. 7 | -- This source code is licensed under the license found in the 8 | -- LICENSE file in the root directory of this source tree. 9 | 10 | require('nngraph') 11 | require('cunn') 12 | require('cudnn') 13 | require('nnx') 14 | 15 | local mod_size=4 16 | 17 | local modelStruct 18 | if opt.nscales==2 then 19 | modelStruct = { 20 | [2] = { 21 | {'convp', 3, 32*mod_size}, 22 | {'convp', 3, 64*mod_size}, 23 | {'feature'}, 24 | {'convp', 3, 32*mod_size}, 25 | {'convp', 3, nil}}, 26 | [1] = { 27 | {'convp', 5, 32*mod_size}, 28 | {'convp', 3, 64*mod_size}, 29 | {'feature'}, 30 | {'convp', 3, 32*mod_size}, 31 | {'convp', 5, nil}}} 32 | elseif opt.nscales==1 then 33 | modelStruct = { 34 | [1] = { 35 | {'convp', 3, 32*mod_size}, 36 | {'convp', 3, 64*mod_size}, 37 | {'feature'}, 38 | {'convp', 3, 32*mod_size}, 39 | {'convp', 3, nil}}} 40 | end 41 | 42 | scaleList = {} 43 | for k, v in pairs(modelStruct) do 44 | scaleList[1+#scaleList] = k 45 | end 46 | 47 | table.sort(scaleList, function(a,b) return b