├── CC_logo.png ├── DEXTR ├── .gitignore ├── LICENSE ├── README.md ├── demo.py ├── doc │ ├── dextr.png │ └── github_teaser.gif ├── helpers │ ├── __init__.py │ ├── helpers.py │ └── pascal_map.npy ├── ims │ ├── bear.jpg │ └── dog-cat.jpg ├── models │ └── download_dextr_model.sh ├── mypath.py └── networks │ ├── __init__.py │ ├── classifiers.py │ ├── dextr.py │ └── resnet.py ├── ExactHistogramMatching ├── LICENSE ├── README.md └── histogram_matching.py ├── INPUT_IMAGE.JPG ├── PCA_Kmeans.py ├── README.md ├── REFERENCE_IMAGE.JPG ├── cd_pcb_results_a.jpg ├── cd_pcb_results_b.jpg ├── conda_changechip.yml ├── crop.py ├── evaluation.py ├── global_variables.py ├── light_differences_elimination.py ├── main.py ├── registration.py ├── run_example.sh └── workflow.PNG /CC_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/CC_logo.png -------------------------------------------------------------------------------- /DEXTR/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.pth 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Pycharm project settings 96 | .idea 97 | 98 | # Rope project settings 99 | .ropeproject 100 | 101 | # mkdocs documentation 102 | /site 103 | 104 | # mypy 105 | .mypy_cache/ 106 | -------------------------------------------------------------------------------- /DEXTR/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 | -------------------------------------------------------------------------------- /DEXTR/README.md: -------------------------------------------------------------------------------- 1 | # Deep Extreme Cut (DEXTR) 2 | Visit our [project page](http://www.vision.ee.ethz.ch/~cvlsegmentation/dextr) for accessing the paper, and the pre-computed results. 3 | 4 | ![DEXTR](doc/dextr.png) 5 | 6 | This is the re-implementation of our work `Deep Extreme Cut (DEXTR)`, for object segmentation from extreme points. Only testing is available, if you would like to train use our original [PyTorch](https://github.com/scaelles/DEXTR-PyTorch) repository. 7 | 8 | ### Abstract 9 | This paper explores the use of extreme points in an object (left-most, right-most, top, bottom pixels) as input to obtain precise object segmentation for images and videos. We do so by adding an extra channel to the image in the input of a convolutional neural network (CNN), which contains a Gaussian centered in each of the extreme points. The CNN learns to transform this information into a segmentation of an object that matches those extreme points. We demonstrate the usefulness of this approach for guided segmentation (grabcut-style), interactive segmentation, video object segmentation, and dense segmentation annotation. We show that we obtain the most precise results to date, also with less user input, in an extensive and varied selection of benchmarks and datasets. 10 | 11 | ### Installation 12 | The code was tested with [Miniconda](https://conda.io/miniconda.html) and Python 3.6. After installing the Miniconda environment: 13 | 14 | 15 | 0. Clone the repo: 16 | ```Shell 17 | git clone https://github.com/scaelles/DEXTR-KerasTensorflow 18 | cd DEXTR-KerasTensorflow 19 | ``` 20 | 21 | 1. Install dependencies: 22 | ```Shell 23 | conda install matplotlib opencv pillow scikit-learn scikit-image h5py 24 | ``` 25 | For CPU mode: 26 | ```Shell 27 | pip install tensorflow keras 28 | ``` 29 | For GPU mode (CUDA 9.0 and cuDNN 7.0 is required for the latest Tensorflow version. If you have CUDA 8.0 and cuDNN 6.0 installed, force the installation of the vesion 1.4 by using ```tensorflow-gpu==1.4```. More information [here](https://www.tensorflow.org/install/)): 30 | ```Shell 31 | pip install tensorflow-gpu keras 32 | ``` 33 | 34 | 35 | 2. Download the model by running the script inside ```models/```: 36 | ```Shell 37 | cd models/ 38 | chmod +x download_dextr_model.sh 39 | ./download_dextr_model.sh 40 | cd .. 41 | ``` 42 | The default model is trained on PASCAL VOC Segmentation train + SBD (10582 images). To download models trained on PASCAL VOC Segmentation train or COCO, please visit our [project page](http://www.vision.ee.ethz.ch/~cvlsegmentation/dextr/#downloads), or keep scrolling till the end of this README. 43 | 44 | 3. To try the demo version of DEXTR, please run: 45 | ```Shell 46 | python demo.py 47 | ``` 48 | If you have multiple GPUs, you can specify which one should be used (for example gpu with id 0): 49 | ```Shell 50 | CUDA_VISIBLE_DEVICES=0 python demo.py 51 | ``` 52 | If installed correctly, the result should look like this: 53 |

