├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── VCLFD.m ├── angularDiffusion ├── diffuseAngular.m ├── drawVisibleLines.m ├── points2ulines.m ├── points2vlines.m ├── splatEPIu.m └── splatEPIv.m ├── compile_mex.m ├── const.m ├── cviewDepthEstim ├── diffuseSpatial.m ├── movePts2Surface.m ├── neighborPtsAlongEdge.m ├── planeSweep.m ├── wmf.m └── wmf │ ├── boxfilter.m │ ├── demo_jpeg.m │ ├── demo_stereo_refine.m │ ├── guidedfilter_color_precompute.m │ ├── guidedfilter_color_runfilter.m │ ├── guidedfilter_color_runfilter_mask.m │ ├── guidedfilter_rgbd_precompute.m │ ├── guidedfilter_rgbd_runfilter.m │ ├── img_jpeg │ ├── 20.jpg │ ├── 28.jpg │ └── 31.jpg │ ├── weighted_median_filter.m │ ├── weighted_median_filter_approx.m │ └── weighted_median_filter_mask.m ├── depth ├── reproj.m ├── reproj2offcenter.m ├── splat.m └── trilatFilt.m ├── eval ├── badpixels.m ├── mse.m └── pairwiseconst.m ├── lahbpcg_mex.cpp ├── lahbpcg_mex.mexmaci64 ├── lines ├── edges2lines.m ├── epis2edges.m ├── filterOutliers.m ├── findEdgesEPI.m ├── fitLinesEPI.m ├── genFilters.m ├── lf2edges4d.m ├── merge.m ├── nms.m ├── pvisible.m ├── refineLineDepth.m ├── visibility.m └── wu.m ├── parameters.m ├── run.sh ├── runOnLightfields.m ├── util ├── expspace.m └── loadLF.m └── view-consistent-depth.gif /.gitignore: -------------------------------------------------------------------------------- 1 | results/* 2 | *.psd 3 | *.mp4 4 | *.png 5 | *~ 6 | *# 7 | *.avi 8 | *.mov 9 | *.mat 10 | *.txt 11 | .DS_Store 12 | */.DS_Store 13 | *.mexa64 14 | *#* -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ImageStack"] 2 | path = ImageStack 3 | url = https://github.com/abadams/ImageStack.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # View-Consistent 4D Light Field Depth Estimation 3 | [Numair Khan](https://cs.brown.edu/~nkhan6)1, 4 | [Min H. Kim](http://vclab.kaist.ac.kr/minhkim/)2, 5 | [James Tompkin](http://www.jamestompkin.com)1
6 | 1Brown, 2KAIST
7 | BMVC 2020 & BMVC 2021
8 | [Project Homepage](http://visual.cs.brown.edu/lightfielddepth/) 9 | 10 | ### [View Consistency Paper](https://www.bmvc2020-conference.com/assets/papers/0395.pdf) | [Edge-aware Bi-directional Diffusion Paper](https://www.bmvc2021-virtualconference.com/assets/papers/0637.pdf) | [Presentation Video](http://visual.cs.brown.edu/projects/lightfielddepth-webpage/video/presentation.mp4) | [Supplemental Results Video](https://www.bmvc2020-conference.com/assets/supp/0395_supp.mp4) 11 | 12 |
13 | 14 | ## Citation 15 | If you use this code in your work, please cite the following works: 16 | 17 | ``` 18 | @article{khan2021edgeaware, 19 | title={Edge-aware Bidirectional Diffusion for Dense Depth Estimation from Light Fields}, 20 | author={Numair Khan and Min H. Kim and James Tompkin}, 21 | journal={British Machine Vision Conference}, 22 | year={2021}, 23 | } 24 | 25 | @article{khan2020vclfd, 26 | title={View-consistent {4D} Lightfield Depth Estimation}, 27 | author={Numair Khan, Min H. Kim, James Tompkin}, 28 | journal={British Machine Vision Conference}, 29 | year={2020}, 30 | } 31 | ``` 32 | 33 | ## Running the MATLAB Code 34 | * [Installing ImageStack](#installing-imagestack) 35 | * [Generating Depth](#generating-depth) 36 | * [Troubleshooting](#troubleshooting) 37 | 38 | ### Installing ImageStack 39 | The code uses ImageStack's implementation of Richard Szeliski's LAHBPCG solver. Along with this repo, you will also have to clone the ImageStack submodule: 40 | 41 | ``` 42 | $ git clone https://github.com/brownvc/lightfielddepth.git 43 | $ cd lightfielddepth 44 | $ git submodule init 45 | $ git submodule update 46 | ``` 47 | 48 | You may have to install the FFTW3 library for ImageStack: 49 | 50 | ``` 51 | $ sudo apt-get install fftw3 52 | ``` 53 | 54 | Then compile the MEX interface to ImageStack: 55 | 56 | ``` 57 | $ matlab -nodisplay -r "compile_mex; exit" 58 | ``` 59 | 60 | ### Generating Depth 61 | To generate disparity estimates for all views of a light field, use `run.sh` followed by the path to the light field file: 62 | 63 | ```$ sudo ./run.sh ``` 64 | 65 | The light field is provided as a `.mat` file containing a 5D array. The dimensions of the 5D array should be ordered as (y, x, rgb, v, u) where "rgb" denotes the color channels. 66 | 67 | ``` 68 | u 69 | ----------------------------> 70 | | ________ ________ 71 | | | x | | x | 72 | | | | | | 73 | v | | y | | y | .... 74 | | | | | | 75 | | |________| |________| 76 | | : 77 | | : 78 | v 79 | ``` 80 | 81 | Alternatively, a path to a directory of images may be provided to `run.sh`. The directory should contain a file called `config.txt` with the dimensions of the light field on the first line in format `y, x, v, u`. 82 | 83 | Make sure to set the camera movement direction for both u and v in `parameters.m`. 84 | 85 | The depth estimation results are output to a 4D MATLAB array in `./results//`. 86 | 87 | ### Troubleshooting 88 | - Code fails with error `Index exceeds the number of array elements`: Make sure you are following the correct dimensional 89 | ordering; for light field images this should be `(y, x, rgb, v, u)` and for depth labels `(y, x, v, u)`. 90 | - The output has very high error: Make sure you specify the direction in which the camera moves in u and v. This can be done by setting the boolean variables `uCamMovingRight` and `vCamMovingRight` in `parameters.m`. The camera movement direction determines the occlusion order of EPI lines, and is important for edge detection and depth ordering. 91 | - The code has been run and tested in MATLAB 2019b. Older version of MATLAB may throw errors on some functions. 92 | -------------------------------------------------------------------------------- /VCLFD.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Generate *View Consistent Light Field Depth* for the input light field using 3 | %% the parameter settings in param 4 | %% 5 | function VCLFD (fin, fout, param) 6 | 7 | LF = loadLF( fin, param.uCamMovingRight, param.vCamMovingRight, 'lab'); 8 | 9 | param.szLF = [size(LF, 1) size(LF, 2) size(LF, 4) size(LF, 5)]; % light field size in y, x, v, u 10 | param.szEPI = [param.szLF(4) param.szLF(2) param.szLF(1)]; % EPI size 11 | param.cviewIdx = ceil(param.szLF(3)/2); 12 | 13 | LFrgb = single(loadLF( fin, param.uCamMovingRight, param.vCamMovingRight, 'rgb')) ./ 255; 14 | LFrgb = num2cell(cat(4, squeeze(LFrgb(:, :, :, :, param.cviewIdx)), squeeze(LFrgb(:, :, :, param.cviewIdx, :))), [1 2 3]); 15 | 16 | LFg = single(loadLF( fin, param.uCamMovingRight, param.vCamMovingRight, 'gray')) ./ 255; 17 | LFg = num2cell(cat(3, squeeze(LFg(:, :, 1, :, param.cviewIdx)), squeeze(LFg(:, :, 1, param.cviewIdx, :))), [1 2]); 18 | 19 | % Get the central row of LF images, and their EPIs 20 | LFuc = squeeze(LF(:, :, :, param.cviewIdx, :)); 21 | 22 | % Filter the views to remove noise 23 | for i = 1:size(LFuc, 4) 24 | LFuc(:, :, :, i) = imgaussfilt( squeeze(LFuc(:, :, :, i)), 0.85); 25 | end 26 | EPIuc = permute(LFuc, [4 2 3 1]); 27 | 28 | % Get the central column of LF images, and their EPIs 29 | LFvc = squeeze(LF(:, :, :, :, param.cviewIdx)); 30 | LFvc = permute(LFvc, [2 1 3 4]); 31 | for i = 1:size(LFvc, 4) 32 | LFvc(:, :, :, i) = imgaussfilt( squeeze(LFvc(:, :, :, i)), 0.85); 33 | end 34 | EPIvc = permute(LFvc, [4 2 3 1]); 35 | 36 | t0 = tic; 37 | 38 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 39 | % EDGE DETECTION & LINE FITTING % 40 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 41 | 42 | % Get 4D edges 43 | % 44 | tic 45 | [P, V] = lf2edges4d(EPIuc, EPIvc, param); 46 | [P, ~] = trilatFilt(P, V, LFrgb, param); 47 | t = toc; 48 | disp(['4D edge detection completed in ' num2str(t) 's']); 49 | 50 | 51 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 52 | % CENTRAL VIEW DEPTH ESTIMATION % 53 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 54 | tic 55 | [O, W, dheuristic] = movePts2Surface(P, V, LFg, param); 56 | P(:, [1 2]) = P(:, [1 2]) + O; 57 | t = toc; 58 | disp(['Point offset completed in ' num2str(t) 's']); 59 | 60 | [P, urIdx] = trilatFilt(P, V, LFrgb, param); 61 | idx = isnan(W) | urIdx; 62 | P(idx, :) = []; 63 | V(idx, :) = []; 64 | W(idx, :) = []; 65 | O(idx, :) = []; 66 | 67 | % Select a specified percentage of highest-confidence points 68 | [W, o] = sort(W, 'descend'); 69 | W = W(1:round(size(o, 1) * const.sparsifyFactor), :); 70 | P = P(o(1:round(size(o, 1) * const.sparsifyFactor)), :); 71 | V = V(o(1:round(size(o, 1) * const.sparsifyFactor)), :); 72 | O = O(o(1:round(size(o, 1) * const.sparsifyFactor)), :); 73 | 74 | % Improve depth at remaining points by performing a plane sweep in a small 75 | % oriented window around each point, and discard points with low alignment confidence 76 | tic 77 | [P, ~, lowConfIdx] = planeSweep(P, O, V, LFg, param); 78 | P(lowConfIdx, :) = []; 79 | V(lowConfIdx, :) = []; 80 | W(lowConfIdx) = []; 81 | t = toc; 82 | disp(['Plane sweep completed in ' num2str(t) 's']); 83 | 84 | tic 85 | dheuristic = wmf(dheuristic, lab2rgb(LF(:, :, :, param.cviewIdx, param.cviewIdx)), 256, 0.01^2, 5); 86 | t = toc; 87 | disp(['Weighted median filtering completed in ' num2str(t) 's']); 88 | 89 | tic 90 | o = diffuseSpatial(P(V(:, param.cviewIdx), :), W(V(:, param.cviewIdx)), LFg{param.cviewIdx}, dheuristic, param); 91 | t = toc; 92 | disp(['Diffusion completed in ' num2str(t) 's']); 93 | 94 | % Remove outliers and sharpen edges 95 | tic 96 | om = medfilt2(o, [3 3]); 97 | mn = min(min(om)); 98 | mx = max(max(om)); 99 | o(o > mx) = mx; 100 | o(o < mn) = mn; 101 | o = wmf(o, lab2rgb(LF(:, :, :, param.cviewIdx, param.cviewIdx)), 256, 0.001^2, 7); 102 | t = toc; 103 | disp(['Weighted median filtering completed in ' num2str(t) 's']); 104 | 105 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 106 | % CROSS-HAIR VIEW PROJECTION % 107 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 108 | v = [1:param.szLF(3) repelem(param.cviewIdx, 1, param.szLF(4))]; 109 | u = [repelem(param.cviewIdx, 1, param.szLF(3)) 1:param.szLF(4)]; 110 | R = zeros(param.szLF(1), param.szLF(2), length(u)); 111 | M = zeros(param.szLF(1), param.szLF(2), length(u)); 112 | 113 | tic; 114 | parfor (i = 1:length(u), 18) 115 | [R(:, :, i), M(:, :, i)] = reproj(o, param.cviewIdx - v(i), param.cviewIdx - u(i)); 116 | end 117 | t = toc; 118 | disp(['Crosshair views projection completed in ' num2str(t) 's']); 119 | 120 | %%%%%%%%%%%%%%%%%%%%%% 121 | % Angular Diffusion % 122 | %%%%%%%%%%%%%%%%%%%%%% 123 | 124 | % In U... 125 | tic; 126 | 127 | dEPIu = permute(R(:, :, param.szLF(3) + 1:end), [3 2 1]); 128 | dEPIu(isnan(dEPIu)) = 0; 129 | mEPIu = permute(M(:, :, param.szLF(3) + 1:end), [3 2 1]); 130 | 131 | % Select points occluded in the central view 132 | idx = ~V(:, param.cviewIdx); 133 | [wEPIu, lEPIu, ~] = splatEPIu(P(idx, :), V(idx, param.szLF(3) + 1:end), W(idx, :), param.szEPI); 134 | 135 | % Diffuse along horizontal EPIs 136 | U = diffuseAngular(dEPIu, mEPIu, lEPIu, wEPIu, o', EPIuc, param); 137 | 138 | dEPIv = permute(permute(R(:, :, 1:param.szLF(3)), [2 1 3]), [3 2 1]); 139 | dEPIv(isnan(dEPIv)) = 0; 140 | mEPIv = permute(permute(M(:, :, 1:param.szLF(3)), [2 1 3]), [3 2 1]); 141 | 142 | idx = ~V(:, param.cviewIdx); 143 | [wEPIv, lEPIv, ~] = splatEPIv(P(idx, :), V(idx, 1:param.szLF(3)), W(idx, :), param.szEPI); 144 | 145 | % Diffuse along vertical EPIs 146 | V = diffuseAngular(dEPIv, mEPIv, lEPIv, wEPIv, o, EPIvc, param); 147 | V = permute(V, [2 1 3]); 148 | 149 | t = toc; 150 | disp(['EPI propagation completed in ' num2str(t) 's']); 151 | 152 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 153 | % Non-Cross Hair View Projection % 154 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 155 | 156 | tic; 157 | D = []; 158 | jv = [1:param.cviewIdx-1 param.cviewIdx + 1:param.szLF(3)]; 159 | for i = [1:param.cviewIdx-1 param.cviewIdx + 1:param.szLF(3)] 160 | parfor (j = 1:length(jv), 12) 161 | [di, m] = reproj2offcenter(V, U, i, j, param); 162 | 163 | g = imgradient(LF(:, :, 1, i, j)); 164 | g = 1./(1000 .* g.^2 + 0.0001); 165 | o = lahbpcg_mex(di, m .* 15000, g, g, 10, 0.00001); 166 | 167 | o(o < min(min(di))) = min(min(di)); 168 | o(o > max(max(di))) = max(max(di)); 169 | Dt(:, :, j) = o; 170 | end 171 | D(:, :, i, jv) = Dt; 172 | end 173 | 174 | D(:, :, param.cviewIdx, :) = U; 175 | D(:, :, :, param.cviewIdx) = V; 176 | 177 | t = toc; 178 | disp(['All views projection completed in ' num2str(t) 's']); 179 | disp(['Depth estimation for ' num2str(param.szLF(3) * param.szLF(4)) ' views completed in ' num2str(toc(t0)) 's']); 180 | disp(['Output saved in ' fout '.mat']); 181 | 182 | save([fout '.mat'], 'D'); 183 | end 184 | -------------------------------------------------------------------------------- /angularDiffusion/diffuseAngular.m: -------------------------------------------------------------------------------- 1 | function O = diffuseAngular(d, m, l, w, dmapc, EPI, param) 2 | 3 | szEPI = size(EPI); 4 | 5 | parfor i = 1:size(EPI, 4) 6 | e(:, :, i) = imgradient(EPI(:, :, 1, i)); 7 | m(:, :, i) = medfilt2(m(:, :, i), [1 3]); 8 | end 9 | 10 | m = m .* 15; 11 | d(m == 0) = 10000; 12 | 13 | d(w > 0) = l(w > 0); 14 | m(w > 0) = w(w > 0); 15 | 16 | d(param.cviewIdx, :, :) = dmapc; 17 | m(param.cviewIdx, :, :) = 5; 18 | 19 | nWorkers = 12; 20 | uEpisPerWorker = ceil(szEPI(4) ./ nWorkers); 21 | 22 | M = accumarray( repelem([1:nWorkers]', uEpisPerWorker, 1), ... 23 | 1:nWorkers * uEpisPerWorker, [], @(r){m(:, :, min(r, szEPI(4)))}); 24 | D = accumarray( repelem([1:nWorkers]', uEpisPerWorker, 1), ... 25 | 1:nWorkers * uEpisPerWorker, [], @(r){d(:, :, min(r, szEPI(4)))}); 26 | E = accumarray( repelem([1:nWorkers]', uEpisPerWorker, 1), ... 27 | 1:nWorkers * uEpisPerWorker, [], @(r){e(:, :, min(r, szEPI(4)))}); 28 | 29 | O = {}; 30 | parfor (i = 1:size(M, 1), nWorkers) 31 | mi = M{i}; 32 | di = D{i}; 33 | ei = E{i}; 34 | oi = zeros( szEPI(1), szEPI(2), uEpisPerWorker ); 35 | 36 | for j = 1:uEpisPerWorker 37 | d = padarray(double(di(:, :, j)), [1 1], 0); 38 | w = padarray(double(mi(:, :, j)), [1 1], 0); 39 | m = max(max(ei(:, :, j))); 40 | g = padarray(ei(:, :, j), [1 1], m); 41 | g = 1 ./ (10 .* g.^2 + 0.0001); 42 | o = lahbpcg_mex(d, w, g, g, 1000, 0.00001); 43 | oi(:, :, j) = o( 2:end - 1, 2:end - 1); 44 | end 45 | O(i) = {oi}; 46 | end 47 | 48 | O = cellfun(@(u) permute(u, [3 2 1]), O, 'UniformOutput', false); 49 | O = vertcat(O{:}); 50 | O = O(1:size(EPI, 4), :, :); 51 | end 52 | -------------------------------------------------------------------------------- /angularDiffusion/drawVisibleLines.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Rasterize EPI lines 3 | %% 4 | function bw = drawVisibleLines(lines, c, v, emptyVal, epiSz) 5 | 6 | [~, o] = sort(lines(:, 2) - lines(:, 1)); 7 | lines = lines(o, :); 8 | c = c(o, :); 9 | v = v(o, :); 10 | 11 | bw = ones(epiSz) .* emptyVal; 12 | for i = 1:size(lines, 1) 13 | 14 | x = [lines(i, 1) lines(i, 2)]; 15 | y = [1 epiSz(1)]; 16 | 17 | nPoints = epiSz(1); 18 | rIndex = [y(1):y(2)]; 19 | cIndex = max(1, min(round(linspace(x(1), x(2), nPoints)), epiSz(2))); 20 | index = sub2ind(epiSz, rIndex, cIndex); 21 | index = index(logical(v(i, :))); 22 | bw(index) = c(i, 1); 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /angularDiffusion/points2ulines.m: -------------------------------------------------------------------------------- 1 | % 2 | % Convert points to lines defined by their top and bottom intercepts on 3 | % horizontal (u) EPIs. 4 | % 5 | function [L, O] = points2ulines(P, szEPI) 6 | 7 | % Group points into lines by rounded y-coordinate 8 | [P, o] = sortrows(P, 2); 9 | idx = P(:, 2) < 1 | P(:, 2) > szEPI(3); 10 | P(idx, :) = []; 11 | o(idx, :) = []; 12 | 13 | [~, ~, X] = unique( round(P(:, 2)) ); 14 | A = accumarray(X, 1:size(P, 1), [], @(r){[P(r, :) o(r, :)]}); 15 | 16 | L = cell(szEPI(3), 1); 17 | for i = 1:size(A, 1) 18 | a = A{i}; 19 | y = round(a(1, 2)); 20 | L(y) = {[a(:, 1) - floor(szEPI(1) ./ 2) .* a(:, 3) ... 21 | a(:, 1) + floor(szEPI(1) ./ 2) .* a(:, 3)]}; 22 | O(y) = {a(:, 4)}; 23 | end 24 | 25 | end 26 | -------------------------------------------------------------------------------- /angularDiffusion/points2vlines.m: -------------------------------------------------------------------------------- 1 | % 2 | % Convert points to lines defined by their top and bottom intercepts on 3 | % vertical (v) EPIs. 4 | % 5 | function [L, O] = points2vlines(P, szEPI) 6 | 7 | % Group points into lines by rounded x-coordinate 8 | [P, o] = sortrows(P, 1); 9 | idx = P(:, 1) < 1 | P(:, 1) > szEPI(3); 10 | P(idx, :) = []; 11 | o(idx, :) = []; 12 | 13 | [~, ~, X] = unique( round(P(:, 1)) ); 14 | A = accumarray(X, 1:size(P, 1), [], @(r){[P(r, :) o(r, :)]}); 15 | 16 | L = cell(szEPI(3), 1); 17 | for i = 1:size(A, 1) 18 | a = A{i}; 19 | x = round(a(1, 1)); 20 | L(x) = {[a(:, 2) - floor(szEPI(1) ./ 2) .* a(:, 3) ... 21 | a(:, 2) + floor(szEPI(1) ./ 2) .* a(:, 3)]}; 22 | O(x) = {a(:, 4)}; 23 | end 24 | 25 | end 26 | -------------------------------------------------------------------------------- /angularDiffusion/splatEPIu.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Splat points as lines onto a horizontal (u) EPI with visibility V and weight W 3 | %% 4 | function [M, D, I] = splatEPIu(P, V, W, szEPI) 5 | 6 | [L, o] = points2ulines(P, szEPI); 7 | Lv = cellfun(@(i) V(i, :), o, 'UniformOutput', false); 8 | Lw = cellfun(@(i) W(i, :), o, 'UniformOutput', false); 9 | Ld = cellfun(@(i) P(i, 3), o, 'UniformOutput', false); 10 | 11 | M = zeros(szEPI); 12 | D = zeros(szEPI); 13 | I = zeros(szEPI); 14 | 15 | for i = 1:szEPI(3) 16 | if isempty(L{i}) 17 | continue; 18 | end 19 | 20 | M(:, :, i) = drawVisibleLines(L{i}, Lw{i}, Lv{i}, 0, szEPI([1 2])); 21 | D(:, :, i) = drawVisibleLines(L{i}, Ld{i}, Lv{i}, 0, szEPI([1 2])); 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /angularDiffusion/splatEPIv.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Splat points as lines onto a vertical (v) EPI with visibility V and weight W 3 | %% 4 | function [M, D, I] = splatEPIv(P, V, W, szEPI) 5 | 6 | [L, o] = points2vlines(P, szEPI); 7 | Lv = cellfun(@(i) V(i, :), o, 'UniformOutput', false); 8 | Lw = cellfun(@(i) W(i, :), o, 'UniformOutput', false); 9 | Ld = cellfun(@(i) P(i, 3), o, 'UniformOutput', false); 10 | 11 | M = zeros(szEPI); 12 | D = zeros(szEPI); 13 | I = zeros(szEPI); 14 | 15 | for i = 1:szEPI(3) 16 | if isempty(L{i}) 17 | continue; 18 | end 19 | M(:, :, i) = drawVisibleLines(L{i}, Lw{i}, Lv{i}, 0, szEPI([1 2])); 20 | D(:, :, i) = drawVisibleLines(L{i}, Ld{i}, Lv{i}, 0, szEPI([1 2])); 21 | %I(:, :, i) = drawLines2(L{i}, o{i}, V{i}, 0, szEPI([1 2])); 22 | end 23 | 24 | end 25 | -------------------------------------------------------------------------------- /compile_mex.m: -------------------------------------------------------------------------------- 1 | filelist = dir('./ImageStack/src/'); 2 | filelist = filelist(~startsWith({filelist.name}, '.')); 3 | filelist = filelist(~startsWith({filelist.name}, 'Func')); 4 | filelist = filelist(endsWith({filelist.name}, '.cpp')); 5 | 6 | filelist = cellfun(@(a) strcat('./ImageStack/src/', a), {filelist.name}, 'UniformOutput', false); 7 | filelist = join(cellfun(@string, filelist)); 8 | 9 | eval(strcat("mex ./lahbpcg_mex.cpp ", filelist, " -I/usr/local/include -L/usr/local/lib/ -DNO_SDL -DNO_OPENEXR -DNO_TIFF -DNO_JPEG -DNO_PNG -lfftw3f -ldl -R2018a")) 10 | -------------------------------------------------------------------------------- /const.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Constants used by the algorithms 3 | %% These should not be changed. Any run specific parameters can 4 | %% be set in parameters.m 5 | %% 6 | classdef const 7 | properties (Constant = true) 8 | SegMinWidthMultiplier = 0.1; 9 | 10 | filtOutliersGradientDirectionThresh = 0.97; 11 | filtOutliersMinContigPixels = 4; 12 | 13 | visibilityMinViews = 3; 14 | visibilityAlignmentThreshold = 0.95 % this is a cos(theta) where theta is the alignment angle 15 | 16 | refineIterCount = 10; 17 | refineTempStart = 0.15; 18 | refineTempAnnealFactor = 0.88; 19 | 20 | trilatFiltWinSz = 10; 21 | 22 | sparsifyFactor = 0.9; 23 | 24 | diffusionScale = 2.0; 25 | 26 | planeSweepMaxViews = 8; 27 | planeSweepPatchSz = [5 5]; 28 | planeSweepMaxDispOffset = 0.25; 29 | planeSweepNumDispOffset = 9; % This should be an odd number 30 | 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /cviewDepthEstim/diffuseSpatial.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Dense depth diffusion in the spatial domain 3 | %% 4 | function o = diffuseSpatial(P, W, I, dheuristic, param) 5 | 6 | P(:, [1 2]) = P(:, [1 2]) * const.diffusionScale; 7 | 8 | % Gradients of the depth heuristic 9 | [gxd, gyd] = imgradientxy( imresize( dheuristic, const.diffusionScale) ); 10 | gd = sqrt( gxd.^2 + gyd.^2 ); 11 | gd(:, [1 end]) = max(max(gd)); 12 | gd([1 end], :) = max(max(gd)); 13 | 14 | gd = imgaussfilt(gd, 1); 15 | 16 | % Gradients of the guidance image 17 | [gx, gy] = imgradientxy( imresize( I, const.diffusionScale) ); 18 | g = sqrt( gx.^2 + gy.^2 ); 19 | g(:, [1 end]) = max(max(g)); 20 | g([1 end], :) = max(max(g)); 21 | 22 | [w, d] = splat(P, W, param.szLF([1 2]) * const.diffusionScale); 23 | 24 | % Weights are determined empirically and work for all light fields 25 | wg = 100./255 ./ sqrt(0.01); 26 | g = wg .* g .* gd; 27 | g = double(1 ./ (10 * g.^2 + 0.0001)); 28 | w = w .* 1500; 29 | 30 | o = lahbpcg_mex(d, w, g, g, 20, 0.00001); 31 | o = imresize(o, param.szLF([1 2])); 32 | end 33 | -------------------------------------------------------------------------------- /cviewDepthEstim/movePts2Surface.m: -------------------------------------------------------------------------------- 1 | % 2 | % Move depth points from edges to surfaces. 3 | % 4 | % In theory, the depth at an edge is undefined -- it is a transition between two surfaces. 5 | % In order to perform diffusion correctly, we want our depth labels to lie on surfaces, 6 | % not edges. So we need to move our points by a small amount off edges. But since we only 7 | % have a sparse set of depth labels, it is not trivial to determine which surface the edge 8 | % depth label corresponds to. 9 | % 10 | % This function moves points off edges by performing diffusion in both surface directions, 11 | % and then checking which direction generates the stronger gradient at the edge. It also 12 | % returns a heuristic estimate of the final disparity. 13 | % 14 | function [O, W, dheuristic] = movePts2Surface(P, V, LFg, param) 15 | 16 | % For each point, get the index of a view in the central cross-hair in which it is visible. 17 | % For points visible in multiple views, the one closest to the central view is selected 18 | [~, viewIdx] = min(abs(V .* [1:param.szLF(3) 1:param.szLF(4)] - param.cviewIdx), [], 2); 19 | 20 | % Get the unique set of views with visible points, ... 21 | [uniqueViewIdx, ~, X] = unique(viewIdx); 22 | % ... and the set of points for each of those views 23 | visiblePtsIdx = accumarray(X, 1:size(V, 1), [], @(r){r}); 24 | 25 | O = zeros(size(P, 1), 1); % The offsets 26 | W = zeros(size(P, 1), 1); % The confidence 27 | Gx = zeros(size(P, 1), 1); % Gradient along x at each point.. 28 | Gy = zeros(size(P, 1), 1); % Gradient along y. 29 | 30 | Oi = {}; 31 | Wi = {}; 32 | Gxi = {}; 33 | Gyi = {}; 34 | 35 | [m, d, idx] = splat(P, 1, [512 512]); 36 | 37 | parfor (i = 1:length(uniqueViewIdx), 18) 38 | view = uniqueViewIdx(i); 39 | ui = (view <= param.szLF(3)) * param.cviewIdx + (view > param.szLF(3)) * (view - param.szLF(3)); 40 | vi = (view <= param.szLF(3)) * view + (view > param.szLF(3)) * param.cviewIdx; 41 | 42 | % Project visible points to current view 43 | vis = V(:, view); 44 | Pi = P; 45 | Pi(:, [1 2]) = [Pi(:, 1) + (ui - param.cviewIdx) .* Pi(:, 3) Pi(:, 2) + (vi - param.cviewIdx) .* Pi(:, 3)]; 46 | 47 | % Find the gradient direction at each points 48 | [lfgx, lfgy] = imgradientxy( LFg{view} ); 49 | pgx = interp2(lfgx, Pi(:, 1), Pi(:, 2)); 50 | pgy = interp2(lfgy, Pi(:, 1), Pi(:, 2)); 51 | pgm = 1 ./ sqrt( pgx.^2 + pgy.^2 ); 52 | pgx = pgx .* pgm; 53 | pgy = pgy .* pgm; 54 | pgx(isnan(pgx)) = 0; 55 | pgy(isnan(pgy)) = 0; 56 | 57 | [g, ~, ~] = splat(Pi(vis, :), 1, [param.szLF(1) param.szLF(2)]); 58 | g = double(1 ./ (g.^2 + 0.0001)); 59 | 60 | % 1. Offset points in gradient direction and diffuse 61 | Po = Pi; 62 | Po(:, [1 2]) = Po(:, [1 2]) + [pgx pgy]; 63 | 64 | [w, d] = splat(Po(vis, :), 1, [param.szLF(1) param.szLF(2)]); 65 | w = double(w .* 100000); 66 | Duf(:, :, i) = lahbpcg_mex(d, w, g, g, 1000, 0.00001); 67 | 68 | % 2. Offset points opposite to the gradient direction and diffuse 69 | Po(:, [1 2]) = Po(:, [1 2]) - 2 * [pgx pgy]; 70 | 71 | [w, d] = splat(Po(vis, :), 1, [param.szLF(1) param.szLF(2)]); 72 | w = double(w .* 100000); 73 | Dub(:, :, i) = lahbpcg_mex(d, w, g, g, 1000, 0.00001); 74 | 75 | ptsIdx = visiblePtsIdx{i}; 76 | 77 | % 78 | % Select the offset direction which generates the sharper gradient at the current edge point 79 | samplesRange = 3; 80 | samplesOffset = [-samplesRange:samplesRange]; 81 | edgeSampleIdx = ceil(length(samplesOffset) ./ 2); 82 | ptsx = Pi(ptsIdx, 1) + pgx(ptsIdx) .* samplesOffset; 83 | ptsy = Pi(ptsIdx, 2) + pgy(ptsIdx) .* samplesOffset; 84 | 85 | df = interp2( Duf(:, :, i), ptsx, ptsy ); 86 | db = interp2( Dub(:, :, i), ptsx, ptsy ); 87 | 88 | idxf = abs(df(:, edgeSampleIdx ) - df(:, edgeSampleIdx - 1)) > abs(df(:, edgeSampleIdx) - df(:, edgeSampleIdx + 1)); 89 | dfc = df(:, 2:end); 90 | dfc(idxf, :) = df(idxf, 1:end-1); 91 | 92 | idxb = abs(db(:, edgeSampleIdx ) - db(:, edgeSampleIdx - 1)) > abs(db(:, edgeSampleIdx) - db(:, edgeSampleIdx + 1)); 93 | dbc = db(:, 2:end); 94 | dbc(idxf, :) = db(idxf, 1:end-1); 95 | 96 | df = dfc; 97 | db = dbc; 98 | 99 | ao = abs(df * [ linspace(-1, -2, samplesRange) linspace(2, 1, samplesRange) ]'); 100 | bo = abs(db * [ linspace(-1, -2, samplesRange) linspace(2, 1, samplesRange) ]'); 101 | Wi(i) = {exp(1.3 * abs(bo - ao))}; 102 | 103 | % Normalize the response across the edge to the range [-1, 1] 104 | df(isnan(df)) = 0; 105 | db(isnan(db)) = 0; 106 | df = df - min(df, [], 2); 107 | df = (df ./ max(df, [], 2)) * 2 - 1; 108 | db = db - min(db, [], 2); 109 | db = (db ./ max(db, [], 2)) * 2 - 1; 110 | 111 | df = abs(df * [ linspace(-1, -2, samplesRange) linspace(2, 1, samplesRange) ]'); 112 | db = abs(db * [ linspace(-1, -2, samplesRange) linspace(2, 1, samplesRange) ]'); 113 | fidx = df > db; 114 | 115 | oi = zeros(size(ptsIdx, 1), 1); 116 | oi(fidx, :) = 1; % Move these points along the gradient direction 117 | oi(~fidx, :) = -1; % Move these points opposite to the gradient direction 118 | 119 | Oi(i) = {oi}; 120 | Gxi(i) = {pgx(ptsIdx)}; 121 | Gyi(i) = {pgy(ptsIdx)}; 122 | end 123 | 124 | cidx = find( uniqueViewIdx == param.cviewIdx); 125 | dheuristic = (Duf(:, :, cidx) + Dub(:, :, cidx)); 126 | 127 | ptsIdx = vertcat(visiblePtsIdx{:}); 128 | O(ptsIdx, :) = vertcat(Oi{:}); 129 | W(ptsIdx, :) = vertcat(Wi{:}); 130 | Gx(ptsIdx, :) = vertcat(Gxi{:}); 131 | Gy(ptsIdx, :) = vertcat(Gyi{:}); 132 | 133 | % Median filter the offsets of neighboring points along an edge 134 | [m, ~, idx] = splat(P, 1, param.szLF([1 2])); 135 | [gx, gy] = imgradientxy(LFg{param.cviewIdx}); 136 | gm = sqrt(gx.^2 + gy.^2); 137 | gx = gx ./ gm; 138 | gy = gy ./ gm; 139 | 140 | O2 = O; 141 | for i = 1:size(P, 1) 142 | p = round(P(i, [1 2])); 143 | neighbors = neighborPtsAlongEdge(m, gx, gy, p, 60); 144 | if ~isempty(neighbors) 145 | O2(i) = median( [O(idx(neighbors))' O(i)] ); 146 | else 147 | O2(i) = O(i); 148 | end 149 | end 150 | 151 | % Offset the points in the determined direction 152 | O = O2 .* [Gx Gy]; 153 | end 154 | -------------------------------------------------------------------------------- /cviewDepthEstim/neighborPtsAlongEdge.m: -------------------------------------------------------------------------------- 1 | % 2 | % Return the neighbors for a point p in the edge image E. 3 | % An point q in E is considered a neighbor of another point r if it lies on an edge (E(q) == 1), and 4 | % it lies along the tangent at r. The set N is constructed by adding neighbors recursively starting 5 | % at p, upto a maximum of maxCount 6 | % 7 | function N = neighborPtsAlongEdge(E, gx, gy, p, maxCount) 8 | 9 | po = p; 10 | N = zeros(maxCount, 2); 11 | i = 1; 12 | 13 | for k = 1:floor(maxCount/2) 14 | 15 | % Move in the tangent direction 16 | tx = -gy(p(2), p(1)); 17 | ty = gx(p(2), p(1)); 18 | 19 | if abs(ty) < abs(tx) 20 | px1 = p(1) + round(tx); 21 | px2 = px1; 22 | py1 = p(2) + ceil(ty); 23 | py2 = p(2) + floor(ty); 24 | else 25 | px1 = p(1) + ceil(tx); 26 | px2 = p(1) + floor(tx); 27 | py1 = p(2) + round(ty); 28 | py2 = py1; 29 | end 30 | 31 | % If an edge point exists in the tangent direction, add it to the list of neighbors 32 | if py1 < size(E, 1) & py1 > 0 & px1 < size(E, 2) & px1 > 0 & E(py1, px1) == 1 33 | p = [px1 py1]; 34 | N(i, :) = p; 35 | i = i + 1; 36 | elseif py2 < size(E, 1) & py2 > 0 & px2 < size(E, 2) & px2 > 0 & E(py2, px2) == 1 37 | p = [px2 py2]; 38 | N(i, :) = p; 39 | i = i + 1; 40 | else 41 | break; 42 | end 43 | end 44 | 45 | p = po; 46 | for k = 1:floor(maxCount/2) 47 | 48 | % Move in the opposite direction of the tangent 49 | tx = gy(p(2), p(1)); 50 | ty = -gx(p(2), p(1)); 51 | 52 | if abs(ty) < abs(tx) 53 | px1 = p(1) + round(tx); 54 | px2 = px1; 55 | py1 = p(2) + ceil(ty); 56 | py2 = p(2) + floor(ty); 57 | else 58 | px1 = p(1) + ceil(tx); 59 | px2 = p(1) + floor(tx); 60 | py1 = p(2) + round(ty); 61 | py2 = py1; 62 | end 63 | 64 | if py1 < size(E, 1) & py1 > 0 & px1 < size(E, 2) & px1 > 0 & E(py1, px1) == 1 65 | p = [px1 py1]; 66 | N(i, :) = p; 67 | i = i + 1; 68 | elseif py2 < size(E, 1) & py2 > 0 & px2 < size(E, 2) & px2 > 0 & E(py2, px2) == 1 69 | p = [px2 py2]; 70 | N(i, :) = p; 71 | i = i + 1; 72 | else 73 | break; 74 | end 75 | end 76 | 77 | N = sub2ind( size(E), N(1:i-1, 2), N(1:i-1, 1) ); 78 | end 79 | -------------------------------------------------------------------------------- /cviewDepthEstim/planeSweep.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Fine-tune the depth at points in P by performing a plane-sweep around each point using a subset of views. 3 | %% 4 | function [P, conf, pUnreliableIdx] = planeSweep(P, O, V, LFg, param) 5 | 6 | npoints = size(P, 1); 7 | doff = P(:, 3) + linspace(-const.planeSweepMaxDispOffset, const.planeSweepMaxDispOffset, const.planeSweepNumDispOffset); 8 | 9 | % For each point get at most const.planeSweepMaxViews views in which it is visible 10 | % 11 | fv = cellfun(@(vi) find(vi), num2cell(V, 2), 'UniformOutput', false); 12 | pviews = cellfun(@(f, i) uint32([repelem(i, min(const.planeSweepMaxViews, length(f)), 1) ... 13 | f( randperm(length(f), min(const.planeSweepMaxViews, length(f)) ))']), ... 14 | fv, num2cell([1:npoints]'), 'UniformOutput', false); 15 | pviews = vertcat(pviews{:}); 16 | Vc = zeros(size(V), 'logical'); 17 | Vc( sub2ind(size(Vc), pviews(:, 1), pviews(:, 2)) ) = 1; 18 | 19 | C = zeros( [const.planeSweepPatchSz(1), const.planeSweepPatchSz(2), const.planeSweepNumDispOffset, npoints, const.planeSweepMaxViews], 'single'); 20 | 21 | % Select the set of views from which we want to project onto our reference plane. 22 | vIdx = single(unique(pviews(:, 2))); 23 | pNextViewIdx = ones(npoints, 1, 'uint8'); 24 | 25 | for i = 1:length(vIdx) 26 | u = (vIdx(i) <= param.szLF(3)) .* param.cviewIdx + (vIdx(i) > param.szLF(3)) .* (vIdx(i) - param.szLF(3)); 27 | v = (vIdx(i) > param.szLF(3)) .* param.cviewIdx + (vIdx(i) <= param.szLF(3)) .* vIdx(i); 28 | s2t = [u - param.cviewIdx v - param.cviewIdx]; 29 | 30 | pIdx = find(Vc(:, vIdx(i))); 31 | ci = costVolumeForImage( LFg{vIdx(i)}, P(pIdx, :), O(pIdx, :), ... 32 | s2t, doff(pIdx,:), const.planeSweepPatchSz ); 33 | for k = 1:length(pIdx) 34 | C(:, :, :, pIdx(k), pNextViewIdx(pIdx(k))) = ci(:, :, :, k); 35 | end 36 | pNextViewIdx(pIdx) = pNextViewIdx(pIdx) + 1; 37 | end 38 | 39 | C(isnan(C)) = 0; % A bit hacky; Does it affect the variance? 40 | 41 | Cvar = var(C, [], 5); % The variance along the views for each disparity estimate 42 | [conf, dmin] = min(Cvar, [], 3); % We use a winner-takes-all strategy for the best disparity 43 | dmin = squeeze(dmin); 44 | 45 | conf = squeeze(conf); % A const.planeSweepPatchSz x const.planeSweepPatchSz x npoints matrix of confidence at each patch pixel for a point 46 | 47 | % Normalize the confidence 48 | varsum = squeeze(sum(Cvar, 3)); 49 | conf = 1 - conf ./ varsum; 50 | idx = conf > 0.99; 51 | didx = cellfun(@(d, i) mode(d(i)), num2cell(dmin, [1 2]), num2cell(idx, [1 2]) ); 52 | didx = didx(:); 53 | 54 | conf = cellfun(@(cf, i) mean(cf(i)), num2cell(conf, [1 2]), num2cell(idx, [1 2]) ); 55 | conf = conf(:); 56 | 57 | idx = sub2ind( size(doff), [1:npoints]', didx ); 58 | pUnreliableIdx = isnan(idx); % These NaNs occur for patches where all pixels' confidence is lower than the threshold 59 | 60 | P(~pUnreliableIdx, 3) = doff( idx(~pUnreliableIdx) ); 61 | end 62 | 63 | %% 64 | %% Create a cost volume 65 | %% 66 | function v = costVolumeForImage(I, ps, o, s2t, doff, patchSz) 67 | ndoff = size(doff, 2); 68 | 69 | % Generate oriented patches at each point 70 | px = ps(:, 1) + s2t(:, 1) .* doff; 71 | py = ps(:, 2) + s2t(:, 2) .* doff; 72 | px = px'; 73 | py = py'; 74 | px = px(:); 75 | py = py(:); 76 | 77 | [patchx, patchy] = orientedPatchAtPoint( [px, py], repelem(o, ndoff, 1), patchSz); 78 | 79 | % Interpolate image values at patch points 80 | v = interp2(I, patchx, patchy); 81 | 82 | % Set NaN values to the mean. 83 | % NaNs occur when the patch exceeds the image bounds. 84 | % Note that even after the following steps we may have NaNs in cases where the 85 | % entire patch is zero. 86 | nanIdx = isnan(v); 87 | vprime = v; 88 | vprime(nanIdx) = 0; 89 | vmean = sum(vprime, 2) ./ sum(~nanIdx, 2); 90 | v = vprime + nanIdx .* vmean; 91 | v = reshape(v', patchSz(1), patchSz(2), ndoff, size(ps, 1)); 92 | end 93 | 94 | %% 95 | %% Return coordinates of a patch along point p oriented along the direction o 96 | %% 97 | function [x, y] = orientedPatchAtPoint(p, o, patchSz) 98 | 99 | nSamplesu = patchSz(1); 100 | nSamplesv = patchSz(2); 101 | 102 | t = [o(:, 2) -o(:, 1)]; % The tangent at the point 103 | 104 | pux = repelem( linspace(-patchSz(1)/2, patchSz(1)/2, nSamplesu) .* t(:, 1), nSamplesv, 1); 105 | puy = repelem( linspace(-patchSz(2)/2, patchSz(2)/2, nSamplesu) .* t(:, 2), nSamplesv, 1); 106 | 107 | pvx = [linspace(0, patchSz(1), nSamplesv) .* o(:, 1)]'; 108 | pvy = [linspace(0, patchSz(2), nSamplesv) .* o(:, 2)]'; 109 | pvx = repelem( pvx(:), 1, nSamplesu); 110 | pvy = repelem( pvy(:), 1, nSamplesu); 111 | 112 | x = pvx + pux + repelem(p(:, 1), nSamplesv, nSamplesu); 113 | y = pvy + puy + repelem(p(:, 2), nSamplesv, nSamplesu); 114 | x = x'; 115 | y = y'; 116 | x = x(:); 117 | y = y(:); 118 | x = reshape(x, nSamplesu * nSamplesv, []); 119 | y = reshape(y, nSamplesu * nSamplesv, []); 120 | x = x'; 121 | y = y'; 122 | end 123 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Perform weighted median filtering of the input depth image using the method 3 | %% described in 'Constant Time Weighted Median Filtering for Stereo Matching and Beyond.' 4 | %% The code for filtering in ./wmf was downloaded from Kaiming He's homepage: 5 | %% http://kaiminghe.com/iccv13wmf/matlab_wmf_release_v1.rar 6 | %% 7 | function D = wmf(D, I, q, epsilon, r) 8 | mn = min(min(D)); 9 | mx = max(max(D)); 10 | D = (D - mn) ./ (mx - mn); 11 | D = round(D .* (q - 1)); 12 | D = weighted_median_filter(D, I, [0:q], r, epsilon); 13 | D = medfilt2(D, [3 3]); 14 | D = D ./ q .* (mx - mn) + mn; 15 | end 16 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/boxfilter.m: -------------------------------------------------------------------------------- 1 | function imDst = boxfilter(imSrc, r) 2 | 3 | % BOXFILTER O(1) time box filtering using cumulative sum 4 | % 5 | % - Definition imDst(x, y)=sum(sum(imSrc(x-r:x+r,y-r:y+r))); 6 | % - Running time independent of r; 7 | % - Equivalent to the function: colfilt(imSrc, [2*r+1, 2*r+1], 'sliding', @sum); 8 | % - But much faster. 9 | 10 | [hei, wid] = size(imSrc); 11 | imDst = zeros(size(imSrc)); 12 | 13 | %cumulative sum over Y axis 14 | imCum = cumsum(imSrc, 1); 15 | %difference over Y axis 16 | imDst(1:r+1, :) = imCum(1+r:2*r+1, :); 17 | imDst(r+2:hei-r, :) = imCum(2*r+2:hei, :) - imCum(1:hei-2*r-1, :); 18 | imDst(hei-r+1:hei, :) = repmat(imCum(hei, :), [r, 1]) - imCum(hei-2*r:hei-r-1, :); 19 | 20 | %cumulative sum over X axis 21 | imCum = cumsum(imDst, 2); 22 | %difference over Y axis 23 | imDst(:, 1:r+1) = imCum(:, 1+r:2*r+1); 24 | imDst(:, r+2:wid-r) = imCum(:, 2*r+2:wid) - imCum(:, 1:wid-2*r-1); 25 | imDst(:, wid-r+1:wid) = repmat(imCum(:, wid), [1, r]) - imCum(:, wid-2*r:wid-r-1); 26 | end 27 | 28 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/demo_jpeg.m: -------------------------------------------------------------------------------- 1 | % demo_jpeg.m 2 | 3 | close all; 4 | clear all; 5 | 6 | imgInput = imread('img_jpeg/20.jpg'); 7 | %imgInput = imread('img_jpeg/28.jpg'); 8 | %imgInput = imread('img_jpeg/31.jpg'); 9 | 10 | 11 | %-------------------------------------------------------------------------- 12 | % JPEG Artifact removal example (without downsampling) 13 | 14 | % imgOutput = zeros(size(imgInput), class(imgInput)); 15 | % for c = 1 : size(imgInput,3) 16 | % imgOutput(:,:,c) = ... 17 | % weighted_median_filter(imgInput(:,:,c), imgInput, 0:255, 5, 0.01); 18 | % end 19 | 20 | %-------------------------------------------------------------------------- 21 | % JPEG Artifact removal example (with downsampling) 22 | 23 | nBins = 16; 24 | imgOutput = weighted_median_filter_approx(imgInput, imgInput, 5, 0.01, nBins); 25 | 26 | figure; imshow(imgInput ); title('Input image:'); 27 | figure; imshow(imgOutput); title('Output image:'); 28 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/demo_stereo_refine.m: -------------------------------------------------------------------------------- 1 | % demo_stereo_refine 2 | 3 | close all; 4 | clear all; 5 | 6 | pair_name = 'tsukuba'; 7 | %pair_name = 'venus'; 8 | 9 | if strcmp(pair_name, 'tsukuba') 10 | num_disp = 15; 11 | disp_scale = 16; %% a constant scale for displaying only 12 | elseif strcmp(pair_name, 'venus') 13 | num_disp = 32; 14 | disp_scale = 8; 15 | end 16 | 17 | imgGuide = imread(['img_stereo/',pair_name,'_left.png']); 18 | dispMapInput = imread(['img_stereo/',pair_name,'_boxagg.png']) / disp_scale; 19 | 20 | eps = 0.01^2; 21 | r = ceil(max(size(imgGuide, 1), size(imgGuide, 2)) / 40); 22 | 23 | dispMapOutput = weighted_median_filter(dispMapInput, imgGuide, 1:num_disp, r, eps); 24 | dispMapOutput = medfilt2(dispMapOutput,[3,3]); 25 | 26 | figure; imshow(dispMapInput * disp_scale); title('Input disparity map'); 27 | figure; imshow(dispMapOutput * disp_scale); title('Output disparity map'); 28 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/guidedfilter_color_precompute.m: -------------------------------------------------------------------------------- 1 | function gfobj = guidedfilter_color_precompute(I, r, eps) 2 | % guidedfilter_color_precompute Precomputation of the O(1) time guided filter using a color image as the guidance. 3 | % 4 | % - guidance image: I (should be a color (RGB) image) 5 | % - local window radius: r 6 | % - regularization parameter: eps 7 | 8 | %global gfobj; 9 | 10 | gfobj.I = I; 11 | gfobj.r = r; 12 | gfobj.eps = eps; 13 | 14 | hei = size(I,1); 15 | wid = size(I,2); 16 | gfobj.N = boxfilter(ones(hei, wid), r); % the size of each local patch; N=(2r+1)^2 except for boundary pixels. 17 | 18 | gfobj.mean_I_r = boxfilter(I(:, :, 1), r) ./ gfobj.N; 19 | gfobj.mean_I_g = boxfilter(I(:, :, 2), r) ./ gfobj.N; 20 | gfobj.mean_I_b = boxfilter(I(:, :, 3), r) ./ gfobj.N; 21 | 22 | % variance of I in each local patch: the matrix Sigma in Eqn (14). 23 | % Note the variance in each local patch is a 3x3 symmetric matrix: 24 | % rr, rg, rb 25 | % Sigma = rg, gg, gb 26 | % rb, gb, bb 27 | gfobj.var_I_rr = boxfilter(I(:, :, 1).*I(:, :, 1), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_r; 28 | gfobj.var_I_rg = boxfilter(I(:, :, 1).*I(:, :, 2), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_g; 29 | gfobj.var_I_rb = boxfilter(I(:, :, 1).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_b; 30 | gfobj.var_I_gg = boxfilter(I(:, :, 2).*I(:, :, 2), r) ./ gfobj.N - gfobj.mean_I_g .* gfobj.mean_I_g; 31 | gfobj.var_I_gb = boxfilter(I(:, :, 2).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_g .* gfobj.mean_I_b; 32 | gfobj.var_I_bb = boxfilter(I(:, :, 3).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_b .* gfobj.mean_I_b; 33 | 34 | gfobj.invSigma = cell(hei, wid); 35 | for y=1:hei 36 | for x=1:wid 37 | Sigma = [gfobj.var_I_rr(y, x), gfobj.var_I_rg(y, x), gfobj.var_I_rb(y, x); 38 | gfobj.var_I_rg(y, x), gfobj.var_I_gg(y, x), gfobj.var_I_gb(y, x); 39 | gfobj.var_I_rb(y, x), gfobj.var_I_gb(y, x), gfobj.var_I_bb(y, x)]; 40 | %Sigma = Sigma + eps * eye(3); 41 | 42 | gfobj.invSigma{y, x} = inv(Sigma + eps * eye(3)); % Eqn. (14) in the paper; 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/guidedfilter_color_runfilter.m: -------------------------------------------------------------------------------- 1 | function q = guidedfilter_color_runfilter(p, gfobj) 2 | % guidedfilter_color_runfilter Run O(1) time implementation of guided filter 3 | % 4 | % NOTE: you must call guidedfilter_color_precompute first! 5 | % 6 | % - filtering input image: p (should be a gray-scale/single channel image) 7 | 8 | %global gfobj; 9 | 10 | r = gfobj.r; 11 | 12 | [hei, wid] = size(p); 13 | 14 | mean_p = boxfilter(p, r) ./ gfobj.N; 15 | 16 | mean_Ip_r = boxfilter(gfobj.I(:, :, 1).*p, r) ./ gfobj.N; 17 | mean_Ip_g = boxfilter(gfobj.I(:, :, 2).*p, r) ./ gfobj.N; 18 | mean_Ip_b = boxfilter(gfobj.I(:, :, 3).*p, r) ./ gfobj.N; 19 | 20 | % covariance of (I, p) in each local patch. 21 | cov_Ip_r = mean_Ip_r - gfobj.mean_I_r .* mean_p; 22 | cov_Ip_g = mean_Ip_g - gfobj.mean_I_g .* mean_p; 23 | cov_Ip_b = mean_Ip_b - gfobj.mean_I_b .* mean_p; 24 | 25 | a = zeros(hei, wid, 3); 26 | for y=1:hei 27 | for x=1:wid 28 | cov_Ip = [cov_Ip_r(y, x), cov_Ip_g(y, x), cov_Ip_b(y, x)]; 29 | a(y, x, :) = cov_Ip * gfobj.invSigma{y, x}; % Eqn. (14) in the paper; 30 | end 31 | end 32 | 33 | b = mean_p - a(:, :, 1) .* gfobj.mean_I_r - a(:, :, 2) .* gfobj.mean_I_g - a(:, :, 3) .* gfobj.mean_I_b; % Eqn. (15) in the paper; 34 | 35 | q = (boxfilter(a(:, :, 1), r).* gfobj.I(:, :, 1)... 36 | + boxfilter(a(:, :, 2), r).* gfobj.I(:, :, 2)... 37 | + boxfilter(a(:, :, 3), r).* gfobj.I(:, :, 3)... 38 | + boxfilter(b, r)) ./ gfobj.N; % Eqn. (16) in the paper; 39 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/guidedfilter_color_runfilter_mask.m: -------------------------------------------------------------------------------- 1 | function q = guidedfilter_color_runfilter_mask(p, mask, gfobj) 2 | % guidedfilter_color_runfilter Run O(1) time implementation of guided filter 3 | % 4 | % NOTE: you must call guidedfilter_color_precompute first! 5 | % 6 | % - filtering input image: p (should be a gray-scale/single channel image) 7 | 8 | %global gfobj; 9 | 10 | r = gfobj.r; 11 | 12 | [hei, wid] = size(p); 13 | 14 | mean_p = boxfilter(p, r) ./ gfobj.N; 15 | 16 | mean_Ip_r = boxfilter(gfobj.I(:, :, 1).*p, r) ./ gfobj.N; 17 | mean_Ip_g = boxfilter(gfobj.I(:, :, 2).*p, r) ./ gfobj.N; 18 | mean_Ip_b = boxfilter(gfobj.I(:, :, 3).*p, r) ./ gfobj.N; 19 | 20 | % covariance of (I, p) in each local patch. 21 | cov_Ip_r = mean_Ip_r - gfobj.mean_I_r .* mean_p; 22 | cov_Ip_g = mean_Ip_g - gfobj.mean_I_g .* mean_p; 23 | cov_Ip_b = mean_Ip_b - gfobj.mean_I_b .* mean_p; 24 | 25 | [i, j] = find(mask); 26 | a = zeros(hei, wid, 3); 27 | 28 | for k = 1:length(i) 29 | x = j(k); 30 | y = i(k); 31 | cov_Ip = [cov_Ip_r(y, x), cov_Ip_g(y, x), cov_Ip_b(y, x)]; 32 | a(y, x, :) = cov_Ip * gfobj.invSigma{y, x}; % Eqn. (14) in the paper; 33 | end 34 | 35 | b = mean_p - a(:, :, 1) .* gfobj.mean_I_r - a(:, :, 2) .* gfobj.mean_I_g - a(:, :, 3) .* gfobj.mean_I_b; % Eqn. (15) in the paper; 36 | 37 | q = (boxfilter(a(:, :, 1), r).* gfobj.I(:, :, 1)... 38 | + boxfilter(a(:, :, 2), r).* gfobj.I(:, :, 2)... 39 | + boxfilter(a(:, :, 3), r).* gfobj.I(:, :, 3)... 40 | + boxfilter(b, r)) ./ gfobj.N; % Eqn. (16) in the paper; 41 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/guidedfilter_rgbd_precompute.m: -------------------------------------------------------------------------------- 1 | function gfobj = guidedfilter_rgbd_precompute(I, r, eps) 2 | % guidedfilter_color_precompute Precomputation of the O(1) time guided filter using a color image as the guidance. 3 | % 4 | % - guidance image: I (should be a color (RGB) image) 5 | % - local window radius: r 6 | % - regularization parameter: eps 7 | 8 | %global gfobj; 9 | 10 | gfobj.I = I; 11 | gfobj.r = r; 12 | gfobj.eps = eps; 13 | 14 | hei = size(I,1); 15 | wid = size(I,2); 16 | gfobj.N = boxfilter(ones(hei, wid), r); % the size of each local patch; N=(2r+1)^2 except for boundary pixels. 17 | 18 | gfobj.mean_I_r = boxfilter(I(:, :, 1), r) ./ gfobj.N; 19 | gfobj.mean_I_g = boxfilter(I(:, :, 2), r) ./ gfobj.N; 20 | gfobj.mean_I_b = boxfilter(I(:, :, 3), r) ./ gfobj.N; 21 | gfobj.mean_I_d = boxfilter(I(:, :, 4), r) ./ gfobj.N; 22 | 23 | % variance of I in each local patch: the matrix Sigma in Eqn (14). 24 | % Note the variance in each local patch is a 3x3 symmetric matrix: 25 | % rr, rg, rb 26 | % Sigma = rg, gg, gb 27 | % rb, gb, bb 28 | gfobj.var_I_rr = boxfilter(I(:, :, 1).*I(:, :, 1), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_r; 29 | gfobj.var_I_rg = boxfilter(I(:, :, 1).*I(:, :, 2), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_g; 30 | gfobj.var_I_rb = boxfilter(I(:, :, 1).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_b; 31 | gfobj.var_I_rd = boxfilter(I(:, :, 1).*I(:, :, 4), r) ./ gfobj.N - gfobj.mean_I_r .* gfobj.mean_I_d; 32 | gfobj.var_I_gg = boxfilter(I(:, :, 2).*I(:, :, 2), r) ./ gfobj.N - gfobj.mean_I_g .* gfobj.mean_I_g; 33 | gfobj.var_I_gb = boxfilter(I(:, :, 2).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_g .* gfobj.mean_I_b; 34 | gfobj.var_I_gd = boxfilter(I(:, :, 2).*I(:, :, 4), r) ./ gfobj.N - gfobj.mean_I_g .* gfobj.mean_I_d; 35 | gfobj.var_I_bb = boxfilter(I(:, :, 3).*I(:, :, 3), r) ./ gfobj.N - gfobj.mean_I_b .* gfobj.mean_I_b; 36 | gfobj.var_I_bd = boxfilter(I(:, :, 3).*I(:, :, 4), r) ./ gfobj.N - gfobj.mean_I_b .* gfobj.mean_I_d; 37 | gfobj.var_I_dd = boxfilter(I(:, :, 4).*I(:, :, 4), r) ./ gfobj.N - gfobj.mean_I_d .* gfobj.mean_I_d; 38 | 39 | gfobj.invSigma = cell(hei, wid); 40 | for y=1:hei 41 | for x=1:wid 42 | Sigma = [gfobj.var_I_rr(y, x), gfobj.var_I_rg(y, x), gfobj.var_I_rb(y, x), gfobj.var_I_rd(y, x); 43 | gfobj.var_I_rg(y, x), gfobj.var_I_gg(y, x), gfobj.var_I_gb(y, x), gfobj.var_I_gd(y, x); 44 | gfobj.var_I_rb(y, x), gfobj.var_I_gb(y, x), gfobj.var_I_bb(y, x), gfobj.var_I_bd(y, x); 45 | gfobj.var_I_rd(y, x), gfobj.var_I_gd(y, x), gfobj.var_I_bd(y, x), gfobj.var_I_dd(y, x)]; 46 | %Sigma = Sigma + eps * eye(3); 47 | 48 | gfobj.invSigma{y, x} = inv(Sigma + eps * eye(4)); % Eqn. (14) in the paper; 49 | end 50 | end 51 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/guidedfilter_rgbd_runfilter.m: -------------------------------------------------------------------------------- 1 | function q = guidedfilter_rgbd_runfilter(p, gfobj) 2 | % guidedfilter_color_runfilter Run O(1) time implementation of guided filter 3 | % 4 | % NOTE: you must call guidedfilter_color_precompute first! 5 | % 6 | % - filtering input image: p (should be a gray-scale/single channel image) 7 | 8 | %global gfobj; 9 | 10 | r = gfobj.r; 11 | 12 | [hei, wid] = size(p); 13 | 14 | mean_p = boxfilter(p, r) ./ gfobj.N; 15 | 16 | mean_Ip_r = boxfilter(gfobj.I(:, :, 1).*p, r) ./ gfobj.N; 17 | mean_Ip_g = boxfilter(gfobj.I(:, :, 2).*p, r) ./ gfobj.N; 18 | mean_Ip_b = boxfilter(gfobj.I(:, :, 3).*p, r) ./ gfobj.N; 19 | mean_Ip_d = boxfilter(gfobj.I(:, :, 4).*p, r) ./ gfobj.N; 20 | 21 | % covariance of (I, p) in each local patch. 22 | cov_Ip_r = mean_Ip_r - gfobj.mean_I_r .* mean_p; 23 | cov_Ip_g = mean_Ip_g - gfobj.mean_I_g .* mean_p; 24 | cov_Ip_b = mean_Ip_b - gfobj.mean_I_b .* mean_p; 25 | cov_Ip_d = mean_Ip_d - gfobj.mean_I_d .* mean_p; 26 | 27 | a = zeros(hei, wid, 4); 28 | for y=1:hei 29 | for x=1:wid 30 | cov_Ip = [cov_Ip_r(y, x), cov_Ip_g(y, x), cov_Ip_b(y, x) cov_Ip_d(y, x)]; 31 | a(y, x, :) = cov_Ip * gfobj.invSigma{y, x}; % Eqn. (14) in the paper; 32 | end 33 | end 34 | 35 | b = mean_p - a(:, :, 1) .* gfobj.mean_I_r - a(:, :, 2) .* gfobj.mean_I_g - a(:, :, 3) .* gfobj.mean_I_b - a(:, :, 4) .* gfobj.mean_I_d; % Eqn. (15) in the paper; 36 | 37 | q = (boxfilter(a(:, :, 1), r).* gfobj.I(:, :, 1)... 38 | + boxfilter(a(:, :, 2), r).* gfobj.I(:, :, 2)... 39 | + boxfilter(a(:, :, 3), r).* gfobj.I(:, :, 3)... 40 | + boxfilter(a(:, :, 4), r).* gfobj.I(:, :, 4)... 41 | + boxfilter(b, r)) ./ gfobj.N; % Eqn. (16) in the paper; 42 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/img_jpeg/20.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brownvc/lightfielddepth/9e6344c9fe6122cc1e6d1c83cf26e8bd4d28d3ed/cviewDepthEstim/wmf/img_jpeg/20.jpg -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/img_jpeg/28.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brownvc/lightfielddepth/9e6344c9fe6122cc1e6d1c83cf26e8bd4d28d3ed/cviewDepthEstim/wmf/img_jpeg/28.jpg -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/img_jpeg/31.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brownvc/lightfielddepth/9e6344c9fe6122cc1e6d1c83cf26e8bd4d28d3ed/cviewDepthEstim/wmf/img_jpeg/31.jpg -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/weighted_median_filter.m: -------------------------------------------------------------------------------- 1 | function dispOut = weighted_median_filter(dispIn, imgGuide, vecDisps, r, epsilon) 2 | %weighted_median_filter - Weighted median filter with guided filter weights 3 | % 4 | % dispOut = weighted_median_filter(dispIn, imgGuide, vecDisps, r, epsilon) 5 | % 6 | % INPUT: 7 | % 8 | % dispIn - Input 1-channel discrete disparity map, disparities must 9 | % come from vecDisps 10 | % imgGuide - Input guidance image, should be 3-channel RGB 11 | % vecDisps - Vector of disparities in consideration, must be intergers 12 | % r - Local window radius for guided filter weights 13 | % epsilon - Regularization parameter for guided filter weights 14 | % 15 | 16 | if ~exist('epsilon', 'var') 17 | epsilon = 0.01; 18 | end 19 | 20 | imgGuide = im2double(imgGuide); 21 | 22 | dispOut = zeros( size(dispIn) ); 23 | imgAccum = zeros( size(dispIn) ); 24 | 25 | gfObj = guidedfilter_color_precompute(imgGuide, r, epsilon); 26 | 27 | I = zeros( size(dispOut, 1), size(dispOut, 2), length(vecDisps)); 28 | 29 | parfor (d = 1:numel(vecDisps), 18) 30 | img01 = guidedfilter_color_runfilter(double(dispIn == vecDisps(d)), gfObj); 31 | I(:, :, d) = img01; 32 | end 33 | 34 | % TODO: use cumsum 35 | for d = 1 : numel(vecDisps) 36 | % accumulation to find median disp. for each pixel 37 | imgAccum = imgAccum + I(:, :, d); 38 | idxSelected = (imgAccum > 0.5) & (dispOut == 0); 39 | dispOut(idxSelected) = d; 40 | end 41 | 42 | dispOut = cast(dispOut, class(dispIn)); 43 | 44 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/weighted_median_filter_approx.m: -------------------------------------------------------------------------------- 1 | function imgOut = weighted_median_filter_approx(imgIn, imgGuide, r, epsilon, nBins, sigmaHist) 2 | %weighted_median_filter_approx - Approximated version of weighted median filter with guided filter weights for images 3 | % 4 | % imgOut = weighted_median_filter_approx(imgIn, imgGuide, r, epsilon, nBins, sigmaHist) 5 | % 6 | % INPUT: 7 | % 8 | % imgIn - Input image 9 | % imgGuide - Input guidance image, should be 3-channel RGB 10 | % r - Local window radius for guided filter weights 11 | % epsilon - Regularization parameter for guided filter weights 12 | % nBins - Number of bins for quantizing 13 | % sigmaHist - Sigma for Gaussian smoothed histogram 14 | % 15 | % 16 | % Algorithm: 17 | % 18 | % This approximated version is for filtering images (usually with 256 labels) only. It constructs a 19 | % Gaussian smoothed weighted histogram, then the median can be found via integrating this histogram. 20 | % This is done in our code as convolving each slice with the erf function, which is essentially a low- 21 | % pass filtering, hence downsampling in range space can be used. 22 | % 23 | 24 | if ~exist('epsilon', 'var') 25 | epsilon = 0.01; 26 | end 27 | 28 | if ~exist('nBins', 'var') 29 | nBins = 32; 30 | end 31 | 32 | if ~exist('sigmaHist', 'var') 33 | sigmaHist = 0.06; 34 | end 35 | 36 | imgIn = im2double(imgIn); 37 | imgGuide = im2double(imgGuide); 38 | imgOut = zeros( size(imgIn) ); 39 | 40 | vecDisps = linspace(0, 1, nBins); 41 | 42 | gfObj = guidedfilter_color_precompute(imgGuide, r, epsilon); 43 | 44 | hei = size(imgIn,1); 45 | wid = size(imgIn,2); 46 | weightedIntegralHist = zeros(hei, wid, nBins); 47 | 48 | for c = 1 : size(imgIn,3) 49 | fprintf('Computing channel: %d\n', c); 50 | for d = 1 : nBins 51 | fprintf('%d of %d\n', d, nBins); 52 | 53 | % apply guided filter to the Gaussian integral slice 54 | weightedIntegralHist(:,:,d) = ... 55 | guidedfilter_color_runfilter(... 56 | gaussian_integral(vecDisps(d), imgIn(:,:,c), sigmaHist), gfObj); 57 | end 58 | 59 | % find the interpolated median 60 | 61 | targetVal = 0.49; 62 | 63 | imgOutc = zeros(hei, wid); 64 | 65 | for d = 1 : nBins-1 66 | imgBin1 = weightedIntegralHist(:,:,d); 67 | imgBin2 = weightedIntegralHist(:,:,d+1); 68 | 69 | bin1Val = vecDisps(d); 70 | bin2Val = vecDisps(d+1); 71 | 72 | frac = (targetVal-imgBin1) ./ (imgBin2-imgBin1); 73 | interpolated = bin1Val + frac * (bin2Val - bin1Val); 74 | 75 | idx = imgBin1=targetVal; 76 | imgOutc(idx) = interpolated(idx); 77 | end 78 | 79 | imgOut(:,:,c) = imgOutc; 80 | end 81 | 82 | end 83 | 84 | %-------------------------------------------------------------------------------------- 85 | function y = gaussian_integral(x, mu, sigma) 86 | y = 0.5 * ( 1 + erf((x-mu) / (sigma * 1.41421356237)) ); 87 | end 88 | -------------------------------------------------------------------------------- /cviewDepthEstim/wmf/weighted_median_filter_mask.m: -------------------------------------------------------------------------------- 1 | function dispOut = weighted_median_filter_mask(dispIn, imgGuide, mask, vecDisps, r, epsilon) 2 | %weighted_median_filter - Weighted median filter with guided filter weights 3 | % 4 | % dispOut = weighted_median_filter(dispIn, imgGuide, vecDisps, r, epsilon) 5 | % 6 | % INPUT: 7 | % 8 | % dispIn - Input 1-channel discrete disparity map, disparities must 9 | % come from vecDisps 10 | % imgGuide - Input guidance image, should be 3-channel RGB 11 | % vecDisps - Vector of disparities in consideration, must be intergers 12 | % r - Local window radius for guided filter weights 13 | % epsilon - Regularization parameter for guided filter weights 14 | % 15 | 16 | if ~exist('epsilon', 'var') 17 | epsilon = 0.01; 18 | end 19 | 20 | imgGuide = im2double(imgGuide); 21 | 22 | dispOut = zeros( size(dispIn) ); 23 | imgAccum = zeros( size(dispIn) ); 24 | 25 | gfObj = guidedfilter_color_precompute(imgGuide, r, epsilon); 26 | 27 | I = zeros( size(dispOut, 1), size(dispOut, 2), length(vecDisps)); 28 | 29 | parfor d = 1:numel(vecDisps) 30 | img01 = guidedfilter_color_runfilter_mask(double(dispIn == vecDisps(d)), mask, gfObj); 31 | I(:, :, d) = img01; 32 | end 33 | 34 | for d = 1 : numel(vecDisps) 35 | %fprintf('%d of %d\n', d, numel(vecDisps)); 36 | 37 | % apply guided filter to each slice 38 | % img01 = guidedfilter_color_runfilter(double(dispIn == vecDisps(d))); 39 | 40 | % accumulation to find median disp. for each pixel 41 | imgAccum = imgAccum + I(:, :, d); %img01; 42 | idxSelected = (imgAccum > 0.5) & (dispOut == 0); 43 | dispOut(idxSelected) = d; 44 | end 45 | 46 | dispOut = cast(dispOut, class(dispIn)); 47 | 48 | -------------------------------------------------------------------------------- /depth/reproj.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% This method was adapted from Jiang et al.'s code for performing forward 3 | %% projection of depth and color. We only use it to reproject depth. 4 | %% Jiang et al.'s code can be found at: 5 | %% http://clim.inria.fr/research/DepthEstim/DepthEstim.zip 6 | %% 7 | function [outputFW, maskFW] = reproj(disparity_ref, delY, delX) 8 | 9 | [h, w] = size(disparity_ref); 10 | [X, Y] = meshgrid(1:w, 1:h); 11 | 12 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 13 | %%% Forward propagation from disparity map of the knwon view %%% 14 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 15 | curX_forward = round(X - delX * disparity_ref); 16 | curY_forward = round(Y - delY * disparity_ref); 17 | 18 | maskFW = false(h,w); 19 | %DispFW = zeros(h, w); 20 | DispFW = ones(h, w)*(-1000); 21 | DispFwIdx = zeros(h, w); 22 | NonOverlapped = false(h,w); 23 | 24 | for H = 1:h 25 | for W = 1:w 26 | 27 | if curY_forward(H,W)<=h && curX_forward(H,W)<=w && curY_forward(H,W)>=1 && curX_forward(H,W)>=1 28 | if(~maskFW(curY_forward(H,W),curX_forward(H,W)) ) 29 | maskFW(curY_forward(H,W),curX_forward(H,W)) = true; 30 | DispFW(curY_forward(H,W),curX_forward(H,W)) = disparity_ref(H,W); 31 | DispFwIdx( curY_forward(H, W), curX_forward(H, W) ) = sub2ind( [h, w], H, W); 32 | NonOverlapped(H, W) = true; 33 | 34 | elseif (disparity_ref(H,W) > DispFW(curY_forward(H,W),curX_forward(H,W)) ) 35 | maskFW(curY_forward(H,W),curX_forward(H,W)) = true; 36 | DispFW(curY_forward(H,W),curX_forward(H,W)) = disparity_ref(H,W); 37 | 38 | if DispFwIdx( curY_forward(H, W), curX_forward(H, W) ) ~= 0 39 | NonOverlapped( DispFwIdx( curY_forward(H, W), curX_forward(H, W) ) ) = false; 40 | end 41 | DispFwIdx( curY_forward(H, W), curX_forward(H, W) ) = sub2ind( [h, w], H, W); 42 | NonOverlapped(H, W) = true; 43 | end 44 | 45 | end 46 | end 47 | end 48 | 49 | curX_forward = double(X - delX * disparity_ref); 50 | curY_forward = double(Y - delY * disparity_ref); 51 | curX_forward = curX_forward(NonOverlapped); 52 | curY_forward = curY_forward(NonOverlapped); 53 | 54 | outputFW = zeros(h,w); 55 | ImgRefVec = disparity_ref(NonOverlapped); 56 | outputFW = griddata(curX_forward, curY_forward, ImgRefVec, X, Y, 'linear'); 57 | outputFW = reshape(outputFW,[h,w]); 58 | maskFW = maskFW & ~isnan(outputFW); 59 | end 60 | -------------------------------------------------------------------------------- /depth/reproj2offcenter.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Reproject depth to a non-crosshair view (which can be a novel view) 3 | %% using the depth of the cross hair views provided in U and V 4 | %% 5 | function [D, M] = reproj2offcenter(V, U, vo, uo, param) 6 | 7 | uIdx = min(max(1, round(uo)), param.szLF(4)); 8 | vIdx = min(max(1, round(vo)), param.szLF(3)); 9 | 10 | [ur, um] = reproj(U(:, :, uIdx), param.cviewIdx - vo, 0); 11 | [vr, vm] = reproj(V(:, :, vIdx), 0, param.cviewIdx - uo); 12 | 13 | vm = medfilt2(vm, [3 3]); 14 | um = medfilt2(um, [3 3]); 15 | 16 | M = cat(3, um, vm); 17 | R = cat(3, ur, vr); 18 | R(isnan(R)) = 0; 19 | mc = num2cell(M, 3); 20 | rc = num2cell(R, 3); 21 | 22 | D = cellfun(@(ri, mi) mean(ri(mi ~= 0)), rc, mc); 23 | D(isnan(D)) = 0; 24 | M = sum(M, 3); 25 | end 26 | 27 | -------------------------------------------------------------------------------- /depth/splat.m: -------------------------------------------------------------------------------- 1 | % 2 | % Splat depth labels, weights, and point ids onto an image 3 | % 4 | function [M, S, Id] = splat(D, W, sz) 5 | [D, o] = sortrows(D, 3); % sort so that foreground points are drawn after 6 | 7 | D(:, [1 2]) = round(D(:, [1 2])); 8 | oIdx = D(:, 1) < 1 | D(:, 1) > sz(2) | D(:, 2) < 1 | D(:, 2) > sz(1); 9 | 10 | if size(D, 1) == size(W, 1) 11 | W = W(o); 12 | W(oIdx, :) = []; 13 | end 14 | D(oIdx, :) = []; 15 | sIdx = sub2ind( sz, D(:, 2), D(:, 1) ); 16 | 17 | S = zeros(sz); 18 | S(sIdx) = D(:, 3); 19 | 20 | M = zeros(sz); 21 | M(sIdx) = W; 22 | 23 | Id = zeros(sz); 24 | Id(sIdx) = o(~oIdx); 25 | end 26 | -------------------------------------------------------------------------------- /depth/trilatFilt.m: -------------------------------------------------------------------------------- 1 | % 2 | % Perform trilateral filtering of points in color, depth, and spatial domains 3 | % 4 | function [Q, urIdx] = trilatFilt(P, V, LF, param) 5 | 6 | % Get the color of each point from a view it is visible in. 7 | % 8 | 9 | % We select the visible view closest to the center 10 | [~, v] = min(abs(V .* [1:param.szLF(3) 1:param.szLF(4)] - 5), [], 2); 11 | 12 | % Group points by their visible view 13 | [U, ~, X] = unique(v); 14 | A = accumarray(X, 1:size(P,1), [], @(r) {P(r, :)}); 15 | O = accumarray(X, 1:size(P,1), [], @(r) {r} ); % This is used to unsort A later 16 | C = {}; 17 | 18 | % Calculate color by interpolating at any subpixel locations 19 | for i = 1:length(U) 20 | ui = (U(i) > param.szLF(3)) * (U(i) - param.szLF(3)) + (U(i) <= param.szLF(3)) * (param.cviewIdx); 21 | vi = (U(i) > param.szLF(3)) * (param.cviewIdx) + (U(i) <= param.szLF(3)) * U(i); 22 | 23 | % project points to current view 24 | pi = A{i}; 25 | pi(:, [1 2]) = [ pi(:, 1) + pi(:, 3) .* (ui - param.cviewIdx) ... 26 | pi(:, 2) + pi(:, 3) .* (vi - param.cviewIdx) ]; 27 | lf = LF{U(i)}; 28 | 29 | ci1 = interp2( lf(:, :, 1), pi(:, 1), pi(:, 2) ); 30 | ci2 = interp2( lf(:, :, 2), pi(:, 1), pi(:, 2) ); 31 | ci3 = interp2( lf(:, :, 3), pi(:, 1), pi(:, 2) ); 32 | C(i) = {[ci1 ci2 ci3]}; 33 | end 34 | 35 | Q = vertcat(A{:}); 36 | C = vertcat(C{:}); 37 | X = Q; 38 | 39 | % Rescale the spatial coordinates to accomodate points that overflow the center view 40 | viewportSz = [max(X(:, 2)) - min(X(:, 2)) max(X(:, 1)) - min(X(:, 1))] + 1; 41 | X(:, 1) = X(:, 1) - min(X(:, 1)) + 1; 42 | X(:, 2) = X(:, 2) - min(X(:, 2)) + 1; 43 | 44 | upscaleFactor = 2; 45 | sigmas = const.trilatFiltWinSz ./ 1; 46 | sigmad = param.maxAbsDisparity / 20; 47 | sigmac = 0.5; 48 | winSz = ceil(const.trilatFiltWinSz / 2) * upscaleFactor; 49 | 50 | sz = param.szLF([1 2]) .* upscaleFactor; 51 | X(:, 1) = X(:, 1) .* upscaleFactor; 52 | X(:, 2) = X(:, 2) .* upscaleFactor; 53 | [~, ~, idx] = splat(X, 1, sz); 54 | 55 | d = X(:, 3); 56 | urIdx = zeros(size(d), 'logical'); 57 | 58 | parfor (i = 1:size(X, 1), 6) 59 | pi = X(i, :); 60 | pc = C(i, :); 61 | 62 | win = idx( max(1, round(pi(2)) - winSz): min(sz(1), round(pi(2)) + winSz), ... 63 | max(1, round(pi(1)) - winSz): min(sz(2), round(pi(1)) + winSz) ); 64 | nidx = win(find(win)); 65 | nidx = nidx(nidx ~= i); % Exclude the current point 66 | 67 | if sum(sum(nidx > 0)) < 5 %(isempty(nidx)) 68 | urIdx(i) = true; 69 | continue; 70 | end 71 | 72 | pn = X(nidx, :); 73 | nd = pn(:, 3); % The neighbors' depth 74 | ns = pn(:, [1 2]); % The neighbors' spatial position 75 | nc = C(nidx, :); % The neighbors' (interpolated) color 76 | 77 | wd = normpdf( nd - pi(3), 0, sigmad ); 78 | ws = normpdf( sqrt(sum((ns - pi([1 2])).^2, 2)), 0, sigmas); 79 | wc = normpdf( sqrt(sum((nc - pc).^2, 2)), 0, sigmac); 80 | 81 | w = max(wd .* ws .* wc, eps); 82 | 83 | d(i) = sum(w .* nd) ./ sum(w); 84 | end 85 | 86 | Q(:, 3) = d; 87 | O = vertcat(O{:}); 88 | [~, S] = sort(O); 89 | Q = Q(S, :); 90 | urIdx = urIdx(S, :); 91 | end 92 | -------------------------------------------------------------------------------- /eval/badpixels.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Bad pixels is defined as the percentage of pixels with an error below 3 | %% a specified threshold t 4 | %% 5 | function e = badpixels(dmap, dgt, t) 6 | e = sum(sum(abs(dmap - dgt) > t)) ./ (size(dmap, 1) * size(dmap, 2)); 7 | end 8 | -------------------------------------------------------------------------------- /eval/mse.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Mean squared error times 100 3 | %% 4 | function e = mse(dmap, dgt) 5 | e = mean((dmap - dgt).^2, 'all') * 100; 6 | end 7 | -------------------------------------------------------------------------------- /eval/pairwiseconst.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Return a symmetric num_views x num_views matrix representing the view consistency 3 | %% between each pair of views in the light field 4 | %% 5 | function C = pairwiseconst(D) 6 | szLF = size(D); 7 | numViews = szLF(3) * szLF(4); 8 | 9 | C = zeros( numViews, numViews); 10 | Dc = reshape(num2cell(D, [1 2]), 1, numViews); 11 | 12 | for i = 1:numViews 13 | [vs, us] = ind2sub( szLF([3 4]), i); % source view indices 14 | di = D(:, :, vs, us); 15 | ci = zeros(1, numViews); 16 | 17 | parfor (j = 1:numViews, 24) 18 | 19 | if i >= j 20 | ci(j) = 0; 21 | continue; 22 | end 23 | 24 | [vt, ut] = ind2sub( [szLF(3) szLF(4)], j); % target view indices 25 | 26 | % Project target onto source 27 | [r, m] = reproj( Dc{j}, 0, vt - vs, ut - us); 28 | 29 | R = [r(:) di(:)]; 30 | R(isnan(R)) = 0; 31 | R(~m(:), :) = 0; 32 | vi = var(R, [], 2); 33 | vi(~m(:)) = 0; % ignore disoccluded pixels 34 | 35 | ci(j) = mean(vi, 'all'); 36 | end 37 | C(:, i) = ci; 38 | end 39 | 40 | end 41 | -------------------------------------------------------------------------------- /lahbpcg_mex.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mex.h" 3 | #include "./ImageStack/src/main.h" 4 | #include "./ImageStack/src/Image.h" 5 | #include "./ImageStack/src/LAHBPCG.h" 6 | 7 | using namespace std; 8 | 9 | void lahbpcg_mex(double *d, double *w, double *gx, double *gy, double *o, double niter, double merr, mwSize m, mwSize n) { 10 | ImageStack::Image data(n, m, 1, 1); 11 | ImageStack::Image grad(n, m, 1, 1); 12 | ImageStack::Image data_weight(n, m, 1, 1); 13 | ImageStack::Image gradx_weight(n, m, 1, 1); 14 | ImageStack::Image grady_weight(n, m, 1, 1); 15 | 16 | //cout << "[n, m] = [" << int(n) << ", " << int(m) << "]" <apply(data, grad, grad, data_weight, gradx_weight, grady_weight, niter, merr); 32 | 33 | for (int x = 0; x < n; x++) { 34 | for (int y = 0; y < m; y++) { 35 | int idx = x * m + y; 36 | o[idx] = result(x, y); 37 | } 38 | } 39 | 40 | delete oplahbpcg; 41 | } 42 | 43 | 44 | void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { 45 | if(nrhs != 6) 46 | mexErrMsgIdAndTxt("MexLAHBPCG:nrhs", "Six inputs required."); 47 | 48 | if(nlhs != 1) { 49 | mexErrMsgIdAndTxt("MexLAHBPCG:nlhs", "One output required."); 50 | } 51 | 52 | double *d = mxGetDoubles(prhs[0]); 53 | double *w = mxGetDoubles(prhs[1]); 54 | double *gx = mxGetDoubles(prhs[2]); 55 | double *gy = mxGetDoubles(prhs[3]); 56 | double niter = mxGetScalar(prhs[4]); 57 | double merr = mxGetScalar(prhs[5]); 58 | plhs[0] = mxCreateDoubleMatrix(mxGetM(prhs[0]), mxGetN(prhs[0]), mxREAL); 59 | double *o = mxGetDoubles(plhs[0]); 60 | 61 | 62 | //cout << "Calling" << endl; 63 | lahbpcg_mex(d, w, gx, gy, o, niter, merr, mxGetM(prhs[0]), mxGetN(prhs[0]) ); 64 | } 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /lahbpcg_mex.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brownvc/lightfielddepth/9e6344c9fe6122cc1e6d1c83cf26e8bd4d28d3ed/lahbpcg_mex.mexmaci64 -------------------------------------------------------------------------------- /lines/edges2lines.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Given an edge confidence map E and a slope map Z, fit a line 3 | %% to the edges. The slope of each line is provided in m. 4 | %% 5 | %% The function returns a line set L, where each line is defined by its 6 | %% top and bottom intercept on an EPI. 7 | %% 8 | function L = edges2lines( E, Z, m ) 9 | szEpi = size(E); 10 | 11 | L = cell(szEpi(3), 1); 12 | 13 | parfor i = 1:szEpi(3) 14 | lines = fitLinesEPI( E(:, :, i), Z(:, :, i), m); 15 | 16 | if isempty(lines) 17 | lines = [0 0]; 18 | end 19 | L(i) = {lines}; 20 | end 21 | 22 | end 23 | -------------------------------------------------------------------------------- /lines/epis2edges.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Detect edges by directional filtering with the filters provided 3 | %% in F. The gradient of each filter is specified in gx, and gy 4 | %% 5 | function [E, Z] = epis2edges( EPI, F, m, gx, gy ) 6 | szEpi = [size(EPI, 1) size(EPI, 2) size(EPI, 4)]; 7 | E = zeros( szEpi ); 8 | Z = zeros( szEpi ); 9 | 10 | parfor i = 1:szEpi(3) 11 | [E(:, :, i), Z(:, :, i), ~] = findEdgesEPI( EPI(:, :, :, i), F, m, gx, gy); 12 | end 13 | 14 | end 15 | -------------------------------------------------------------------------------- /lines/filterOutliers.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Remove outliers from the set of EPI lines L. 3 | %% An outlier is a line whos gradient doesn't match the gradient of the corresponding EPI 4 | %% at a minimum specified number of sample points 5 | %% 6 | function L = filterOutliers(L, EPI, gxEPI, gyEPI, param) 7 | 8 | szEPI = size(EPI); 9 | 10 | for i = 1:length(L) 11 | lines = L{i}; 12 | if isempty(lines) 13 | continue; 14 | end 15 | 16 | % 17 | % Remove lines who's gradients don't match EPI gradients over a minimum number of views 18 | 19 | % Get EPI gradients 20 | imgx = gxEPI(:, :, i); 21 | imgy = gyEPI(:, :, i); 22 | 23 | % Calculate line gradients 24 | gx = szEPI(1); 25 | gy = lines(:, 1) - lines(:, 2); 26 | gm = 1 ./ sqrt(gx.^2 + gy.^2); 27 | gx = gx .* gm; 28 | gy = gy .* gm; 29 | 30 | idx = ones(size(lines, 1), 1, 'logical'); 31 | 32 | for j = 1:size(lines, 1) 33 | x = [lines(j, 1) lines(j, 2)]; 34 | y = [1 szEPI(1)]; 35 | 36 | nPoints = szEPI(1); 37 | rIndex = [y(1):y(2)]; 38 | cIndex = max(1, min(round(linspace(x(1), x(2), nPoints)), szEPI(2))); 39 | index = sub2ind([szEPI(1) szEPI(2)], rIndex, cIndex); 40 | 41 | c = abs(gx(j) .* imgx(index) + gy(j) .* imgy(index)); 42 | 43 | c = c > const.filtOutliersGradientDirectionThresh; 44 | if max(accumarray( [cumsum(diff([0 c]) == 1) .* c + 1]', c)) < const.filtOutliersMinContigPixels 45 | idx(j) = 0; 46 | end 47 | 48 | end 49 | L(i) = {lines(idx, :)}; 50 | end 51 | 52 | end 53 | -------------------------------------------------------------------------------- /lines/findEdgesEPI.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Find edges in a single EPI E by directional filtering with 3 | %% the filters provided in F. 4 | %% 5 | function [e, z, c] = findEdgesEPI(E, F, m, gx, gy) 6 | 7 | % Directional filtering 8 | l = zeros( size(E, 1), size(E, 2), size(F, 3)); 9 | a = zeros(size(l)); 10 | b = zeros(size(l)); 11 | 12 | for i = 1:size(F, 3) 13 | l(:, :, i) = abs(conv2(E(:, :, 1), F(:, :, i), 'same')); 14 | a(:, :, i) = abs(conv2(E(:, :, 2), F(:, :, i), 'same')); 15 | b(:, :, i) = abs(conv2(E(:, :, 3), F(:, :, i), 'same')); 16 | end 17 | 18 | % Select filter value with maximum response at each pixel 19 | [ml, mlIdx] = max(l, [], 3); 20 | [ma, maIdx] = max(a, [], 3); 21 | [mb, mbIdx] = max(b, [], 3); 22 | 23 | c = max(cat(3, ml, ma, mb), [], 3); 24 | 25 | % Non-maximal suppression 26 | nl = nms(ml, [gx(mlIdx(:))' gy(mlIdx(:))']) .* ml; 27 | na = nms(ma, [gx(maIdx(:))' gy(maIdx(:))']) .* ma; 28 | nb = nms(mb, [gx(mbIdx(:))' gy(mbIdx(:))']) .* mb; 29 | 30 | % Standard-deviation based modulation 31 | vl = stdfilt( E(:, :, 1) ) .* nl; 32 | va = stdfilt( E(:, :, 2) ) .* na; 33 | vb = stdfilt( E(:, :, 3) ) .* nb; 34 | vl = nl; va = na; vb = nb; 35 | 36 | % Select as edge value the maximum across all channels... 37 | [e, eIdx] = max(cat(3, vl, va, vb), [], 3); 38 | 39 | % ... setting the corresponding pixel values in the slope map 40 | z = (eIdx == 1) .* mlIdx + (eIdx == 2) .* maIdx + (eIdx == 3) .* mbIdx; 41 | end 42 | -------------------------------------------------------------------------------- /lines/fitLinesEPI.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Fit a line to each non-zero pixel in c according to the slope map z 3 | %% The lines are specified by their top and bottom intercepts on the EPI 4 | %% 5 | function l = fitLinesEPI(c, z, m, EPI) 6 | 7 | l = []; 8 | 9 | while sum(sum(c)) > 0 10 | 11 | % We start by fitting the most confident lines 12 | [~, maxIdx] = max(c(:)); 13 | [i, j] = ind2sub( size(c), maxIdx ); 14 | 15 | % Disregard values along the top and bottom edges of the EPI as 16 | % these are usually noisy 17 | if(i == 1 | i == size(c, 1)) | (j == 1 | j == size(c, 2)) 18 | c(i, j) = 0; 19 | continue; 20 | end 21 | p = [i, j]; 22 | 23 | % 24 | % Fit a line at point p. 25 | % A line template is fit according to the slope at point p in the slope map z. 26 | tIdx = z( p(1), p(2) ); 27 | 28 | % 29 | % Clear all pixels in the edge map around the fit line. 30 | % To do this, we calculate the perpendicular distance of each non-zero pixel in 31 | % c from the line with slope m(tIdx) passing through p. 32 | 33 | % A point on the line, in addition to p 34 | q = [0; p(2) + p(1) ./ m(tIdx)]; 35 | 36 | % The pixels for which we want to calculate the distance from the line 37 | [Y, X] = find(c > 0); 38 | 39 | % Calculate perpendical distance from our fit line 40 | D = abs(X .* (q(1) - p(1)) - Y .* (q(2) - p(2)) + q(2) * p(1) - q(1) * p(2)) ./ ... 41 | sqrt( (q(1) - p(1)) .^ 2 + (q(2) - p(2)) .^ 2 ); 42 | 43 | % Select pixels with distance less than desired threshold 44 | D = D < round((const.SegMinWidthMultiplier * size(c, 1))); 45 | idx = sub2ind(size(c), Y, X); 46 | proximalPtsIdx = D .* idx; 47 | proximalPtsIdx = proximalPtsIdx( proximalPtsIdx > 0); 48 | 49 | l = cat(1, l, [tIdx i j]); 50 | 51 | c(i, j) = 0; 52 | c(proximalPtsIdx) = 0; 53 | end 54 | 55 | if ~isempty(l) 56 | % Get the intercepts of the templates on the top and bottom of the EPI 57 | m = m(l(:, 1))'; 58 | xt = l(:, 3) + (l(:, 2) - 1) ./ m; 59 | xb = l(:, 3) + (l(:, 2) - size(c, 1)) ./ m; 60 | l = [xt xb]; 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /lines/genFilters.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Generate 2 * param.nDisparity symmetric directional Prewitt filters. 3 | %% The filters are twice as high as the height of the EPI. 4 | %% 5 | %% The gradient of each filter along the x, and y directions is returned in gx, 6 | %% and gy respectively. The slope in m. 7 | %% 8 | function [F, m, gx, gy] = genFilters(param) 9 | 10 | n = ceil(param.nDisparity/2); 11 | s = expspace( -param.maxAbsDisparity, 0, -1, n); 12 | 13 | h = 2 * param.szEPI(1) + 1; 14 | w = ceil(max(h, max(abs(s)) * h + 2)); 15 | if mod(w, 2) == 0 16 | w = w + 1; 17 | end 18 | xc = ceil(w/2); 19 | yc = ceil(h/2); 20 | 21 | F = zeros(h, w, n * 2 - 1); 22 | gx = zeros(1, n * 2 - 1); 23 | gy = zeros(1, n * 2 - 1); 24 | m = zeros(1, n * 2 - 1); 25 | 26 | [X, Y] = meshgrid(1:w, 1:h); 27 | 28 | for i = 1:n 29 | x = [xc + s(i) * (yc - 1) xc + s(i) * (yc - h)]; 30 | y = [1 h]; 31 | 32 | bwPos = zeros(h, w); 33 | bwPos = wu( bwPos, x(1) - 1, y(1), x(2) - 1, y(2)); 34 | bwPos = bwPos / sum(sum(bwPos)); 35 | 36 | bwNeg = zeros(h, w); 37 | bwNeg = wu( bwNeg, x(1) + 1, y(1), x(2) + 1, y(2)); 38 | bwNeg = (bwNeg / sum(sum(bwNeg))) .* -1; 39 | 40 | F(:, :, i) = bwNeg + bwPos; 41 | 42 | % Calculate the slope and the gradients of the filters 43 | dy = h - 1; 44 | dx = x(1) - x(2); 45 | dm = 1 ./ sqrt(dx.^2 + dy.^2); 46 | gy(i) = -dx .* dm; 47 | gx(i) = dy .* dm; 48 | m(i) = dy ./ dx; 49 | end 50 | 51 | % the next n filters are generated by flipping the existing ones 52 | F(:, :, n+1:end) = fliplr(F(:, :, n-1:-1:1)) .* -1; 53 | gx(n+1:end) = gx(n-1:-1:1); 54 | gy(n+1:end) = -gy(n-1:-1:1); 55 | m(n+1:end) = -m(n-1:-1:1); 56 | end 57 | 58 | 59 | -------------------------------------------------------------------------------- /lines/lf2edges4d.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Edge detection and line fitting 3 | %% 4 | function [P, V] = lf2edges4d(EPIuc, EPIvc, param) 5 | 6 | % Get EPI gradient images 7 | for i = 1:size(EPIvc, 4) 8 | [gxEPIv(:, :, i) gyEPIv(:, :, i)] = imgradientxy(EPIvc(:, :, 1, i)); 9 | gm = sqrt(gxEPIv(:, :, i).^2 + gyEPIv(:, :, i).^2); 10 | gxEPIv(:, :, i) = gxEPIv(:, :, i) ./ gm; 11 | gyEPIv(:, :, i) = gyEPIv(:, :, i) ./ gm; 12 | end 13 | 14 | for i = 1:size(EPIuc, 4) 15 | [gxEPIu(:, :, i) gyEPIu(:, :, i)] = imgradientxy(EPIuc(:, :, 1, i)); 16 | gm = sqrt(gxEPIu(:, :, i).^2 + gyEPIu(:, :, i).^2); 17 | gxEPIu(:, :, i) = gxEPIu(:, :, i) ./ gm; 18 | gyEPIu(:, :, i) = gyEPIu(:, :, i) ./ gm; 19 | end 20 | 21 | % Generate the filters for edge detection, ... 22 | [F, m, gx, gy] = genFilters(param); 23 | 24 | % Calculate the edge confidence and slope maps 25 | [Eu, Zu] = epis2edges( EPIuc, F, m, gx, gy); 26 | [Ev, Zv] = epis2edges( EPIvc, F, m, gx, gy); 27 | 28 | % Fit lines to the edges 29 | Lu = edges2lines(Eu, Zu, m); 30 | Lv = edges2lines(Ev, Zv, m); 31 | 32 | % Remove outliers 33 | Lu = filterOutliers(Lu, EPIuc, gxEPIu, gyEPIu, param); 34 | Lv = filterOutliers(Lv, EPIvc, gxEPIv, gyEPIv, param); 35 | 36 | % Gradient-based line slope(depth)refinement 37 | Lu = refineLineDepth(Lu, gxEPIu, gyEPIu, EPIuc); 38 | Lv = refineLineDepth(Lv, gxEPIv, gyEPIv, EPIvc); 39 | 40 | % Merge lines from vertical and horizontal EPIs 41 | P = merge(Lu, Lv, param.szLF); 42 | 43 | % Determine the visibility of points/lines in each cross-hair view as a boolean matrix V. 44 | % The rows of V represents points/lines; the columns represent the cross-hair views (ordered linearly as vu) 45 | V = pvisible(P, gxEPIu, gyEPIu, gxEPIv, gyEPIv); 46 | 47 | % The central light field view is represented twice - once in the central column and once in the central row. 48 | % If an EPI line/point detected in the *central column* of views is hidden in the central view, 49 | % it is set as hidden in the entire *central row*, and vice versa 50 | idxv = V(:, param.cviewIdx) == 0; 51 | idxu = V(:, param.cviewIdx + param.szLF(3)) == 0; 52 | V(idxv, param.szLF(3) + 1 : end) = 0; 53 | V(idxu, 1:param.szLF(3)) = 0; 54 | 55 | % Remove points visible in less than a minimum number of views as outliers 56 | idx = sum(V, 2) < const.visibilityMinViews; 57 | P(idx, :) = []; 58 | V(idx, :) = []; 59 | end 60 | -------------------------------------------------------------------------------- /lines/merge.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Merge horizontal and vertical EPI lines into a single set of 3D points. 3 | %% Points in the set P are represented by their spatial position in the central view, 4 | %% along with their depth. 5 | %% 6 | function [P, puIdx, pvIdx] = merge(Lu, Lv, szLF) 7 | 8 | Lu = cellfun(@(l, i) [sum(l, 2) ./ 2, ... % x-coordinate 9 | repelem(i, size(l, 1), 1), ... % y-coordinate 10 | (l(:, 2) - l(:, 1)) ./ (szLF(3) - 1)], ... % disparity 11 | Lu, num2cell([1:length(Lu)]'), 'UniformOutput', false); 12 | 13 | Lv = cellfun(@(l, i) [repelem(i, size(l, 1), 1), ... % x-coordinate 14 | sum(l, 2) ./ 2, ... % y-coordinate 15 | (l(:, 2) - l(:, 1)) ./ (szLF(3) - 1)], ... % disparity 16 | Lv, num2cell([1:length(Lv)]'), 'UniformOutput', false); 17 | 18 | Lu = vertcat(Lu{:}); 19 | Lv = vertcat(Lv{:}); 20 | 21 | P = [Lu; Lv]; 22 | puIdx = zeros(size(P, 1), 1, 'logical'); 23 | pvIdx = zeros(size(P, 1), 1, 'logical'); 24 | puIdx([1:size(Lu, 1)]) = 1; 25 | pvIdx([size(Lu, 1) + 1:size(Lu, 1) + size(Lv, 1)]) = 1; 26 | end 27 | -------------------------------------------------------------------------------- /lines/nms.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Non-Maximal Suppression 3 | %% 4 | function s = nms(im, g) 5 | h = size(im, 1); 6 | w = size(im, 2); 7 | 8 | g(:, 2) = -g(:, 2); 9 | 10 | % Get the direction of the two closest pixels in the gradient 11 | % direction on an integer grid. 12 | a = ceil(abs(g)) .* sign(g + eps); 13 | b = (abs(g(:, 1)) > abs(g(:, 2))) .* repmat([1 0], size(g, 1), 1) .* sign(g(:, 1) + eps) + ... 14 | (abs(g(:, 1)) <= abs(g(:, 2))) .* repmat([0 1], size(g, 1), 1) .* sign(g(:, 2) + eps); 15 | theta = atan( abs(g(:, 2)) ./ abs(g(:, 1)) ); 16 | 17 | [X, Y] = meshgrid(1:w, 1:h); 18 | A = sub2ind( size(im), min( h, max(1, Y(:) + a(:, 2))), min( w, max(1, X(:) + a(:, 1))) ); 19 | B = sub2ind( size(im), min( h, max(1, Y(:) + b(:, 2))), min( w, max(1, X(:) + b(:, 1))) ); 20 | 21 | l1 = abs(pi/2 - theta)/ (pi/2); 22 | v = (1 - l1) .* im(A) + l1 .* im(B); 23 | 24 | % The closest pixels to the negative of the gradient 25 | c = -a; 26 | d = -b; 27 | C = sub2ind( size(im), min( h, max(1, Y(:) + c(:, 2))), min( w, max(1, X(:) + c(:, 1))) ); 28 | D = sub2ind( size(im), min( h, max(1, Y(:) + d(:, 2))), min( w, max(1, X(:) + d(:, 1))) ); 29 | w = (1 - l1) .* im(C) + l1 .* im(D); 30 | 31 | s = reshape( (im(:) > v) & (im(:) > w) , size(im, 1), size(im, 2) ); 32 | end 33 | -------------------------------------------------------------------------------- /lines/pvisible.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Get the cross-hair view indices in which each point is visible 3 | %% 4 | function V = pvisible(P, gxEPIu, gyEPIu, gxEPIv, gyEPIv) 5 | 6 | % Group points into lines by rounded y-coordinate 7 | [P, o] = sortrows(P, 2); 8 | [~, ~, X] = unique( round(P(:, 2)) ); 9 | A = accumarray(X, 1:size(P, 1), [], @(r){P(r, :)}); 10 | 11 | U = cell(size(A, 1), 1); 12 | for i = 1:size(A, 1) 13 | a = A{i}; 14 | y = round(a(1, 2)); 15 | if y < 1 | y > size(gxEPIu, 3) 16 | U(i) = {zeros( size(a, 1), size(gxEPIu, 1) )}; 17 | continue; 18 | end 19 | 20 | lines = [a(:, 1) - floor(size(gxEPIu, 1) ./ 2) .* a(:, 3) ... 21 | a(:, 1) + floor(size(gxEPIu, 1) ./ 2) .* a(:, 3)]; 22 | 23 | U(i) = {visibility(lines, gxEPIu(:, :, y), gyEPIu(:, :, y))}; 24 | end 25 | 26 | % Reverse U to original point order 27 | [~, o] = sort(o); 28 | U = vertcat(U{:}); 29 | P = P(o, :); 30 | U = U(o, :); 31 | 32 | % Group points into lines by rounded x-coordinate 33 | [P, o] = sortrows(P, 1); 34 | [~, ~, X] = unique( round(P(:, 1)) ); 35 | A = accumarray(X, 1:size(P, 1), [], @(r){P(r, :)}); 36 | 37 | V = cell(size(A, 1), 1); 38 | for i = 1:size(A, 1) 39 | a = A{i}; 40 | x = round(a(1, 1)); 41 | if x < 1 | x > size(gxEPIv, 3) 42 | V(i) = {zeros( size(a, 1), size(gxEPIv, 1) )}; 43 | continue; 44 | end 45 | 46 | lines = [a(:, 2) - floor(size(gxEPIv, 1) ./ 2) .* a(:, 3) ... 47 | a(:, 2) + floor(size(gxEPIv, 1) ./ 2) .* a(:, 3)]; 48 | 49 | V(i) = {visibility(lines, gxEPIv(:, :, x), gyEPIv(:, :, x))}; 50 | end 51 | 52 | % Reverse V to original point order 53 | [~, o] = sort(o); 54 | V = vertcat(V{:}); 55 | V = V(o, :); 56 | 57 | V = logical([V U]); 58 | end 59 | -------------------------------------------------------------------------------- /lines/refineLineDepth.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Refine the depth of each EPI line by minimizing the entropy of a set of points 3 | %% sampled along the line. 4 | %% 5 | function [L, C] = refineLineDepth(L, gxEPI, gyEPI, EPI) 6 | 7 | parfor k = 1:length(L) 8 | 9 | lk = L{k}; 10 | 11 | epigx = gxEPI(:, :, k); 12 | epigy = gyEPI(:, :, k); 13 | 14 | cprev = linesCost(lk, EPI(:, :, :, k)); 15 | 16 | for j = 1:const.refineIterCount 17 | ti = const.refineTempStart * (const.refineTempAnnealFactor .^ (j - 1)); 18 | dxt = rand(size(lk, 1), 1) * 2 * ti - ti; 19 | dxb = rand(size(lk, 1), 1) * 2 * ti - ti; 20 | 21 | lines = [lk(:, 1) + dxt lk(:, 2) + dxb]; 22 | %c = refineCost(lines, epigx, epigy); 23 | c = linesCost(lines, EPI(:, :, :, k)); 24 | % Update lines for which cost has reduced 25 | idx = c < cprev; 26 | 27 | lk(idx, :) = lines(idx, :); 28 | cprev(idx) = c(idx); 29 | end 30 | L(k) = {lk}; 31 | C(k) = {cprev}; 32 | end 33 | 34 | end 35 | 36 | %% 37 | %% The entropy-based cost of a given line depth assignment 38 | %% 39 | function c = linesCost(lines, epi) 40 | szEpi = [size(epi, 1) size(epi, 2)]; 41 | c = zeros(size(lines, 1), 1); 42 | nSamples = 15; 43 | 44 | % The fractional x values of each line at integer y coordinates 45 | % 46 | m = (lines(:, 1) - lines(:, 2)) ./ (szEpi(1) - 1); 47 | x = min(max(1, lines(:, 1) - m * linspace(0, szEpi(1) - 1, nSamples)) , szEpi(2)); 48 | 49 | xf = floor(x); 50 | xc = ceil(x); 51 | y = repelem(linspace(1, szEpi(1), nSamples), size(lines,1), 1); 52 | w = x - xf; % linear interpolation weights 53 | 54 | % cubic interpolation 55 | [p, q] = meshgrid([1:szEpi(2)], [1:szEpi(1)]); 56 | li = interp2(p, q, epi(:, :, 1), x, y, 'cubic'); 57 | 58 | % Linearly interpolate the luminance value of the line 59 | li = li ./ max(li, [], 2); 60 | c = entropy(li); 61 | end 62 | -------------------------------------------------------------------------------- /lines/visibility.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Get the view indices in which an EPI line is visible. 3 | %% 4 | function b = visibility(l, epigx, epigy) 5 | 6 | szEPI = [size(epigx, 1), size(epigx,2)]; 7 | 8 | b = ones( size(l, 1), size(epigx, 1), 'logical'); 9 | n = size(l, 1); 10 | 11 | % Find all pairs of intersecting lines... 12 | % 13 | u = repmat(l(:, 1), 1, n); 14 | v = repmat(l(:, 2), 1, n); 15 | s = repmat(l(:, 1)', n, 1); 16 | r = repmat(l(:, 2)', n, 1); 17 | 18 | % The foreground/background line is determined by slope 19 | N = ((r <= v & s >= u) | (r >= v & s <= u)); 20 | [lb, lf] = find(N .*((r - s) > (v - u)) > 0); 21 | 22 | % Also get lines that extend outside the visible EPI region 23 | lo = find((l(:, 1) < 1 | l(:, 1) > szEPI(2)) | (l(:, 2) < 1 | l(:, 2) > szEPI(2))); 24 | lb = unique([lb; lo]); 25 | 26 | % Get pixel positions to sample along each background line 27 | % 28 | lbu = l(lb, :); 29 | 30 | m = (lbu(:, 1) - lbu(:, 2)) ./ (szEPI(1) - 1); 31 | x = lbu(:, 1) - m * linspace(0, szEPI(1) - 1, szEPI(1)); 32 | y = repelem(linspace(1, szEPI(1), szEPI(1)), size(lbu, 1), 1); 33 | 34 | % Calculate the gradient of each background line 35 | gx = szEPI(1) - 1; 36 | gy = lbu(:, 1) - lbu(:, 2); 37 | gm = 1 ./ sqrt(gx.^2 + gy.^2); 38 | gx = gx .* gm; 39 | gy = gy .* gm; 40 | 41 | imgx_interp = interp2(epigx, x, y, 'cubic'); 42 | imgy_interp = interp2(epigy, x, y, 'cubic'); 43 | 44 | img_m = 1 ./ sqrt(imgx_interp.^2 + imgy_interp.^2); 45 | imgx_interp = imgx_interp .* img_m; 46 | imgy_interp = imgy_interp .* img_m; 47 | 48 | a = imgx_interp .* gx + imgy_interp .* gy; 49 | b(unique(lb), :) = medfilt2(abs(imgx_interp .* gx + imgy_interp .* gy) > const.visibilityAlignmentThreshold, [1 3]); 50 | end 51 | -------------------------------------------------------------------------------- /lines/wu.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Xiaolin Wu's antialiased line drawing algorithm. 3 | %% Code downloaded from Wikipedia 4 | %% 5 | 6 | function I = wu(I, x0, y0, x1, y1) 7 | 8 | idx = []; 9 | 10 | ipart = @(x) floor(x); % integer part of x 11 | fpart = @(x) x - floor(x); % fractional part of x 12 | rfpart = @(x) 1 - fpart(x); 13 | 14 | steep = abs(y1 - y0) > abs(x1 - x0); 15 | 16 | if steep 17 | [x0, y0] = deal(y0, x0); 18 | [x1, y1] = deal(y1, x1); 19 | end 20 | if x0 > x1 21 | [x0, x1] = deal(x1, x0); 22 | [y0, y1] = deal(y1, y0); 23 | end 24 | 25 | dx = x1 - x0; 26 | dy = y1 - y0; 27 | gradient = dy / dx; 28 | 29 | if dx == 0.0 30 | gradient = 1.0 31 | end 32 | 33 | % first endpoint 34 | xend1 = round(x0); 35 | yend1 = y0 + gradient * (xend1 - x0); 36 | xgap1 = rfpart(x0 + 0.5); 37 | xpxl1 = xend1; % this will be used in the main loop 38 | ypxl1 = ipart(yend1); 39 | 40 | % second endpoint 41 | xend2 = round(x1); 42 | yend2 = y1 + gradient * (xend2 - x1); 43 | xgap2 = fpart(x1 + 0.5); 44 | xpxl2 = xend2; %this will be used in the main loop 45 | ypxl2 = ipart(yend2); 46 | 47 | idx = ones( xpxl2 - 1 - xpxl1, 3); 48 | n = 1; 49 | 50 | if steep 51 | idx(n, :) = [xpxl1, ypxl1, rfpart(yend1) * xgap1]; 52 | idx(n + 1, :) = [xpxl1, ypxl1 + 1, fpart(yend1) * xgap1]; 53 | else 54 | idx(n, :) = [ypxl1, xpxl1, rfpart(yend1) * xgap1]; 55 | idx(n + 1, :) = [ypxl1 + 1, xpxl1, fpart(yend1) * xgap1]; 56 | end 57 | n = n + 2; 58 | intery = yend1 + gradient; % first y-intersection for the main loop 59 | 60 | if steep 61 | idx(n, :) = [xpxl2, ypxl2, rfpart(yend2) * xgap2]; 62 | idx(n + 1, :) = [xpxl2, ypxl2 + 1, fpart(yend2) * xgap2]; 63 | else 64 | idx(n, :) = [ypxl2, xpxl2, rfpart(yend2) * xgap2]; 65 | idx(n + 1, :) = [ypxl2 + 1, xpxl2, fpart(yend2) * xgap2]; 66 | end 67 | n = n + 2; 68 | 69 | % main loop 70 | if steep 71 | for x = xpxl1+1:xpxl2-1 72 | idx(n, :) = [x, ipart(intery), rfpart(intery)]; 73 | idx(n + 1, :) = [x, ipart(intery) + 1, fpart(intery)]; 74 | n = n + 2; 75 | intery = intery + gradient; 76 | end 77 | else 78 | for x = xpxl1+1:xpxl2-1 79 | idx(n, :) = [ipart(intery), x, rfpart(intery)]; 80 | idx(n + 1, :) = [ipart(intery) + 1, x, fpart(intery)]; 81 | n = n + 2; 82 | intery = intery + gradient; 83 | end 84 | end 85 | 86 | idx = idx( (idx(:, 1) > 0 & idx(:, 1) <= size(I, 1)) & ... 87 | (idx(:, 2) > 0 & idx(:, 2) <= size(I, 2)), :); 88 | f = sub2ind( size(I), idx(:, 1), idx(:, 2)); 89 | I(f) = idx(:, 3); 90 | end 91 | -------------------------------------------------------------------------------- /parameters.m: -------------------------------------------------------------------------------- 1 | 2 | classdef parameters 3 | properties 4 | % Multithreading 5 | nWorkers = 3; 6 | 7 | szLF = []; 8 | szEPI = []; 9 | cviewIdx = 0; 10 | 11 | % The code requires the camera to move towards the RIGHT in both the horizontal (u) 12 | % and vertical (v) directions. This ensures a uniform occlusion order for lines 13 | % in an EPI based on slope. 14 | % Set the following parameters to ensure the light field is loaded in the 15 | % correct order. 16 | uCamMovingRight = false; 17 | vCamMovingRight = true; 18 | 19 | % The maximum absolute disparity between two adjacent light field views 20 | maxAbsDisparity = 2.0; 21 | nDisparity = 60; 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | lightfields="'$*'" 4 | matlab -nodisplay -r "runOnLightfields(strsplit($lightfields, ','));exit" 5 | -------------------------------------------------------------------------------- /runOnLightfields.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Run the depth estimation code on multiple lightfields, 3 | %% saving results to file. 4 | %% 5 | function runOnLightfields (D) 6 | addpath('./util', './lines', './depth', './cviewDepthEstim', './cviewDepthEstim/wmf', ... 7 | './angularDiffusion'); 8 | if isempty(D{1}) 9 | disp('Error! No input specified. Please see README.md for help.'); 10 | return; 11 | end 12 | 13 | % Results are saved in a a folder with the current timestamp as the name 14 | % 15 | tstamp = datestr(datetime, 'dd-mmm-yyyy HHMM'); 16 | tstamp( isspace(tstamp) ) = '_'; 17 | folder = ['./results/' tstamp 'hrs']; 18 | mkdir(folder); 19 | 20 | % The output file the name is the name of the light field 21 | fout = {}; 22 | for i = 1:length(D) 23 | [filepath, name, ext] = fileparts( D{i} ); 24 | if isempty(ext) 25 | str = D{i}; 26 | if str(end) == '/' 27 | str(end) = []; 28 | end 29 | s = strsplit(str, '/'); 30 | fout{i} = s{end}; 31 | else 32 | disp('Input Error! Please provide a path to the folder containing light field images'); 33 | end 34 | end 35 | 36 | % Run parameters 37 | % Change these to evaluate the output with different settings for different light fields 38 | param = parameters; 39 | 40 | % Initialize Matlab's parpool 41 | cluster = parcluster('local'); 42 | cluster.NumWorkers = param.nWorkers; 43 | saveProfile(cluster); 44 | delete(gcp('nocreate')); 45 | parpool(param.nWorkers); 46 | 47 | % Run... 48 | for i = 1:length(D) 49 | VCLFD( D{i}, [folder '/' fout{i}], param); 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /util/expspace.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Return n exponentially spaced points between v0 and v1 3 | %% 4 | function v = expspace(v0, v1, d, n) 5 | v = exp(d .* linspace(0, 1, n)); 6 | v = v - min(v); 7 | v = (v ./ max(v)) .* (v0 - v1); 8 | v = v + v1; 9 | end 10 | -------------------------------------------------------------------------------- /util/loadLF.m: -------------------------------------------------------------------------------- 1 | %% 2 | %% Load the light field images into a 5D array: (y, x, rgb, v, u) 3 | %% Indices of the returned array follow Matlab's convention of (row, column): 4 | %% u 5 | %% ----------------------------> 6 | %% | ________ ________ 7 | %% | | x | | x | 8 | %% | | | | | 9 | %% v | | y | | y | .... 10 | %% | | | | | 11 | %% | |________| |________| 12 | %% | : 13 | %% | : 14 | %% v 15 | %% 16 | %% The input files may be in .mat, or 17 | %% alternately, a folder with the light field images (PNGs) may be provided. 18 | 19 | function [LF, dmin, dmax] = loadLF( fin, uCameraMovingRight, vCameraMovingRight, cspace) 20 | 21 | [folder, name, ext] = fileparts(fin); 22 | LF = []; 23 | 24 | if isempty(ext) 25 | % Read the light field from a directory of images. 26 | % Assumes the images in the directory are named in row-major order. 27 | % A file with the name config.txt must be included in the image 28 | % directory which lists the size of the light field as v, u, y, x 29 | 30 | config = fopen(fullfile(fin, 'config.txt'), 'r'); 31 | assert( config > 0, ['Error: No config.txt found at ' fin]); 32 | pm = textscan(config, '%f %f %f %f %f %f', 1); 33 | sz = pm(1:4); 34 | dmin = pm(5); 35 | dmax = pm(6); 36 | fclose(config); 37 | 38 | v = sz{3}; u = sz{4}; y = sz{1}; x = sz{2}; 39 | files = dir(fullfile(fin, '*.png')); 40 | assert( length(files) == u * v, 'Error: Lightfield size mismatch'); 41 | 42 | if strcmp(cspace, 'lab') 43 | LF = zeros(y, x, 3, v, u); 44 | elseif strcmp(cspace, 'gray') 45 | %LF = zeros(y, x, 1, v, u, 'uint8'); 46 | LF = zeros(y, x, 1, v, u); 47 | else 48 | LF = zeros(y, x, 3, v, u); 49 | end 50 | 51 | for i = 1:v 52 | for j = 1:u 53 | filename = fullfile(fin, files((i - 1) * u + j).name); 54 | 55 | if strcmp(cspace, 'lab') 56 | LF(:, :, :, i, j) = rgb2lab(imread(filename)); 57 | elseif strcmp(cspace, 'ycbcr') 58 | LF(:, :, :, i, j) = rgb2ycbcr(imread(filename)); 59 | elseif strcmp(cspace, 'gray') 60 | LF(:, :, 1, i, j) = rgb2gray(imread(filename)); 61 | else 62 | LF(:, :, :, i, j) = (imread(filename)); 63 | end 64 | end 65 | end 66 | elseif strcmp(ext, '.mat') 67 | % Read light field from a .mat file 68 | LF = struct2cell(load(fin)); 69 | LF = LF{1}; 70 | else 71 | disp(['Error: Unrecognized light field file extension ' ext]); 72 | disp("Hint: Use utility function HCIloadLF in runOnLightfields.m to load HCI dataset light fields."); 73 | return; 74 | end 75 | 76 | % Flipping ensures a uniform occlusion order in EPIs 77 | if uCameraMovingRight 78 | LF = flip(LF, 5); 79 | end 80 | if vCameraMovingRight 81 | LF = flip(LF, 4); 82 | end 83 | 84 | end 85 | -------------------------------------------------------------------------------- /view-consistent-depth.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brownvc/lightfielddepth/9e6344c9fe6122cc1e6d1c83cf26e8bd4d28d3ed/view-consistent-depth.gif --------------------------------------------------------------------------------