54 | 55 | Enjoy!! 56 | 57 | ### Pre-trained models 58 | We provide the following DEXTR models, pre-trained on: 59 | * [PASCAL + SBD](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal-sbd.h5), trained on PASCAL VOC Segmentation train + SBD (10582 images). Achieves mIoU of 91.5% on PASCAL VOC Segmentation val. 60 | * [PASCAL](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal.h5), trained on PASCAL VOC Segmentation train (1464 images). Achieves mIoU of 90.5% on PASCAL VOC Segmentation val. 61 | * [COCO](https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_coco.h5), trained on COCO train 2014 (82783 images). Achieves mIoU of 87.8% on PASCAL VOC Segmentation val. 62 | 63 | ### Annotation tool 64 | [@karan-shr](https://github.com/karan-shr) has built an annotation tool based on DEXTR, which you can find here: 65 | ``` 66 | https://github.com/karan-shr/DEXTR-AnnoTool 67 | ``` 68 | 69 | ### Citation 70 | If you use this code, please consider citing the following papers: 71 | 72 | @Inproceedings{Man+18, 73 | Title = {Deep Extreme Cut: From Extreme Points to Object Segmentation}, 74 | Author = {K.K. Maninis and S. Caelles and J. Pont-Tuset and L. {Van Gool}}, 75 | Booktitle = {Computer Vision and Pattern Recognition (CVPR)}, 76 | Year = {2018} 77 | } 78 | 79 | @InProceedings{Pap+17, 80 | Title = {Extreme clicking for efficient object annotation}, 81 | Author = {D.P. Papadopoulos and J. Uijlings and F. Keller and V. Ferrari}, 82 | Booktitle = {ICCV}, 83 | Year = {2017} 84 | } 85 | 86 | 87 | We thank the authors of [PSPNet-Keras-tensorflow](https://github.com/Vladkryvoruchko/PSPNet-Keras-tensorflow) for making their Keras re-implementation of PSPNet available! 88 | 89 | If you encounter any problems please contact us at {kmaninis, scaelles}@vision.ee.ethz.ch. 90 | -------------------------------------------------------------------------------- /DEXTR/demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3.6 2 | import sys 3 | print(sys.path) 4 | sys.path.append('/home/yonif/.conda/envs/pca_kmeans_change_detection/lib/python3.6/site-packages') 5 | from PIL import Image 6 | import numpy as np 7 | import cv2 8 | from sklearn.cluster import MiniBatchKMeans 9 | import argparse 10 | from matplotlib import pyplot as plt 11 | from keras import backend as K 12 | import tensorflow as tf 13 | from networks.dextr import DEXTR 14 | from mypath import Path 15 | from helpers import helpers as helpers 16 | modelName = 'dextr_pascal-sbd' 17 | pad = 50 18 | thres = 0.8 19 | gpu_id = 0 20 | 21 | 22 | # Handle input and output args 23 | sess = tf.Session() 24 | K.set_session(sess) 25 | 26 | with sess.as_default(): 27 | net = DEXTR(nb_classes=1, resnet_layers=101, input_shape=(512, 512), weights=modelName, 28 | num_input_channels=4, classifier='psp', sigmoid=True) 29 | 30 | # Read image and click the points 31 | image = np.array(Image.open('mlography.jpg')) 32 | plt.ion() 33 | plt.axis('off') 34 | plt.imshow(image) 35 | plt.title('Click the four extreme points of the objects\nHit enter when done (do not close the window)') 36 | 37 | results = [] 38 | 39 | while 1: 40 | extreme_points_ori = np.array(plt.ginput(4, timeout=0)).astype(np.int) 41 | 42 | # Crop image to the bounding box from the extreme points and resize 43 | bbox = helpers.get_bbox(image, points=extreme_points_ori, pad=pad, zero_pad=True) 44 | crop_image = helpers.crop_from_bbox(image, bbox, zero_pad=True) 45 | resize_image = helpers.fixed_resize(crop_image, (512, 512)).astype(np.float32) 46 | 47 | # Generate extreme point heat map normalized to image values 48 | extreme_points = extreme_points_ori - [np.min(extreme_points_ori[:, 0]), np.min(extreme_points_ori[:, 1])] + [pad, 49 | pad] 50 | extreme_points = (512 * extreme_points * [1 / crop_image.shape[1], 1 / crop_image.shape[0]]).astype(np.int) 51 | extreme_heatmap = helpers.make_gt(resize_image, extreme_points, sigma=10) 52 | extreme_heatmap = helpers.cstm_normalize(extreme_heatmap, 255) 53 | 54 | # Concatenate inputs and convert to tensor 55 | input_dextr = np.concatenate((resize_image, extreme_heatmap[:, :, np.newaxis]), axis=2) 56 | 57 | # Run a forward pass 58 | pred = net.model.predict(input_dextr[np.newaxis, ...])[0, :, :, 0] 59 | result = helpers.crop2fullmask(pred, bbox, im_size=image.shape[:2], zero_pad=True, relax=pad) > thres 60 | 61 | results.append(result) 62 | 63 | # Plot the results 64 | plt.imshow(helpers.overlay_masks(image / 255, results)) 65 | plt.plot(extreme_points_ori[:, 0], extreme_points_ori[:, 1], 'gx') 66 | -------------------------------------------------------------------------------- /DEXTR/doc/dextr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/doc/dextr.png -------------------------------------------------------------------------------- /DEXTR/doc/github_teaser.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/doc/github_teaser.gif -------------------------------------------------------------------------------- /DEXTR/helpers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/helpers/__init__.py -------------------------------------------------------------------------------- /DEXTR/helpers/helpers.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import cv2 4 | import random 5 | import numpy as np 6 | 7 | 8 | def tens2image(im): 9 | if im.size()[0] == 1: 10 | tmp = np.squeeze(im.numpy(), axis=0) 11 | else: 12 | tmp = im.numpy() 13 | if tmp.ndim == 2: 14 | return tmp 15 | else: 16 | return tmp.transpose((1, 2, 0)) 17 | 18 | 19 | def crop2fullmask(crop_mask, bbox, im=None, im_size=None, zero_pad=False, relax=0, mask_relax=True, 20 | interpolation=cv2.INTER_CUBIC, scikit=False): 21 | if scikit: 22 | from skimage.transform import resize as sk_resize 23 | assert(not(im is None and im_size is None)), 'You have to provide an image or the image size' 24 | if im is None: 25 | im_si = im_size 26 | else: 27 | im_si = im.shape 28 | # Borers of image 29 | bounds = (0, 0, im_si[1] - 1, im_si[0] - 1) 30 | 31 | # Valid bounding box locations as (x_min, y_min, x_max, y_max) 32 | bbox_valid = (max(bbox[0], bounds[0]), 33 | max(bbox[1], bounds[1]), 34 | min(bbox[2], bounds[2]), 35 | min(bbox[3], bounds[3])) 36 | 37 | # Bounding box of initial mask 38 | bbox_init = (bbox[0] + relax, 39 | bbox[1] + relax, 40 | bbox[2] - relax, 41 | bbox[3] - relax) 42 | 43 | if zero_pad: 44 | # Offsets for x and y 45 | offsets = (-bbox[0], -bbox[1]) 46 | else: 47 | assert((bbox == bbox_valid).all()) 48 | offsets = (-bbox_valid[0], -bbox_valid[1]) 49 | 50 | # Simple per element addition in the tuple 51 | inds = tuple(map(sum, zip(bbox_valid, offsets + offsets))) 52 | 53 | if scikit: 54 | crop_mask = sk_resize(crop_mask, (bbox[3] - bbox[1] + 1, bbox[2] - bbox[0] + 1), order=0, mode='constant').astype(crop_mask.dtype) 55 | else: 56 | crop_mask = cv2.resize(crop_mask, (bbox[2] - bbox[0] + 1, bbox[3] - bbox[1] + 1), interpolation=interpolation) 57 | result_ = np.zeros(im_si) 58 | result_[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1] = \ 59 | crop_mask[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1] 60 | 61 | result = np.zeros(im_si) 62 | if mask_relax: 63 | result[bbox_init[1]:bbox_init[3]+1, bbox_init[0]:bbox_init[2]+1] = \ 64 | result_[bbox_init[1]:bbox_init[3]+1, bbox_init[0]:bbox_init[2]+1] 65 | else: 66 | result = result_ 67 | 68 | return result 69 | 70 | 71 | def overlay_mask(im, ma, colors=None, alpha=0.5): 72 | assert np.max(im) <= 1.0 73 | if colors is None: 74 | colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255. 75 | else: 76 | colors = np.append([[0.,0.,0.]], colors, axis=0); 77 | 78 | if ma.ndim == 3: 79 | assert len(colors) >= ma.shape[0], 'Not enough colors' 80 | ma = ma.astype(np.bool) 81 | im = im.astype(np.float32) 82 | 83 | if ma.ndim == 2: 84 | fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[1, :3] # np.array([0,0,255])/255.0 85 | else: 86 | fg = [] 87 | for n in range(ma.ndim): 88 | fg.append(im * alpha + np.ones(im.shape) * (1 - alpha) * colors[1+n, :3]) 89 | # Whiten background 90 | bg = im.copy() 91 | if ma.ndim == 2: 92 | bg[ma == 0] = im[ma == 0] 93 | bg[ma == 1] = fg[ma == 1] 94 | total_ma = ma 95 | else: 96 | total_ma = np.zeros([ma.shape[1], ma.shape[2]]) 97 | for n in range(ma.shape[0]): 98 | tmp_ma = ma[n, :, :] 99 | total_ma = np.logical_or(tmp_ma, total_ma) 100 | tmp_fg = fg[n] 101 | bg[tmp_ma == 1] = tmp_fg[tmp_ma == 1] 102 | bg[total_ma == 0] = im[total_ma == 0] 103 | 104 | # [-2:] is s trick to be compatible both with opencv 2 and 3 105 | contours = cv2.findContours(total_ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] 106 | cv2.drawContours(bg, contours[0], -1, (0.0, 0.0, 0.0), 1) 107 | 108 | return bg 109 | 110 | 111 | def overlay_masks(im, masks, alpha=0.5): 112 | colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255. 113 | 114 | if isinstance(masks, np.ndarray): 115 | masks = [masks] 116 | 117 | assert len(colors) >= len(masks), 'Not enough colors' 118 | 119 | ov = im.copy() 120 | im = im.astype(np.float32) 121 | total_ma = np.zeros([im.shape[0], im.shape[1]]) 122 | i = 1 123 | for ma in masks: 124 | ma = ma.astype(np.bool) 125 | fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[i, :3] # np.array([0,0,255])/255.0 126 | i = i + 1 127 | ov[ma == 1] = fg[ma == 1] 128 | total_ma += ma 129 | 130 | # [-2:] is s trick to be compatible both with opencv 2 and 3 131 | contours = cv2.findContours(ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:] 132 | cv2.drawContours(ov, contours[0], -1, (0.0, 0.0, 0.0), 1) 133 | ov[total_ma == 0] = im[total_ma == 0] 134 | 135 | return ov 136 | 137 | 138 | def extreme_points(mask, pert): 139 | def find_point(id_x, id_y, ids): 140 | sel_id = ids[0][random.randint(0, len(ids[0]) - 1)] 141 | return [id_x[sel_id], id_y[sel_id]] 142 | 143 | # List of coordinates of the mask 144 | inds_y, inds_x = np.where(mask > 0.5) 145 | 146 | # Find extreme points 147 | return np.array([find_point(inds_x, inds_y, np.where(inds_x <= np.min(inds_x)+pert)), # left 148 | find_point(inds_x, inds_y, np.where(inds_x >= np.max(inds_x)-pert)), # right 149 | find_point(inds_x, inds_y, np.where(inds_y <= np.min(inds_y)+pert)), # top 150 | find_point(inds_x, inds_y, np.where(inds_y >= np.max(inds_y)-pert)) # bottom 151 | ]) 152 | 153 | 154 | def get_bbox(mask, points=None, pad=0, zero_pad=False): 155 | if points is not None: 156 | inds = np.flip(points.transpose(), axis=0) 157 | else: 158 | inds = np.where(mask > 0) 159 | 160 | if inds[0].shape[0] == 0: 161 | return None 162 | 163 | if zero_pad: 164 | x_min_bound = -np.inf 165 | y_min_bound = -np.inf 166 | x_max_bound = np.inf 167 | y_max_bound = np.inf 168 | else: 169 | x_min_bound = 0 170 | y_min_bound = 0 171 | x_max_bound = mask.shape[1] - 1 172 | y_max_bound = mask.shape[0] - 1 173 | 174 | x_min = max(inds[1].min() - pad, x_min_bound) 175 | y_min = max(inds[0].min() - pad, y_min_bound) 176 | x_max = min(inds[1].max() + pad, x_max_bound) 177 | y_max = min(inds[0].max() + pad, y_max_bound) 178 | 179 | return x_min, y_min, x_max, y_max 180 | 181 | 182 | def crop_from_bbox(img, bbox, zero_pad=False): 183 | # Borders of image 184 | bounds = (0, 0, img.shape[1] - 1, img.shape[0] - 1) 185 | 186 | # Valid bounding box locations as (x_min, y_min, x_max, y_max) 187 | bbox_valid = (max(bbox[0], bounds[0]), 188 | max(bbox[1], bounds[1]), 189 | min(bbox[2], bounds[2]), 190 | min(bbox[3], bounds[3])) 191 | 192 | if zero_pad: 193 | # Initialize crop size (first 2 dimensions) 194 | crop = np.zeros((bbox[3] - bbox[1] + 1, bbox[2] - bbox[0] + 1), dtype=img.dtype) 195 | 196 | # Offsets for x and y 197 | offsets = (-bbox[0], -bbox[1]) 198 | 199 | else: 200 | assert(bbox == bbox_valid) 201 | crop = np.zeros((bbox_valid[3] - bbox_valid[1] + 1, bbox_valid[2] - bbox_valid[0] + 1), dtype=img.dtype) 202 | offsets = (-bbox_valid[0], -bbox_valid[1]) 203 | 204 | # Simple per element addition in the tuple 205 | inds = tuple(map(sum, zip(bbox_valid, offsets + offsets))) 206 | 207 | img = np.squeeze(img) 208 | if img.ndim == 2: 209 | crop[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1] = \ 210 | img[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1] 211 | else: 212 | crop = np.tile(crop[:, :, np.newaxis], [1, 1, 3]) # Add 3 RGB Channels 213 | crop[inds[1]:inds[3] + 1, inds[0]:inds[2] + 1, :] = \ 214 | img[bbox_valid[1]:bbox_valid[3] + 1, bbox_valid[0]:bbox_valid[2] + 1, :] 215 | 216 | return crop 217 | 218 | 219 | def fixed_resize(sample, resolution, flagval=None): 220 | 221 | if flagval is None: 222 | if ((sample == 0) | (sample == 1)).all(): 223 | flagval = cv2.INTER_NEAREST 224 | else: 225 | flagval = cv2.INTER_CUBIC 226 | 227 | if isinstance(resolution, int): 228 | tmp = [resolution, resolution] 229 | tmp[np.argmax(sample.shape[:2])] = int(round(float(resolution)/np.min(sample.shape[:2])*np.max(sample.shape[:2]))) 230 | resolution = tuple(tmp) 231 | 232 | if sample.ndim == 2 or (sample.ndim == 3 and sample.shape[2] == 3): 233 | sample = cv2.resize(sample, resolution[::-1], interpolation=flagval) 234 | else: 235 | tmp = sample 236 | sample = np.zeros(np.append(resolution, tmp.shape[2]), dtype=np.float32) 237 | for ii in range(sample.shape[2]): 238 | sample[:, :, ii] = cv2.resize(tmp[:, :, ii], resolution[::-1], interpolation=flagval) 239 | return sample 240 | 241 | 242 | def crop_from_mask(img, mask, relax=0, zero_pad=False): 243 | if mask.shape[:2] != img.shape[:2]: 244 | mask = cv2.resize(mask, dsize=tuple(reversed(img.shape[:2])), interpolation=cv2.INTER_NEAREST) 245 | 246 | assert(mask.shape[:2] == img.shape[:2]) 247 | 248 | bbox = get_bbox(mask, pad=relax, zero_pad=zero_pad) 249 | 250 | if bbox is None: 251 | return None 252 | 253 | crop = crop_from_bbox(img, bbox, zero_pad) 254 | 255 | return crop 256 | 257 | 258 | def make_gaussian(size, sigma=10, center=None, d_type=np.float64): 259 | """ Make a square gaussian kernel. 260 | size: is the dimensions of the output gaussian 261 | sigma: is full-width-half-maximum, which 262 | can be thought of as an effective radius. 263 | """ 264 | 265 | x = np.arange(0, size[1], 1, float) 266 | y = np.arange(0, size[0], 1, float) 267 | y = y[:, np.newaxis] 268 | 269 | if center is None: 270 | x0 = y0 = size[0] // 2 271 | else: 272 | x0 = center[0] 273 | y0 = center[1] 274 | 275 | return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / sigma ** 2).astype(d_type) 276 | 277 | 278 | def make_gt(img, labels, sigma=10, one_mask_per_point=False): 279 | """ Make the ground-truth for landmark. 280 | img: the original color image 281 | labels: label with the Gaussian center(s) [[x0, y0],[x1, y1],...] 282 | sigma: sigma of the Gaussian. 283 | one_mask_per_point: masks for each point in different channels? 284 | """ 285 | h, w = img.shape[:2] 286 | if labels is None: 287 | gt = make_gaussian((h, w), center=(h//2, w//2), sigma=sigma) 288 | else: 289 | labels = np.array(labels) 290 | if labels.ndim == 1: 291 | labels = labels[np.newaxis] 292 | if one_mask_per_point: 293 | gt = np.zeros(shape=(h, w, labels.shape[0])) 294 | for ii in range(labels.shape[0]): 295 | gt[:, :, ii] = make_gaussian((h, w), center=labels[ii, :], sigma=sigma) 296 | else: 297 | gt = np.zeros(shape=(h, w), dtype=np.float64) 298 | for ii in range(labels.shape[0]): 299 | gt = np.maximum(gt, make_gaussian((h, w), center=labels[ii, :], sigma=sigma)) 300 | 301 | gt = gt.astype(dtype=img.dtype) 302 | 303 | return gt 304 | 305 | 306 | def cstm_normalize(im, max_value): 307 | """ 308 | Normalize image to range 0 - max_value 309 | """ 310 | imn = max_value*(im - im.min()) / max((im.max() - im.min()), 1e-8) 311 | return imn 312 | 313 | 314 | def generate_param_report(logfile, param): 315 | log_file = open(logfile, 'w') 316 | for key, val in param.items(): 317 | log_file.write(key+':'+str(val)+'\n') 318 | log_file.close() 319 | -------------------------------------------------------------------------------- /DEXTR/helpers/pascal_map.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/helpers/pascal_map.npy -------------------------------------------------------------------------------- /DEXTR/ims/bear.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/ims/bear.jpg -------------------------------------------------------------------------------- /DEXTR/ims/dog-cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/ims/dog-cat.jpg -------------------------------------------------------------------------------- /DEXTR/models/download_dextr_model.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Model trained on PASCAL + SBD 4 | wget https://data.vision.ee.ethz.ch/csergi/share/DEXTR/dextr_pascal-sbd.h5 5 | -------------------------------------------------------------------------------- /DEXTR/mypath.py: -------------------------------------------------------------------------------- 1 | 2 | class Path(object): 3 | @staticmethod 4 | def models_dir(): 5 | return 'DEXTR/models/' 6 | -------------------------------------------------------------------------------- /DEXTR/networks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/DEXTR/networks/__init__.py -------------------------------------------------------------------------------- /DEXTR/networks/classifiers.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | 3 | from keras.layers.merge import Concatenate, Add 4 | from keras.layers import AveragePooling2D, ZeroPadding2D 5 | 6 | from keras.layers import Activation 7 | from keras.layers import Conv2D 8 | from keras.layers import Layer 9 | 10 | from DEXTR.networks import resnet 11 | import keras.backend as K 12 | from keras.backend import tf as ktf 13 | 14 | class Upsampling(Layer): 15 | 16 | def __init__(self, new_size, **kwargs): 17 | self.new_size = new_size 18 | super(Upsampling, self).__init__(**kwargs) 19 | 20 | def build(self, input_shape): 21 | super(Upsampling, self).build(input_shape) 22 | 23 | def call(self, inputs, **kwargs): 24 | new_height, new_width = self.new_size 25 | resized = ktf.image.resize_images(inputs, [new_height, new_width], 26 | align_corners=True) 27 | return resized 28 | 29 | def compute_output_shape(self, input_shape): 30 | return tuple([None, self.new_size[0], self.new_size[1], input_shape[3]]) 31 | 32 | def get_config(self): 33 | config = super(Upsampling, self).get_config() 34 | config['new_size'] = self.new_size 35 | return config 36 | 37 | 38 | def psp_block(prev_layer, level, feature_map_shape, input_shape): 39 | if input_shape == (512, 512): 40 | kernel_strides_map = {1: [64, 64], 41 | 2: [32, 32], 42 | 3: [22, 21], 43 | 6: [11, 9]} # TODO: Level 6: Kernel correct, but stride not exactly the same as Pytorch 44 | else: 45 | raise ValueError("Pooling parameters for input shape " + input_shape + " are not defined.") 46 | 47 | if K.image_data_format() == 'channels_last': 48 | bn_axis = 3 49 | else: 50 | bn_axis = 1 51 | 52 | names = [ 53 | "class_psp_" + str(level) + "_conv", 54 | "class_psp_" + str(level) + "_bn" 55 | ] 56 | kernel = (kernel_strides_map[level][0], kernel_strides_map[level][0]) 57 | strides = (kernel_strides_map[level][1], kernel_strides_map[level][1]) 58 | prev_layer = AveragePooling2D(kernel, strides=strides)(prev_layer) 59 | prev_layer = Conv2D(512, (1, 1), strides=(1, 1), name=names[0], use_bias=False)(prev_layer) 60 | prev_layer = resnet.BN(bn_axis, name=names[1])(prev_layer) 61 | prev_layer = Activation('relu')(prev_layer) 62 | prev_layer = Upsampling(feature_map_shape)(prev_layer) 63 | return prev_layer 64 | 65 | 66 | def build_pyramid_pooling_module(res, input_shape, nb_classes, sigmoid=False, output_size=None): 67 | """Build the Pyramid Pooling Module.""" 68 | # ---PSPNet concat layers with Interpolation 69 | feature_map_size = tuple(int(ceil(input_dim / 8.0)) for input_dim in input_shape) 70 | if K.image_data_format() == 'channels_last': 71 | bn_axis = 3 72 | else: 73 | bn_axis = 1 74 | print("PSP module will interpolate to a final feature map size of %s" % 75 | (feature_map_size, )) 76 | 77 | interp_block1 = psp_block(res, 1, feature_map_size, input_shape) 78 | interp_block2 = psp_block(res, 2, feature_map_size, input_shape) 79 | interp_block3 = psp_block(res, 3, feature_map_size, input_shape) 80 | interp_block6 = psp_block(res, 6, feature_map_size, input_shape) 81 | 82 | # concat all these layers. resulted 83 | res = Concatenate()([interp_block1, 84 | interp_block2, 85 | interp_block3, 86 | interp_block6, 87 | res]) 88 | x = Conv2D(512, (1, 1), strides=(1, 1), padding="same", name="class_psp_reduce_conv", use_bias=False)(res) 89 | x = resnet.BN(bn_axis, name="class_psp_reduce_bn")(x) 90 | x = Activation('relu')(x) 91 | 92 | x = Conv2D(nb_classes, (1, 1), strides=(1, 1), name="class_psp_final_conv")(x) 93 | 94 | if output_size: 95 | x = Upsampling(output_size)(x) 96 | 97 | if sigmoid: 98 | x = Activation('sigmoid')(x) 99 | return x 100 | -------------------------------------------------------------------------------- /DEXTR/networks/dextr.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from os.path import splitext, join 3 | import numpy as np 4 | from scipy import misc 5 | from keras import backend as K 6 | 7 | import tensorflow as tf 8 | import DEXTR.networks.resnet as resnet 9 | 10 | from DEXTR.mypath import Path 11 | 12 | 13 | class DEXTR(object): 14 | """Pyramid Scene Parsing Network by Hengshuang Zhao et al 2017""" 15 | 16 | def __init__(self, nb_classes, resnet_layers, input_shape, weights, num_input_channels=4, 17 | classifier='psp', use_numpy=False, sigmoid=False): 18 | self.input_shape = input_shape 19 | self.num_input_channels = num_input_channels 20 | self.sigmoid = sigmoid 21 | self.model = resnet.build_network(nb_classes=nb_classes, resnet_layers=resnet_layers, num_input_channels=num_input_channels, 22 | input_shape=self.input_shape, classifier=classifier, sigmoid=self.sigmoid, output_size=self.input_shape) 23 | if use_numpy: 24 | print("No Keras model & weights found, import from npy weights.") 25 | self.set_npy_weights(weights) 26 | else: 27 | print("Loading weights from H5 file.") 28 | h5_path = join(Path.models_dir(), weights + '.h5') 29 | self.model.load_weights(h5_path) 30 | 31 | def predict(self, img): 32 | # Preprocess 33 | img = misc.imresize(img, self.input_shape) 34 | img = img.astype('float32') 35 | probs = self.feed_forward(img) 36 | return probs 37 | 38 | def feed_forward(self, data): 39 | print("Predicting...") 40 | assert data.shape == (self.input_shape[0], self.input_shape[1], self.num_input_channels) 41 | prediction = self.model.predict(np.expand_dims(data, 0))[0] 42 | print("Finished prediction...") 43 | return prediction 44 | 45 | def set_npy_weights(self, weights_path): 46 | npy_weights_path = join("weights", "npy", weights_path + ".npy") 47 | h5_path = join(Path.models_dir(), weights_path + '.h5') 48 | # h5_path_model = join("models", weights_path + ".h5") 49 | 50 | print("Importing weights from %s" % npy_weights_path) 51 | weights = np.load(npy_weights_path, encoding='bytes').item() 52 | for layer in self.model.layers: 53 | # print('{}'.format(layer.name)) 54 | if layer.name[:2] == 'bn' or layer.name[-2:] == 'bn': 55 | print('{}'.format(layer.name)) 56 | # print('{} {}'.format(layer.name, layer.get_weights()[0].shape)) 57 | gamma = weights[layer.name]['gamma'] 58 | beta = weights[layer.name]['beta'] 59 | moving_mean = weights[layer.name]['moving_mean'] 60 | moving_variance = weights[layer.name]['moving_variance'] 61 | 62 | self.model.get_layer(layer.name).set_weights([gamma, beta, moving_mean, moving_variance]) 63 | 64 | elif layer.name[:3] == 'res' or layer.name[-4:] == 'conv' or layer.name[:4] == 'conv': 65 | print('{}'.format(layer.name)) 66 | # print('{} {}'.format(layer.name, layer.get_weights()[0].shape)) 67 | if len(self.model.get_layer(layer.name).get_weights()) == 2: 68 | weight = weights[layer.name]['weights'] 69 | biases = weights[layer.name]['biases'] 70 | if biases is None: 71 | raise ValueError('Bias inconsistency') 72 | self.model.get_layer(layer.name).set_weights([weight, biases]) 73 | else: 74 | weight = weights[layer.name]['weights'] 75 | self.model.get_layer(layer.name).set_weights([weight]) 76 | 77 | print('Finished importing weights.') 78 | 79 | print("Writing keras weights") 80 | self.model.save_weights(h5_path) 81 | # models.save_model(self.model, h5_path_model, include_optimizer=False) 82 | 83 | print("Finished writing Keras model & weights") 84 | 85 | 86 | if __name__ == "__main__": 87 | classifier = 'psp' 88 | input_size = 512 89 | num_input_channels = 4 90 | resnet_size = 101 91 | image = 'ims/dog_512.png' 92 | extreme_points = 'ims/dog_512_extreme.png' 93 | 94 | input_type = 'bbox' if num_input_channels == 3 else 'extreme' 95 | 96 | model = 'dextr_pascal-sbd' 97 | 98 | # Handle input and output args 99 | sess = tf.Session() 100 | K.set_session(sess) 101 | 102 | with sess.as_default(): 103 | dextr = DEXTR(nb_classes=1, resnet_layers=resnet_size, input_shape=(input_size, input_size), weights=model, 104 | num_input_channels=num_input_channels, classifier=classifier, use_numpy=False, sigmoid=True) 105 | 106 | img = misc.imread(image, mode='RGB') 107 | if num_input_channels == 4: 108 | extreme = misc.imread(extreme_points) 109 | 110 | img_extreme = np.zeros((input_size, input_size, 4)) 111 | img_extreme[:, :, :3] = img 112 | img_extreme[:, :, 3] = extreme 113 | img_extreme = np.expand_dims(img_extreme.astype('float32'), 0) 114 | else: 115 | img_extreme = np.expand_dims(img.astype('float32'), 0) 116 | 117 | pred = dextr.model.predict(img_extreme)[0, :, :, 0] 118 | 119 | mask = pred > 0.8 120 | 121 | filename, ext = splitext(image) 122 | 123 | misc.imsave(filename + "_seg_"+ classifier + ext, mask.astype(np.uint8)*255) 124 | -------------------------------------------------------------------------------- /DEXTR/networks/resnet.py: -------------------------------------------------------------------------------- 1 | from keras.layers import Input 2 | from keras import layers 3 | from keras.layers import Activation 4 | from keras.layers import Conv2D 5 | from keras.layers import MaxPooling2D 6 | from keras.layers import ZeroPadding2D 7 | from keras.layers import BatchNormalization 8 | from keras.models import Model 9 | 10 | import keras.backend as K 11 | 12 | from DEXTR.networks.classifiers import build_pyramid_pooling_module 13 | 14 | 15 | def BN(axis, name=""): 16 | return BatchNormalization(axis=axis, momentum=0.1, name=name, epsilon=1e-5) 17 | 18 | 19 | def identity_block(input_tensor, kernel_size, filters, stage, block, dilation=1): 20 | """The identity block is the block that has no conv layer at shortcut. 21 | 22 | # Arguments 23 | input_tensor: input tensor 24 | kernel_size: defualt 3, the kernel size of middle conv layer at main path 25 | filters: list of integers, the filterss of 3 conv layer at main path 26 | stage: integer, current stage label, used for generating layer names 27 | block: 'a','b'..., current block label, used for generating layer names 28 | dilation: dilation of the intermediate convolution 29 | 30 | # Returns 31 | Output tensor for the block. 32 | """ 33 | filters1, filters2, filters3 = filters 34 | if K.image_data_format() == 'channels_last': 35 | bn_axis = 3 36 | else: 37 | bn_axis = 1 38 | conv_name_base = 'res' + str(stage) + block + '_branch' 39 | bn_name_base = 'bn' + str(stage) + block + '_branch' 40 | 41 | x = Conv2D(filters1, (1, 1), name=conv_name_base + '2a', use_bias=False)(input_tensor) 42 | x = BN(axis=bn_axis, name=bn_name_base + '2a')(x) 43 | x = Activation('relu')(x) 44 | 45 | x = Conv2D(filters2, kernel_size, padding='same', name=conv_name_base + '2b', use_bias=False, dilation_rate=dilation)(x) 46 | x = BN(axis=bn_axis, name=bn_name_base + '2b')(x) 47 | x = Activation('relu')(x) 48 | 49 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x) 50 | x = BN(axis=bn_axis, name=bn_name_base + '2c')(x) 51 | 52 | x = layers.add([x, input_tensor]) 53 | x = Activation('relu')(x) 54 | return x 55 | 56 | 57 | def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(1, 1), dilation=1): 58 | """conv_block is the block that has a conv layer at shortcut 59 | 60 | # Arguments 61 | input_tensor: input tensor 62 | kernel_size: defualt 3, the kernel size of middle conv layer at main path 63 | filters: list of integers, the filterss of 3 conv layer at main path 64 | stage: integer, current stage label, used for generating layer names 65 | block: 'a','b'..., current block label, used for generating layer names 66 | 67 | # Returns 68 | Output tensor for the block. 69 | 70 | Note that from stage 3, the first conv layer at main path is with strides=(2,2) 71 | And the shortcut should have strides=(2,2) as well 72 | """ 73 | filters1, filters2, filters3 = filters 74 | if K.image_data_format() == 'channels_last': 75 | bn_axis = 3 76 | else: 77 | bn_axis = 1 78 | conv_name_base = 'res' + str(stage) + block + '_branch' 79 | bn_name_base = 'bn' + str(stage) + block + '_branch' 80 | 81 | x = Conv2D(filters1, (1, 1), strides=strides, name=conv_name_base + '2a', use_bias=False)(input_tensor) 82 | x = BN(axis=bn_axis, name=bn_name_base + '2a')(x) 83 | x = Activation('relu')(x) 84 | 85 | x = Conv2D(filters2, kernel_size, padding='same', name=conv_name_base + '2b', use_bias=False, dilation_rate=dilation)(x) 86 | x = BN(axis=bn_axis, name=bn_name_base + '2b')(x) 87 | x = Activation('relu')(x) 88 | 89 | x = Conv2D(filters3, (1, 1), name=conv_name_base + '2c', use_bias=False)(x) 90 | x = BN(axis=bn_axis, name=bn_name_base + '2c')(x) 91 | 92 | shortcut = Conv2D(filters3, (1, 1), strides=strides, name=conv_name_base + '1', use_bias=False)(input_tensor) 93 | shortcut = BN(axis=bn_axis, name=bn_name_base + '1')(shortcut) 94 | 95 | x = layers.add([x, shortcut]) 96 | x = Activation('relu')(x) 97 | return x 98 | 99 | 100 | def ResNet101(input_tensor=None): 101 | 102 | img_input = input_tensor 103 | if K.image_data_format() == 'channels_last': 104 | bn_axis = 3 105 | else: 106 | bn_axis = 1 107 | 108 | x = ZeroPadding2D((3, 3))(img_input) 109 | x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', use_bias=False)(x) 110 | x = BN(axis=bn_axis, name='bn_conv1')(x) 111 | x = Activation('relu')(x) 112 | x = ZeroPadding2D((1, 1))(x) 113 | x = MaxPooling2D((3, 3), strides=(2, 2), padding='valid')(x) 114 | 115 | x = conv_block(x, 3, [64, 64, 256], stage=2, block='a') 116 | x = identity_block(x, 3, [64, 64, 256], stage=2, block='b') 117 | x = identity_block(x, 3, [64, 64, 256], stage=2, block='c') 118 | 119 | x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', strides=(2, 2)) 120 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='b') 121 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='c') 122 | x = identity_block(x, 3, [128, 128, 512], stage=3, block='d') 123 | 124 | x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', dilation=2) 125 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', dilation=2) 126 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', dilation=2) 127 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', dilation=2) 128 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', dilation=2) 129 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', dilation=2) 130 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='g', dilation=2) 131 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='h', dilation=2) 132 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='i', dilation=2) 133 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='j', dilation=2) 134 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='k', dilation=2) 135 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='l', dilation=2) 136 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='m', dilation=2) 137 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='n', dilation=2) 138 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='o', dilation=2) 139 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='p', dilation=2) 140 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='q', dilation=2) 141 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='r', dilation=2) 142 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='s', dilation=2) 143 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='t', dilation=2) 144 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='u', dilation=2) 145 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='v', dilation=2) 146 | x = identity_block(x, 3, [256, 256, 1024], stage=4, block='w', dilation=2) 147 | 148 | x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', dilation=4) 149 | x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', dilation=4) 150 | x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', dilation=4) 151 | 152 | return x 153 | 154 | 155 | def build_network(nb_classes, input_shape, resnet_layers=101, classifier='psp', sigmoid=False, output_size=None, 156 | num_input_channels=4): 157 | """Build Network""" 158 | inp = Input((input_shape[0], input_shape[1], num_input_channels)) 159 | if resnet_layers == 101: 160 | res = ResNet101(inp) 161 | else: 162 | ValueError('Resnet {} does not exist'.format(resnet_layers)) 163 | if classifier == 'psp': 164 | print("Building network based on ResNet %i and PSP module expecting inputs of shape %s predicting %i classes" % ( 165 | resnet_layers, input_shape, nb_classes)) 166 | x = build_pyramid_pooling_module(res, input_shape, nb_classes, sigmoid=sigmoid, output_size=output_size) 167 | else: 168 | raise ValueError('Classifier not implemented.') 169 | model = Model(inputs=inp, outputs=x) 170 | 171 | return model 172 | -------------------------------------------------------------------------------- /ExactHistogramMatching/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /ExactHistogramMatching/README.md: -------------------------------------------------------------------------------- 1 | # Exact Histogram Specification 2 | This is a Python implementation of *Exact Histogram Specification* by *Dinu Coltuc et al.* 3 | 4 | In contrast to traditional histogram matching algorithms which only approximate a reference histogram, 5 | this technique can match the exact reference histograms. 6 | This is accomplished by using several kernels which calculate the average of a neighbourhood. 7 | Thereby a pixel can not only be sorted after its value, but also after its average values in more than one neighbourhood. 8 | This helps to create a truely bijective function which is a prerequisite for exact histogram matching. 9 | 10 | More information can be found in the [original paper](https://www.researchgate.net/publication/7109912_Exact_Histogram_Specification) or 11 | in Digital Image Processing, 4th Edition, chapter 3.3 which describes the algorithm more concise. 12 | -------------------------------------------------------------------------------- /ExactHistogramMatching/histogram_matching.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | """ 4 | @license: Apache License Version 2.0 5 | @author: Stefano Di Martino 6 | Exact histogram matching 7 | """ 8 | 9 | 10 | import numpy as np 11 | from scipy import signal 12 | 13 | 14 | class ExactHistogramMatcher: 15 | _kernel1 = 1.0 / 5.0 * np.array([[0, 1, 0], 16 | [1, 1, 1], 17 | [0, 1, 0]]) 18 | 19 | _kernel2 = 1.0 / 9.0 * np.array([[1, 1, 1], 20 | [1, 1, 1], 21 | [1, 1, 1]]) 22 | 23 | _kernel3 = 1.0 / 13.0 * np.array([[0, 0, 1, 0, 0], 24 | [0, 1, 1, 1, 0], 25 | [1, 1, 1, 1, 1], 26 | [0, 1, 1, 1, 0], 27 | [0, 0, 1, 0, 0]]) 28 | 29 | _kernel4 = 1.0 / 21.0 * np.array([[0, 1, 1, 1, 0], 30 | [1, 1, 1, 1, 1], 31 | [1, 1, 1, 1, 1], 32 | [1, 1, 1, 1, 1], 33 | [0, 1, 1, 1, 0]]) 34 | 35 | _kernel5 = 1.0 / 25.0 * np.array([[1, 1, 1, 1, 1], 36 | [1, 1, 1, 1, 1], 37 | [1, 1, 1, 1, 1], 38 | [1, 1, 1, 1, 1], 39 | [1, 1, 1, 1, 1]]) 40 | _kernel_mapping = {1: [_kernel1], 41 | 2: [_kernel1, _kernel2], 42 | 3: [_kernel1, _kernel2, _kernel3], 43 | 4: [_kernel1, _kernel2, _kernel3, _kernel4], 44 | 5: [_kernel1, _kernel2, _kernel3, _kernel4, _kernel5]} 45 | 46 | @staticmethod 47 | def get_histogram(image, image_bit_depth=8): 48 | """ 49 | :param image: image as numpy array 50 | :param image_bit_depth: bit depth of the image. Most images have 8 bit. 51 | :return: 52 | """ 53 | max_grey_value = pow(2, image_bit_depth) 54 | 55 | if len(image.shape) == 3: 56 | dimensions = image.shape[2] 57 | hist = np.empty((max_grey_value, dimensions)) 58 | 59 | for dimension in range(0, dimensions): 60 | for gray_value in range(0, max_grey_value): 61 | image_2d = image[:, :, dimension] 62 | hist[gray_value, dimension] = len(image_2d[image_2d == gray_value]) 63 | else: 64 | hist = np.empty((max_grey_value,)) 65 | 66 | for gray_value in range(0, max_grey_value): 67 | hist[gray_value] = len(image[image == gray_value]) 68 | 69 | return hist 70 | 71 | @staticmethod 72 | def _get_averaged_images(img, kernels): 73 | return np.array([signal.convolve2d(img, kernel, 'same') for kernel in kernels]) 74 | 75 | @staticmethod 76 | def _get_average_values_for_every_pixel(img, number_kernels): 77 | """ 78 | :param img: the image to be used in order to calculate averaged images 79 | :param number_kernels: number of kernels to be used in order to calculate the averaged images 80 | :return: averaged images with the shape: 81 | (image height * image width, number averaged images) 82 | Every row represents one pixel and its averaged values. 83 | I. e. x[0] represents the first pixel and contains an array with k 84 | averaged pixels where k are the number of used kernels. 85 | """ 86 | kernels = ExactHistogramMatcher._kernel_mapping[number_kernels] 87 | averaged_images = ExactHistogramMatcher._get_averaged_images(img, kernels) 88 | img_size = averaged_images[0].shape[0] * averaged_images[0].shape[1] 89 | 90 | # shape of averaged_images: (number averaged images, height, width). 91 | # Reshape in a way, that one row contains all averaged values of pixel in position (x, y) 92 | reshaped_averaged_images = averaged_images.reshape((number_kernels, img_size)) 93 | transposed_averaged_images = reshaped_averaged_images.transpose() 94 | return transposed_averaged_images 95 | 96 | @staticmethod 97 | def sort_rows_lexicographically(matrix): 98 | # Because lexsort in numpy sorts after the last row, 99 | # then after the second last row etc., we have to rotate 100 | # the matrix in order to sort all rows after the first column, 101 | # and then after the second column etc. 102 | 103 | rotated_matrix = np.rot90(matrix) 104 | 105 | # TODO lexsort is very memory hungry! If the image is too big, this can result in SIG 9! 106 | sorted_indices = np.lexsort(rotated_matrix) 107 | return matrix[sorted_indices] 108 | 109 | @staticmethod 110 | def _match_to_histogram(image, reference_histogram, number_kernels): 111 | """ 112 | :param image: image as numpy array. 113 | :param reference_histogram: reference histogram as numpy array 114 | :param number_kernels: The more kernels you use in order to calculate average images, 115 | the more likely it is, the resulting image will have the exact 116 | histogram like the reference histogram 117 | :return: The image with the exact reference histogram. 118 | """ 119 | img_size = image.shape[0] * image.shape[1] 120 | 121 | merged_images = np.empty((img_size, number_kernels + 2)) 122 | 123 | # The first column are the original pixel values. 124 | merged_images[:, 0] = image.reshape((img_size,)) 125 | 126 | # The last column of this array represents the flattened image indices. 127 | # These indices are necessary to keep track of the pixel positions 128 | # after they haven been sorted lexicographically according their values. 129 | indices_of_flattened_image = np.arange(img_size).transpose() 130 | merged_images[:, -1] = indices_of_flattened_image 131 | 132 | # Calculate average images and add them to merged_images 133 | averaged_images = ExactHistogramMatcher._get_average_values_for_every_pixel(image, number_kernels) 134 | for dimension in range(0, number_kernels): 135 | merged_images[:, dimension + 1] = averaged_images[:, dimension] 136 | 137 | # Sort the array according the original pixels values and then after 138 | # the average values of the respective pixel 139 | sorted_merged_images = ExactHistogramMatcher.sort_rows_lexicographically(merged_images) 140 | 141 | # Assign gray values according the distribution of the reference histogram 142 | index_start = 0 143 | for gray_value in range(0, len(reference_histogram)): 144 | index_end = int(index_start + reference_histogram[gray_value]) 145 | sorted_merged_images[index_start:index_end, 0] = gray_value 146 | index_start = index_end 147 | 148 | # Sort back ordered by the flattened image index. The last column represents the index 149 | sorted_merged_images = sorted_merged_images[sorted_merged_images[:, -1].argsort()] 150 | new_target_img = sorted_merged_images[:, 0].reshape(image.shape) 151 | 152 | return new_target_img 153 | 154 | @staticmethod 155 | def match_image_to_histogram(image, reference_histogram, number_kernels=5): 156 | """ 157 | :param image: image as numpy array. 158 | :param reference_histogram: reference histogram as numpy array 159 | :param number_kernels: The more kernels you use in order to calculate average images, 160 | the more likely it is, the resulting image will have the exact 161 | histogram like the reference histogram 162 | :return: The image with the exact reference histogram. 163 | CAUTION: Don't save the image in a lossy format like JPEG, 164 | because the compression algorithm will alter the histogram! 165 | Use lossless formats like PNG. 166 | """ 167 | if len(image.shape) == 3: 168 | # Image with more than one dimension. I. e. an RGB image. 169 | output = np.empty(image.shape) 170 | dimensions = image.shape[2] 171 | 172 | for dimension in range(0, dimensions): 173 | output[:, :, dimension] = ExactHistogramMatcher._match_to_histogram(image[:, :, dimension], 174 | reference_histogram[:, dimension], 175 | number_kernels) 176 | else: 177 | # Gray value image 178 | output = ExactHistogramMatcher._match_to_histogram(image, 179 | reference_histogram, 180 | number_kernels) 181 | 182 | return output 183 | -------------------------------------------------------------------------------- /INPUT_IMAGE.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/INPUT_IMAGE.JPG -------------------------------------------------------------------------------- /PCA_Kmeans.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from numpy import savetxt 3 | from scipy.misc import imread, imsave, imresize 4 | from sklearn.cluster import KMeans 5 | from sklearn.cluster import DBSCAN 6 | from sklearn.decomposition import PCA 7 | from skimage import color 8 | import global_variables 9 | import cv2 10 | import matplotlib.pyplot as plt 11 | import seaborn as sns 12 | 13 | def get_descriptors (image1, image2, window_size, pca_dim_gray, pca_dim_rgb): 14 | 15 | ################################################# grayscale-diff (abs) 16 | 17 | descriptors = np.zeros((image1.shape[0],image1.shape[1], window_size * window_size)) 18 | diff_image = cv2.absdiff(image1, image2) 19 | diff_image = color.rgb2gray(diff_image) 20 | imsave(global_variables.output_dir + '/diff.jpg', diff_image) 21 | diff_image = np.pad(diff_image,((window_size // 2, window_size // 2), (window_size // 2, window_size // 2)), 22 | 'constant') # default is 0 23 | for i in range(image1.shape[0]): 24 | for j in range(image1.shape[1]): 25 | descriptors[i,j,:] =diff_image[i:i+window_size,j:j+window_size].ravel() 26 | descriptors_gray_diff = descriptors.reshape((descriptors.shape[0] * descriptors.shape[1], descriptors.shape[2])) 27 | 28 | ################################################# 3-channels-diff (abs) 29 | 30 | descriptors = np.zeros((image1.shape[0], image1.shape[1], window_size * window_size*3)) 31 | diff_image_r = cv2.absdiff(image1[:, :, 0],image2[:, :, 0]) 32 | diff_image_g = cv2.absdiff(image1[:, :, 1],image2[:, :, 1]) 33 | diff_image_b = cv2.absdiff(image1[:, :, 2],image2[:, :, 2]) 34 | 35 | if (global_variables.save_extra_stuff): 36 | imsave(global_variables.output_dir + '/final_diff.jpg', cv2.absdiff(image1, image2)) 37 | imsave(global_variables.output_dir +'/final_diff_r.jpg', diff_image_r) 38 | imsave(global_variables.output_dir + '/final_diff_g.jpg', diff_image_g) 39 | imsave(global_variables.output_dir + '/final_diff_b.jpg', diff_image_b) 40 | 41 | diff_image_r = np.pad(diff_image_r, ((window_size // 2, window_size // 2), (window_size // 2, window_size // 2)), 42 | 'constant') # default is 0 43 | diff_image_g = np.pad(diff_image_g, 44 | ((window_size // 2, window_size // 2), (window_size // 2, window_size // 2)), 45 | 'constant') # default is 0 46 | diff_image_b = np.pad(diff_image_b, 47 | ((window_size // 2, window_size // 2), (window_size // 2, window_size // 2)), 48 | 'constant') # default is 0 49 | 50 | for i in range(image1.shape[0]): 51 | for j in range(image1.shape[1]): 52 | feature_r = diff_image_r[i:i + window_size, j:j + window_size].ravel() 53 | feature_g = diff_image_g[i:i + window_size, j:j + window_size].ravel() 54 | feature_b = diff_image_b[i:i + window_size, j:j + window_size].ravel() 55 | descriptors[i, j, :] = np.concatenate((feature_r, feature_g, feature_b)) 56 | descriptors_rgb_diff = descriptors.reshape((descriptors.shape[0] * descriptors.shape[1], descriptors.shape[2])) 57 | 58 | ################################################# concatination 59 | 60 | descriptors_gray_diff = descriptors_to_pca(descriptors_gray_diff, pca_dim_gray,window_size) 61 | descriptors_colored_diff = descriptors_to_pca(descriptors_rgb_diff, pca_dim_rgb,window_size) 62 | 63 | descriptors = np.concatenate((descriptors_gray_diff, descriptors_colored_diff), axis=1) 64 | 65 | return descriptors 66 | 67 | 68 | #assumes descriptors is already flattened 69 | #returns descriptors after moving them into the PCA vector space 70 | def descriptors_to_pca(descriptors, pca_target_dim, window_size): 71 | vector_set, mean_vec = find_vector_set(descriptors,window_size) 72 | pca = PCA(pca_target_dim) 73 | pca.fit(vector_set) 74 | EVS = pca.components_ 75 | mean_vec = np.dot(mean_vec, EVS.transpose()) 76 | FVS = find_FVS(descriptors, EVS.transpose(), mean_vec) 77 | return FVS 78 | 79 | 80 | #The returned vector_set goes later to the PCA algorithm which derives the EVS (Eigen Vector Space). 81 | #Therefore, there is a mean normalization of the data 82 | #jump_size is for iterating non-overlapping windows. This parameter should be eqaul to the window_size of the system 83 | def find_vector_set(descriptors, jump_size): 84 | descriptors_2d = descriptors.reshape((global_variables.size_0, global_variables.size_1, descriptors.shape[1])) 85 | vector_set = descriptors_2d[::jump_size,::jump_size] 86 | vector_set = vector_set.reshape((vector_set.shape[0]*vector_set.shape[1], vector_set.shape[2])) 87 | mean_vec = np.mean(vector_set, axis=0) 88 | vector_set = vector_set - mean_vec # mean normalization 89 | return vector_set, mean_vec 90 | 91 | #returns the FSV (Feature Vector Space) which then goes directly to clustering (with Kmeans) 92 | #Multiply the data with the EVS to get the entire data in the PCA target space 93 | def find_FVS(descriptors, EVS, mean_vec): 94 | FVS = np.dot(descriptors, EVS) 95 | FVS = FVS - mean_vec 96 | print("\nfeature vector space size", FVS.shape) 97 | return FVS 98 | 99 | #Creates the change map, according to a specified number of clusters and the other parameters 100 | def compute_change_map(image1, image2, window_size=5, clusters=16, pca_dim_gray=3, pca_dim_rgb=9): 101 | descriptors = get_descriptors(image1, image2, window_size, pca_dim_gray, pca_dim_rgb) 102 | # Now we are ready for clustering! 103 | change_map = Kmeansclustering(descriptors, clusters, image1.shape) 104 | mse_array, size_array = clustering_to_mse_values(change_map, image1, image2, clusters) 105 | sorted_indexes = np.argsort(mse_array) 106 | colors_array = [plt.cm.jet(float(np.argwhere(sorted_indexes == class_))/(clusters-1)) for class_ in range(clusters)] 107 | colored_change_map = np.zeros((change_map.shape[0], change_map.shape[1], 3), np.uint8) 108 | palette_colored_change_map = np.zeros((change_map.shape[0], change_map.shape[1], 3), np.uint8) 109 | palette = sns.color_palette("Paired", clusters) 110 | for i in range(change_map.shape[0]): 111 | for j in range(change_map.shape[1]): 112 | colored_change_map[i, j]= (255*colors_array[change_map[i,j]][0],255*colors_array[change_map[i,j]][1],255*colors_array[change_map[i,j]][2]) 113 | palette_colored_change_map[i, j] = [255*palette[change_map[i, j]][0],255*palette[change_map[i, j]][1],255*palette[change_map[i, j]][2]] 114 | 115 | if (global_variables.save_extra_stuff): 116 | imsave(global_variables.output_dir+ '/window_size_'+str(window_size)+'_pca_dim_gray'+str(pca_dim_gray)+'_pca_dim_rgb' 117 | +str(pca_dim_rgb)+'_clusters_'+ str(clusters) + '.jpg', colored_change_map) 118 | imsave(global_variables.output_dir + '/PALETTE_window_size_' + str(window_size) + '_pca_dim_gray' + str(pca_dim_gray) + '_pca_dim_rgb' 119 | + str(pca_dim_rgb) + '_clusters_' + str(clusters) + '.jpg', palette_colored_change_map) 120 | 121 | #Saving Output for later evaluation 122 | savetxt(global_variables.output_dir+ '/clustering_data.csv', change_map, delimiter=',') 123 | return change_map, mse_array, size_array 124 | 125 | def Kmeansclustering(FVS, components, images_size): 126 | kmeans = KMeans(components, verbose=0) 127 | kmeans.fit(FVS) 128 | flatten_change_map = kmeans.predict(FVS) 129 | change_map = np.reshape(flatten_change_map, (images_size[0],images_size[1])) 130 | return change_map 131 | 132 | #calculates the mse value for each cluster of change_map 133 | def clustering_to_mse_values(change_map, img1, img2, n): 134 | mse = [0.0 for i in range (0,n)] 135 | size = [0 for i in range (0,n)] 136 | img1 = img1.astype(int) 137 | img2 = img2.astype(int) 138 | for i in range(change_map.shape[0]): 139 | for j in range(change_map.shape[1]): 140 | mse[change_map[i,j]] += np.mean((img1[i,j]-img2[i,j])**2) 141 | size[change_map[i,j]] += 1 142 | return [(mse[k]/(255**2))/size[k] for k in range (0,n)], size 143 | 144 | 145 | #clustering is the clustering map which is de-facto a list that in index #class_ has a list of indexes of the pixels that belong to that class. 146 | #n is the number of classes 147 | #img1 and img2 are the 2 images to compute the MSE values on 148 | #the function returns a list of arrays, in each there are the classes that should be for this result. Each array is called a combination. 149 | def find_groups(MSE_array, size_array, n, problem_size): 150 | results_groups = [] 151 | class_number_arr = [x for x in range(n)] 152 | plt.figure() 153 | plt.xticks(class_number_arr) 154 | plt.xlabel('Index') 155 | plt.ylabel('MSE') 156 | zipped = zip(MSE_array,size_array, class_number_arr) 157 | #sort according to increasing MSE values 158 | zipped= sorted(zipped) 159 | max_mse = np.max(MSE_array) 160 | zipped_filtered = [(mse, size, class_num) for mse, size, class_num in zipped if (mse>= 0.1 * max_mse and size<0.1*problem_size)] 161 | MSE_filtered_sorted = [mse for mse, size, class_num in zipped_filtered] 162 | number_class_filtered_sorted = [class_num for mse, size, class_num in zipped_filtered] 163 | 164 | #save output for later evaluation if needed 165 | savetxt(global_variables.output_dir + '/mse_filtered_sorted.csv', MSE_filtered_sorted, delimiter=',') 166 | savetxt(global_variables.output_dir + '/classes_filtered_sorted.csv', number_class_filtered_sorted, delimiter=',') 167 | 168 | print(MSE_filtered_sorted[::-1]) #decreasing MSE values 169 | plt.scatter([i for i in range(len(MSE_filtered_sorted))], MSE_filtered_sorted[::-1] , c='red') 170 | plt.savefig(global_variables.output_dir+"/mse.png") 171 | 172 | consecutive_diff = np.diff(MSE_filtered_sorted) 173 | if len(number_class_filtered_sorted) == 0: 174 | print("No (small) changes detected") 175 | exit(0) 176 | elif len(consecutive_diff) ==0: 177 | results_groups.append([number_class_filtered_sorted[0]]) 178 | else: 179 | max = len(number_class_filtered_sorted)-1 180 | while (max >0 and num_results>0): 181 | num_results = num_results -1 182 | max = np.argmax(consecutive_diff) 183 | consecutive_diff = consecutive_diff[:max] 184 | results_groups.append(number_class_filtered_sorted[max+1:]) 185 | if(max==0 and num_results>0): 186 | results_groups.append(number_class_filtered_sorted) 187 | return results_groups 188 | 189 | #selects the classes to be shown to the user as 'changes'. 190 | #this selection is done by an MSE heuristic using DBSCAN clustering, to seperate the highest mse-valued classes from the others. 191 | #the eps density parameter of DBSCAN might differ from system to system 192 | def find_group_of_accepted_classes_DBSCAN(MSE_array): 193 | print(MSE_array) 194 | clustering = DBSCAN(eps=0.02, min_samples=1).fit(np.array(MSE_array).reshape(-1,1)) 195 | number_of_clusters = len(set(clustering.labels_)) 196 | if number_of_clusters == 1: 197 | print("No significant changes are detected.") 198 | exit(0) 199 | #print(clustering.labels_) 200 | classes = [[] for i in range(number_of_clusters)] 201 | centers = [0 for i in range(number_of_clusters)] 202 | for i in range(len(MSE_array)): 203 | centers[clustering.labels_[i]] += MSE_array[i] 204 | classes[clustering.labels_[i]].append(i) 205 | 206 | centers = [centers[i]/len(classes[i]) for i in range(number_of_clusters)] 207 | min_class = centers.index(min(centers)) 208 | accepted_classes = [] 209 | for i in range(len(MSE_array)): 210 | if clustering.labels_[i] != min_class: 211 | accepted_classes.append(i) 212 | plt.figure() 213 | plt.xlabel('Index') 214 | plt.ylabel('MSE') 215 | plt.scatter(range(len(MSE_array)), MSE_array, c="red") 216 | print(accepted_classes) 217 | print(np.array(MSE_array)[np.array(accepted_classes)]) 218 | plt.scatter(accepted_classes[:], np.array(MSE_array)[np.array(accepted_classes)], c="blue") 219 | plt.title('K Mean Classification') 220 | plt.savefig(global_variables.output_dir+"/mse.png") 221 | 222 | #save output for later evaluation 223 | savetxt(global_variables.output_dir + '/accepted_classes.csv', accepted_classes, delimiter=',') 224 | return [accepted_classes] 225 | 226 | #save output for later evaluation 227 | savetxt(global_variables.output_dir + '/accepted_classes.csv', accepted_classes, delimiter=',') 228 | return [accepted_classes] 229 | 230 | #the 'changes' are drawn on the input image (with some transparency) 231 | #combination is the list of classes to appear in the result. 232 | #the color of each class is determined by its order of magnitude according to a jet palette. 233 | def draw_combination_on_transparent_input_image(classes_mse, clustering, combination, transparent_input_image): 234 | 235 | # HEAT MAP ACCORDING TO MSE ORDER 236 | sorted_indexes = np.argsort(classes_mse) 237 | for class_ in combination: 238 | c = plt.cm.jet(float(np.argwhere(sorted_indexes == class_))/(len(classes_mse)-1)) 239 | for [i, j] in clustering[class_]: 240 | transparent_input_image[i, j] = (c[2] * 255, c[1] * 255, c[0] * 255, 255) #BGR 241 | return transparent_input_image 242 | 243 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChangeChip 2 | 3 | 4 | *ChangeChip* was developed to detect changes between an inspected PCB image and a reference (golden) PCB image, in order to detect defects in the inspected PCB.\ 5 | The system is based on Image Processing, Computer Vision and Unsupervised Machine Learning.\ 6 | *ChangeChip* is targeted to handle optical images, and also radiographic images, and may be applicable to other technologies as well.\ 7 | We note that *ChangeChip* is not limited to PCBs only, and may be suitable to other systems that require object comparison by their images. 8 | The workflow of *ChangeChip* is presented as follows: 9 | 10 | 11 | 12 | ## Requirements: 13 | - Download the DEXTR model (for the optinal cropping stage): 14 | ``` 15 | cd DEXTR/models/ 16 | chmod +x download_dextr_model.sh 17 | ./download_dextr_model.sh 18 | cd ../.. 19 | ``` 20 | - Conda Requirements: 21 | 22 | Building environment from ```yml``` file (recommended): 23 | 24 | ```conda env create --name envname --file=conda_changechip.yml``` 25 | 26 | Or, create a new conda environment with the following packages: 27 | ``` 28 | conda install pytorch torchvision -c pytorch 29 | conda install numpy scipy matplotlib 30 | conda install opencv pillow scikit-learn scikit-image 31 | conda install keras tensorflow 32 | ``` 33 | ## Running: 34 | - Run the following command under the conda environment with your spesific directory and images paths, and change the values of the system parameters, if needed. 35 | ``` 36 | python main.py -output_dir OUTPUT_DIR 37 | -input_path INPUT_IMAGE.JPG 38 | -reference_path REFERENCE_IMAGE.JPG 39 | -n 16 40 | -window_size 5 41 | -pca_dim_gray 3 42 | -pca_dim_rgb 9 43 | -resize_factor 1 44 | -lighting_fix 45 | -use_homography 46 | -save_extra_stuff 47 | ``` 48 | You can either run ```./run_exmaple.sh```. 49 | # CD-PCB 50 | As part of this work, a small dataset of 20 pairs of PCBs images was created, with annotated changes between them. This dataset is proposed for evaluation of change detection algorithms in the PCB Inspection field. The dataset is available [here](https://drive.google.com/file/d/1b1GFuKS88nKaH-Nfx2XmlhwulUxMwwBA/view?usp=sharing). 51 | 52 | --- 53 | 54 | #### Example of pairs from CD-PCB, the ground truth changes and *ChangeChip* results according to the parameters described in the Results section in the paper. 55 | #### The red circles are for easy identification by the reader. 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /REFERENCE_IMAGE.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/REFERENCE_IMAGE.JPG -------------------------------------------------------------------------------- /cd_pcb_results_a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/cd_pcb_results_a.jpg -------------------------------------------------------------------------------- /cd_pcb_results_b.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/cd_pcb_results_b.jpg -------------------------------------------------------------------------------- /conda_changechip.yml: -------------------------------------------------------------------------------- 1 | name: pca_kmeans_change_detection 2 | channels: 3 | - defaults 4 | - conda-forge 5 | dependencies: 6 | - _libgcc_mutex=0.1=main 7 | - ca-certificates=2020.1.1=0 8 | - certifi=2020.4.5.1=py36_0 9 | - ld_impl_linux-64=2.33.1=h53a641e_7 10 | - libffi=3.2.1=hd88cf55_4 11 | - libgcc-ng=9.1.0=hdf63c60_0 12 | - libstdcxx-ng=9.1.0=hdf63c60_0 13 | - ncurses=5.9=10 14 | - openssl=1.0.2u=h7b6447c_0 15 | - pip=20.0.2=py36_1 16 | - python=3.6.0=2 17 | - readline=6.2=0 18 | - sqlite=3.13.0=1 19 | - tk=8.5.19=2 20 | - wheel=0.34.2=py36_0 21 | - xz=5.2.4=h14c3975_4 22 | - zlib=1.2.11=h7b6447c_3 23 | - pip: 24 | - absl-py==0.9.0 25 | - astor==0.8.1 26 | - cachetools==4.1.0 27 | - chardet==3.0.4 28 | - cycler==0.10.0 29 | - cython==0.29.17 30 | - decorator==4.4.2 31 | - gast==0.2.2 32 | - google-auth==1.13.1 33 | - google-auth-oauthlib==0.4.1 34 | - google-pasta==0.2.0 35 | - grpcio==1.28.1 36 | - h5py==2.10.0 37 | - hdbscan==0.8.26 38 | - idna==2.9 39 | - image-slicer==0.3.0 40 | - imageio==2.8.0 41 | - joblib==0.14.1 42 | - keras==2.2.4 43 | - keras-applications==1.0.8 44 | - keras-preprocessing==1.1.0 45 | - kiwisolver==1.2.0 46 | - lap==0.4.0 47 | - markdown==3.2.1 48 | - matplotlib==3.2.1 49 | - medpy==0.4.0 50 | - networkx==2.4 51 | - nibabel==3.1.0 52 | - numpy==1.18.2 53 | - oauthlib==3.1.0 54 | - opencv-contrib-python==3.4.2.16 55 | - opencv-python==3.4.2.16 56 | - opt-einsum==3.2.0 57 | - packaging==20.3 58 | - pandas==0.25.3 59 | - pillow==7.1.1 60 | - protobuf==3.11.3 61 | - pyasn1==0.4.8 62 | - pyasn1-modules==0.2.8 63 | - pydicom==1.4.2 64 | - pyparsing==2.4.7 65 | - pyqt5-sip==12.7.2 66 | - python-dateutil==2.8.1 67 | - pytz==2019.3 68 | - pywavelets==1.1.1 69 | - pyyaml==5.3.1 70 | - requests==2.23.0 71 | - requests-oauthlib==1.3.0 72 | - rsa==4.0 73 | - scikit-image==0.16.2 74 | - scikit-learn==0.22.2.post1 75 | - scipy==1.1.0 76 | - seaborn==0.10.1 77 | - setuptools==39.1.0 78 | - simpleitk==1.2.4 79 | - six==1.14.0 80 | - tensorboard==1.9.0 81 | - tensorflow==1.9.0 82 | - tensorflow-estimator==2.0.1 83 | - termcolor==1.1.0 84 | - urllib3==1.25.8 85 | - werkzeug==1.0.1 86 | - wrapt==1.12.1 87 | prefix: /home/yonif/.conda/envs/pca_kmeans_change_detection 88 | 89 | -------------------------------------------------------------------------------- /crop.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | from matplotlib import pyplot as plt 4 | import global_variables 5 | from keras import backend as K 6 | import tensorflow as tf 7 | from DEXTR.helpers import helpers as helpers 8 | from DEXTR.networks.dextr import DEXTR 9 | import cv2 10 | 11 | def crop_images(image_1, image_2): 12 | scale = 0.2 13 | image_1_small = cv2.resize(image_1, (0,0), fx=scale, fy=scale , interpolation=cv2.INTER_AREA) 14 | image_2_small = cv2.resize(image_2, (0,0), fx=scale, fy=scale , interpolation=cv2.INTER_AREA) 15 | modelName = 'dextr_pascal-sbd' 16 | pad = 50 17 | thres = 0.8 18 | 19 | # Handle input and output args 20 | sess = tf.Session() 21 | K.set_session(sess) 22 | 23 | with sess.as_default(): 24 | net = DEXTR(nb_classes=1, resnet_layers=101, input_shape=(512, 512), weights=modelName, 25 | num_input_channels=4, classifier='psp', sigmoid=True) 26 | 27 | plt.figure() 28 | plt.ion() 29 | plt.axis('off') 30 | plt.imshow(image_1_small, cmap='gray') 31 | plt.title('Click the four extreme points of the objects\nHit enter when done (do not close the window)') 32 | plt.show() 33 | #################----image1----############################################################################## 34 | results_1 = [] 35 | extreme_points_ori = np.array(plt.ginput(4, timeout=0)).astype(np.int) 36 | 37 | # Crop image to the bounding box from the extreme points and resize 38 | bbox = helpers.get_bbox(image_1_small, points=extreme_points_ori, pad=pad, zero_pad=True) 39 | crop_image = helpers.crop_from_bbox(image_1_small, bbox, zero_pad=True) 40 | resize_image = helpers.fixed_resize(crop_image, (512, 512)).astype(np.float32) 41 | 42 | # Generate extreme point heat map normalized to image values 43 | extreme_points = extreme_points_ori - [np.min(extreme_points_ori[:, 0]), np.min(extreme_points_ori[:, 1])] + [ 44 | pad, 45 | pad] 46 | extreme_points = (512 * extreme_points * [1 / crop_image.shape[1], 1 / crop_image.shape[0]]).astype(np.int) 47 | extreme_heatmap = helpers.make_gt(resize_image, extreme_points, sigma=10) 48 | extreme_heatmap = helpers.cstm_normalize(extreme_heatmap, 255) 49 | 50 | # Concatenate inputs and convert to tensor 51 | input_dextr = np.concatenate((resize_image, extreme_heatmap[:, :, np.newaxis]), axis=2) 52 | 53 | # Run a forward pass 54 | pred = net.model.predict(input_dextr[np.newaxis, ...])[0, :, :, 0] 55 | result_1 = helpers.crop2fullmask(pred, bbox, im_size=image_1_small.shape[:2], zero_pad=True, relax=pad) > thres 56 | 57 | results_1.append(result_1) 58 | 59 | # Plot the results 60 | plt.imshow(helpers.overlay_masks(image_1_small / 255, results_1)) 61 | plt.plot(extreme_points_ori[:, 0], extreme_points_ori[:, 1], 'gx') 62 | result_1 = np.asarray(result_1, dtype="uint8") 63 | result_1 = cv2.resize(result_1,(image_1.shape[1],image_1.shape[0]) ,interpolation=cv2.INTER_AREA) 64 | for i in range(image_1.shape[:2][0]): 65 | for j in range(image_1.shape[:2][1]): 66 | if result_1[i][j] == False: 67 | image_1[i][j] = 0 68 | cv2.imwrite(global_variables.output_dir + '/cropped_1.jpg', image_1) 69 | #################----image2----############################################################################## 70 | 71 | plt.figure() 72 | plt.ion() 73 | plt.axis('off') 74 | plt.imshow(image_2_small, cmap='gray') 75 | plt.title('Click the four extreme points of the objects\nHit enter when done (do not close the window)') 76 | plt.show() 77 | 78 | results_2 = [] 79 | extreme_points_ori = np.array(plt.ginput(4, timeout=0)).astype(np.int) 80 | 81 | # Crop image to the bounding box from the extreme points and resize 82 | bbox = helpers.get_bbox(image_2_small, points=extreme_points_ori, pad=pad, zero_pad=True) 83 | crop_image = helpers.crop_from_bbox(image_2_small, bbox, zero_pad=True) 84 | resize_image = helpers.fixed_resize(crop_image, (512, 512)).astype(np.float32) 85 | 86 | # Generate extreme point heat map normalized to image values 87 | extreme_points = extreme_points_ori - [np.min(extreme_points_ori[:, 0]), np.min(extreme_points_ori[:, 1])] + [ 88 | pad, 89 | pad] 90 | extreme_points = (512 * extreme_points * [1 / crop_image.shape[1], 1 / crop_image.shape[0]]).astype(np.int) 91 | extreme_heatmap = helpers.make_gt(resize_image, extreme_points, sigma=10) 92 | extreme_heatmap = helpers.cstm_normalize(extreme_heatmap, 255) 93 | 94 | # Concatenate inputs and convert to tensor 95 | input_dextr = np.concatenate((resize_image, extreme_heatmap[:, :, np.newaxis]), axis=2) 96 | 97 | # Run a forward pass 98 | pred = net.model.predict(input_dextr[np.newaxis, ...])[0, :, :, 0] 99 | result_2 = helpers.crop2fullmask(pred, bbox, im_size=image_2_small.shape[:2], zero_pad=True, relax=pad) > thres 100 | results_2.append(result_2) 101 | 102 | # Plot the results 103 | plt.imshow(helpers.overlay_masks(image_2_small / 255, results_2)) 104 | plt.plot(extreme_points_ori[:, 0], extreme_points_ori[:, 1], 'gx') 105 | result_2 = np.asarray(result_2, dtype="uint8") 106 | result_2 = cv2.resize(result_2, (image_2.shape[1],image_2.shape[0]), interpolation=cv2.INTER_AREA) 107 | for i in range(image_2.shape[:2][0]): 108 | for j in range(image_2.shape[:2][1]): 109 | if result_2[i][j] == False: 110 | image_2[i][j] = 0 111 | if (global_variables.save_extra_stuff): 112 | cv2.imwrite(global_variables.output_dir + '/cropped_2.jpg', image_2) 113 | return image_1, image_2, result_1, result_2 114 | 115 | 116 | -------------------------------------------------------------------------------- /evaluation.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import cv2 3 | import numpy as np 4 | from numpy import loadtxt 5 | from pathlib import Path 6 | 7 | def main(results_dir): 8 | clustering_map = loadtxt(results_dir+'/clustering_data.csv', delimiter=',') 9 | accepted_classes = loadtxt(results_dir + '/accepted_classes.csv', delimiter=',') 10 | gt = cv2.imread(results_dir + "/../../GT.JPG") 11 | gt = cv2.resize(gt, (clustering_map.shape[1],clustering_map.shape[0] ), interpolation=cv2.INTER_AREA) 12 | recall = 0 13 | precision = 0 14 | gt_size = 0 15 | selected_size = 0 16 | for i in range(gt.shape[0]): 17 | for j in range(gt.shape[1]): 18 | if np.all(gt[i,j] == [255,255,255]): 19 | gt_size += 1 20 | if clustering_map[i,j] in accepted_classes: 21 | recall += 1 22 | if clustering_map[i,j] in accepted_classes: 23 | selected_size+=1 24 | if np.all(gt[i,j] == [255,255,255]): 25 | precision += 1 26 | 27 | recall = recall / gt_size 28 | precision= precision / selected_size 29 | print("Recall", round(recall,4)) 30 | print("Precision", round(precision,4)) 31 | return recall, precision 32 | 33 | if __name__ == '__main__': 34 | parser = argparse.ArgumentParser(description='Parameters for Running') 35 | parser.add_argument('-results_dir', 36 | dest='results_dir', 37 | help='destination of the results to evaluate') 38 | args = parser.parse_args() 39 | main(args.results_dir) -------------------------------------------------------------------------------- /global_variables.py: -------------------------------------------------------------------------------- 1 | import os 2 | def init(dir, save_extra): 3 | global output_dir 4 | output_dir = dir 5 | if not os.path.exists(output_dir): 6 | os.makedirs(output_dir) 7 | global save_extra_stuff 8 | save_extra_stuff = save_extra 9 | 10 | def set_size(size_00, size_11): 11 | global size_0 12 | size_0 = size_00 13 | global size_1 14 | size_1 = size_11 -------------------------------------------------------------------------------- /light_differences_elimination.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import cv2 4 | import global_variables 5 | 6 | def light_diff_elimination_NAIVE(image1, image2_registered): 7 | img_hsv1 = cv2.cvtColor(image1, cv2.COLOR_RGB2HSV) 8 | img_cpy1 = np.copy(img_hsv1) 9 | img_hsv2 = cv2.cvtColor(image2_registered, cv2.COLOR_RGB2HSV) 10 | img_cpy2 = np.copy(img_hsv2) 11 | for i in range(img_hsv1.shape[0]): 12 | for j in range(img_hsv1.shape[1]): 13 | if img_cpy1[i, j, 1] >= 50 or img_cpy1[i, j, 2] <= 205: 14 | img_cpy1[i, j, 1] = (img_hsv1[i, j, 1] + img_hsv2[i, j, 1]) 15 | for i in range(img_hsv1.shape[0]): 16 | for j in range(img_hsv1.shape[1]): 17 | if img_cpy2[i, j, 1] >= 50 or img_cpy2[i, j, 2] <= 205: 18 | img_cpy2[i, j, 1] = (img_hsv1[i, j, 1] + img_hsv2[i, j, 1]) 19 | # image1[:, :, 1] = 120 20 | # image2_registered[:, :, 1] = 120 vc 21 | image1 = cv2.cvtColor(img_cpy1, cv2.COLOR_HSV2RGB) 22 | if (global_variables.save_extra_stuff): 23 | cv2.imwrite(global_variables.output_dir + '/img1_light_correction.jpg', image1) 24 | image2_registered = cv2.cvtColor(img_cpy2, cv2.COLOR_HSV2RGB) 25 | if (global_variables.save_extra_stuff): 26 | cv2.imwrite(global_variables.output_dir + '/img2_light_correction.jpg', 27 | image2_registered) 28 | return image1, image2_registered 29 | 30 | #rgb - are the images in rgb colors of just gray? 31 | def light_diff_elimination(image1, image2_registered): 32 | import imageio 33 | from ExactHistogramMatching.histogram_matching import ExactHistogramMatcher 34 | reference_histogram = ExactHistogramMatcher.get_histogram(image1) 35 | new_target_img = ExactHistogramMatcher.match_image_to_histogram(image2_registered, reference_histogram) 36 | cv2.imwrite(global_variables.output_dir + '/image2_registered_histogram_matched.jpg', new_target_img) 37 | new_target_img = np.asarray(new_target_img, dtype=np.uint8) 38 | return new_target_img -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append('/home/yonif/.conda/envs/pca_kmeans_change_detection/lib/python3.6/site-packages') 3 | import numpy as np 4 | np.set_printoptions(threshold=sys.maxsize) 5 | import cv2 6 | import time 7 | from PCA_Kmeans import compute_change_map, find_group_of_accepted_classes_DBSCAN, draw_combination_on_transparent_input_image 8 | import global_variables 9 | import os 10 | import argparse 11 | 12 | def main(output_dir,input_path,reference_path,n,window_size, pca_dim_gray, pca_dim_rgb, 13 | cut, lighting_fix, use_homography, resize_factor, save_extra_stuff): 14 | ''' 15 | 16 | :param output_dir: destination directory for the output 17 | :param input_path: path to the input image 18 | :param reference_path: path to the reference image 19 | :param n: number of classes for clustering the diff descriptors 20 | :param window_size: window size for the diff descriptors 21 | :param pca_dim_gray: pca target dimension for the gray diff descriptor 22 | :param pca_dim_rgb: pca target dimension for the rgb diff descriptor 23 | :param cut: true to enable DXTR cropping 24 | :param lighting_fix: true to enable histogram matching 25 | :param use_homography: true to enable SIFT homography (always recommended) 26 | :param resize_factor: scale the input images, usually with factor smaller than 1 for faster results 27 | :param save_extra_stuff: save diagnostics and extra results, usually for debugging 28 | :return: the results are saved in output_dir 29 | ''' 30 | global_variables.init(output_dir, save_extra_stuff) #setting global variables 31 | 32 | if use_homography: 33 | from registration import homography 34 | if lighting_fix: 35 | from light_differences_elimination import light_diff_elimination 36 | 37 | 38 | #for time estimations 39 | start_time = time.time() 40 | 41 | #read the inputs 42 | image_1 = cv2.imread(input_path, 1) 43 | image_2 = cv2.imread(reference_path, 1) 44 | 45 | #we need the images to be the same size. resize_factor is for increasing or decreasing further the images 46 | new_shape = (int(resize_factor*0.5*(image_1.shape[1]+image_2.shape[1])), int(resize_factor*0.5*(image_1.shape[0]+image_2.shape[0]))) 47 | image_1 = cv2.resize(image_1,new_shape, interpolation=cv2.INTER_AREA) 48 | image_2 = cv2.resize(image_2, new_shape, interpolation=cv2.INTER_AREA) 49 | global_variables.set_size(new_shape[0],new_shape[1]) 50 | if cut: 51 | import crop 52 | image_1, image_2, result_1, result_2 = crop.crop_images(image_1, image_2) 53 | mask = np.zeros((result_2.shape[0], result_2.shape[1], 3), dtype=np.uint8) 54 | for i in range(image_2.shape[:2][0]): 55 | for j in range(image_2.shape[:2][1]): 56 | if result_2[i][j] == True: 57 | mask[i][j] = [255, 255, 255] 58 | if use_homography: 59 | image2_registered, mask_registered, blank_pixels = homography(cut, image_1, image_2, mask) 60 | else: 61 | image2_registered = image_2 62 | min_width = min(image_1.shape[:2][0], image_2.shape[:2][0]) 63 | min_height = min(image_1.shape[:2][1], image_2.shape[:2][1]) 64 | for i in range(min_width): 65 | for j in range(min_height): 66 | if mask_registered[i][j][0] == 0 or result_1[i][j] == False: 67 | image2_registered[i][j] = 0 68 | image_1[i][j] = 0 69 | cv2.imwrite(global_variables.output_dir + '/blanked_1.jpg', image_1) 70 | cv2.imwrite(global_variables.output_dir + '/blanked_2.jpg', image2_registered) 71 | else: 72 | if use_homography: 73 | image2_registered, mask_registered, blank_pixels = homography(cut, image_1, image_2, None) 74 | else: 75 | image2_registered = image_2 76 | 77 | if use_homography: 78 | image_1[blank_pixels] = [0,0,0] 79 | image2_registered[blank_pixels] = [0, 0, 0] 80 | 81 | if (global_variables.save_extra_stuff): 82 | cv2.imwrite(global_variables.output_dir+ '/resized_blanked_1.jpg', image_1) 83 | 84 | if (lighting_fix): 85 | #Using the histogram matching, only image2_registered is changed 86 | image2_registered = light_diff_elimination(image_1, image2_registered) 87 | 88 | print("--- Preprocessing time - %s seconds ---" % (time.time() - start_time)) 89 | 90 | 91 | start_time = time.time() 92 | clustering_map, mse_array, size_array = compute_change_map(image_1, image2_registered, window_size=window_size, 93 | clusters=n, pca_dim_gray= pca_dim_gray, pca_dim_rgb=pca_dim_rgb) 94 | 95 | clustering = [[] for _ in range(n)] 96 | for i in range(clustering_map.shape[0]): 97 | for j in range(clustering_map.shape[1]): 98 | clustering[int(clustering_map[i,j])].append([i,j]) 99 | 100 | input_image = cv2.imread(input_path) 101 | input_image = cv2.resize(input_image,new_shape, interpolation=cv2.INTER_AREA) 102 | b_channel, g_channel, r_channel = cv2.split(input_image) 103 | alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255 104 | alpha_channel[:, :] = 50 105 | groups = find_group_of_accepted_classes_DBSCAN(mse_array) 106 | for group in groups: 107 | transparent_input_image = cv2.merge((b_channel, g_channel, r_channel, alpha_channel)) 108 | result = draw_combination_on_transparent_input_image(mse_array, clustering, group, transparent_input_image) 109 | cv2.imwrite(global_variables.output_dir + '/ACCEPTED_CLASSES'+'.png', result) 110 | 111 | print("--- PCA-Kmeans + Post-processing time - %s seconds ---" % (time.time() - start_time)) 112 | 113 | if __name__ == '__main__': 114 | 115 | parser = argparse.ArgumentParser(description='Parameters for Running') 116 | parser.add_argument('-output_dir', 117 | dest='output_dir', 118 | help='destination directory for the output') 119 | parser.add_argument('-input_path', 120 | dest='input_path', 121 | help='path to the input image') 122 | parser.add_argument('-reference_path', 123 | dest='reference_path', 124 | help='path to the reference image') 125 | parser.add_argument('-n', 126 | dest='n', 127 | help='number of classes for clustering the diff descriptors') 128 | parser.add_argument('-window_size', 129 | dest='window_size', 130 | help='window size for the diff descriptors') 131 | parser.add_argument('-pca_dim_gray', 132 | dest='pca_dim_gray', 133 | help='pca target dimension for the gray diff descriptor') 134 | parser.add_argument('-pca_dim_rgb', 135 | dest='pca_dim_rgb', 136 | help='pca target dimension for the rgb diff descriptor') 137 | parser.add_argument('-pca_target_dim', 138 | dest='pca_target_dim', 139 | help='pca target dimension for final combination of the descriptors') 140 | parser.add_argument('-cut', 141 | dest='cut', 142 | help='true to enable DXTR cropping', 143 | default=False, action='store_true') 144 | parser.add_argument('-lighting_fix', 145 | dest='lighting_fix', 146 | help='true to enable histogram matching', 147 | default=False, action='store_true') 148 | parser.add_argument('-use_homography', 149 | dest='use_homography', 150 | help='true to enable SIFT homography (always recommended)', 151 | default=False, action='store_true') 152 | parser.add_argument('-resize_factor', 153 | dest='resize_factor', 154 | help='scale the input images, usually with factor smaller than 1 for faster results') 155 | parser.add_argument('-save_extra_stuff', 156 | dest='save_extra_stuff', 157 | help='save diagnostics and extra results, usually for debugging', 158 | default=False, action='store_true') 159 | args = parser.parse_args() 160 | main(args.output_dir, args.input_path, args.reference_path, int(args.n), int(args.window_size), 161 | int(args.pca_dim_gray), int(args.pca_dim_rgb), bool(args.cut), bool(args.lighting_fix), bool(args.use_homography), 162 | float(args.resize_factor), bool(args.save_extra_stuff)) -------------------------------------------------------------------------------- /registration.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import cv2 4 | import global_variables 5 | 6 | def homography(cut, img1, img2, mask_img): 7 | # Initiate SIFT detector 8 | sift = cv2.xfeatures2d.SIFT_create() 9 | # find the keypoints and descriptors with SIFT 10 | kp1, des1 = sift.detectAndCompute(img1, None) 11 | kp2, des2 = sift.detectAndCompute(img2, None) 12 | # BFMatcher with default params 13 | bf = cv2.BFMatcher() 14 | matches = bf.knnMatch(des2, des1, k=2) 15 | 16 | # Apply ratio test 17 | good_draw = [] 18 | good_without_list = [] 19 | for m, n in matches: 20 | if m.distance < 0.8 * n.distance: #0.8 = a value suggested by David G. Lowe. 21 | good_draw.append([m]) 22 | good_without_list.append(m) 23 | 24 | # cv.drawMatchesKnn expects list of lists as matches. 25 | img3 = cv2.drawMatchesKnn(img2, kp2, img1, kp1, good_draw, None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS) 26 | if (global_variables.save_extra_stuff): 27 | cv2.imwrite(global_variables.output_dir + '/matching.png', img3) 28 | # Extract location of good matches 29 | points1 = np.zeros((len(good_without_list), 2), dtype=np.float32) 30 | points2 = np.zeros((len(good_without_list), 2), dtype=np.float32) 31 | 32 | for i, match in enumerate(good_without_list): 33 | points1[i, :] = kp2[match.queryIdx].pt 34 | points2[i, :] = kp1[match.trainIdx].pt 35 | 36 | # Find homography 37 | h, mask = cv2.findHomography(points1, points2, cv2.RANSAC) 38 | 39 | # Use homography 40 | height, width = img2.shape[:2] 41 | white_img2 = 255- np.zeros(shape=img2.shape, dtype=np.uint8) 42 | whiteReg = cv2.warpPerspective(white_img2, h, (width, height)) 43 | blank_pixels_mask = np.any(whiteReg != [255, 255, 255], axis=-1) 44 | im2Reg = cv2.warpPerspective(img2, h, (width, height)) 45 | if (global_variables.save_extra_stuff): 46 | cv2.imwrite(global_variables.output_dir + '/aligned.jpg', im2Reg) 47 | if cut: 48 | mask_registered = cv2.warpPerspective(mask_img, h, (width, height)) 49 | return im2Reg, mask_registered, blank_pixels_mask 50 | else: 51 | return im2Reg, None, blank_pixels_mask 52 | 53 | -------------------------------------------------------------------------------- /run_example.sh: -------------------------------------------------------------------------------- 1 | python main.py -output_dir example_output -input_path INPUT_IMAGE.JPG -reference_path REFERENCE_IMAGE.JPG -n 16 -window_size 5 -pca_dim_gray 3 -pca_dim_rgb 9 -resize_factor 0.2 -lighting_fix -use_homography -save_extra_stuff 2 | -------------------------------------------------------------------------------- /workflow.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Scientific-Computing-Lab/ChangeChip/1c3281fabc009fc46a4a11c4c49441992fe22352/workflow.PNG --------------------------------------------------------------------------------