├── .gitignore ├── COPYING ├── README.md ├── blue.net ├── blue ├── lconsts.py ├── preprocess.py ├── recognise.py ├── segment.py └── train.py ├── cap ├── __init__.py ├── consts.py ├── cvext.py ├── extras.py ├── general.py ├── preprocess.py ├── recognise.py └── segment.py ├── captchure.komodoproject ├── demo.bat ├── deprecated ├── clear.py ├── deprecated.py ├── filter_segments.py ├── recognise_naive.py ├── recognise_seg_naive.py ├── test.py ├── test_red.py └── threshold.py ├── green.net ├── green ├── lconsts.py ├── preprocess.py ├── recognise.py ├── segment.py └── train.py ├── main.py ├── red.net ├── red ├── lconsts.py ├── preprocess.py ├── recognise.py ├── segment.py └── train.py ├── yellow ├── create_valid_data.py ├── lconsts.py ├── preprocess.py ├── recognise.py ├── segment.py └── train.py ├── yellow_19_183.net └── yellow_20_191.net /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | RUSSIAN 2 | 3 | Это Captchure, программа для распознавания CAPTCHA, применяемых наиболее популярными операторами сотовой связи (на 2011 год). Код написан на Python с применением библиотек OpenCV v2.1 и FANN v2.1, разрабатывался в Komodo Edit и распространяется на условиях GNU GPL v3 или позднее, как и файлы нейросетей. 4 | 5 | Сайт автора программы - http://lcme.ucoz.ru/ 6 | Ветка программы на форуме - http://lcme.ucoz.ru/forum/38 7 | 8 | ENGLISH 9 | 10 | This is Captchure, a program for recognizing CAPTCHAs used by the most popular Russian mobile network operators, as of 2011. The code is written in Python, uses OpenCV v2.1 and FANN v2.1, was developed in Komodo Edit and is distributed under the terms of GNU GPL v3 or later. The neural networks' files are distributed under the terms of GNU GPL v3 as well. 11 | 12 | Author's web site - http://lcme.ucoz.ru/ 13 | Program's forum branch - http://lcme.ucoz.ru/forum/38 -------------------------------------------------------------------------------- /blue/lconsts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | nSegs = 6 21 | 22 | segW = 16 23 | segH = 20 24 | segSize = (segW, segH) 25 | 26 | charset = "0123456789" 27 | 28 | num_input = segW * segH 29 | num_output = len(charset) 30 | 31 | train_file = "ann.train" 32 | ann_file = "ann.net" -------------------------------------------------------------------------------- /blue/preprocess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | 22 | def doSplit(image): 23 | b = cv.CreateImage(cv.GetSize(image), image.depth, 1) 24 | g = cv.CreateImage(cv.GetSize(image), image.depth, 1) 25 | r = cv.CreateImage(cv.GetSize(image), image.depth, 1) 26 | cv.Split(image, b, g, r, None) 27 | return b, g, r 28 | 29 | def createMask(image, thresh): 30 | b, g, r = doSplit(image) 31 | cv.Threshold(b, b, thresh, 255, cv.CV_THRESH_BINARY) 32 | cv.Threshold(g, g, thresh, 255, cv.CV_THRESH_BINARY) 33 | cv.Threshold(r, r, thresh, 255, cv.CV_THRESH_BINARY) 34 | cv.And(b, g, b, None) 35 | cv.And(b, r, b, None) 36 | return b 37 | 38 | def cutLetters(image, thresh, log): 39 | mask = createMask(image, thresh) 40 | log.log(mask) 41 | h = cv.CreateImage(cv.GetSize(image), image.depth, 1) 42 | cv.CvtColor(image, image, cv.CV_BGR2HSV) 43 | cv.Split(image, h, None, None, None) 44 | log.log(h) 45 | cv.Set(h, cv.ScalarAll(255), mask) 46 | return h 47 | 48 | 49 | def preprocess(image, addr, extras): 50 | log = cap.logger(extras, image) 51 | image = cutLetters(image, 116, log) 52 | log.log(image) 53 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_PREPROCESS) 54 | return image -------------------------------------------------------------------------------- /blue/recognise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cap 21 | from lconsts import ann_file, charset, segSize 22 | 23 | ann = cap.loadAnn(ann_file) 24 | 25 | def recognise(segments, addr, extras): 26 | return cap.defaultRecognise(segments, addr, extras, ann, segSize, charset, cap.resizeFit) -------------------------------------------------------------------------------- /blue/segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from operator import itemgetter 22 | from lconsts import nSegs 23 | 24 | from math import sqrt 25 | def doRotate(image, alpha, fillval=0, resize=True, interpolation=cv.CV_INTER_CUBIC): 26 | matrix = cv.CreateMat(2, 3, cv.CV_32FC1) 27 | w, h = cv.GetSize(image) 28 | center = ((w - 1) / 2.0, (h - 1) / 2.0) 29 | cv.GetRotationMatrix2D(center, alpha, 1.0, matrix) 30 | if resize: 31 | d = sqrt(w*w + h*h) 32 | d2 = d / 2.0 33 | matrix[0, 2] += d2 - center[0] 34 | matrix[1, 2] += d2 - center[1] 35 | d = int(d) 36 | size = (d, d) 37 | else: 38 | size = cv.GetSize(image) 39 | result = cv.CreateImage(size, image.depth, image.nChannels) 40 | cv.WarpAffine(image, result, matrix, interpolation + cv.CV_WARP_FILL_OUTLIERS, fillval) 41 | return result 42 | 43 | def findLineSlope(pt1, pt2): 44 | dx = pt2[0] - pt1[0] 45 | dy = pt2[1] - pt1[1] 46 | result = cv.FastArctan(dy, dx) 47 | if result >= 180.0: 48 | result -= 180.0 49 | result = 180.0 - result 50 | if result >= 90.0: 51 | result -= 180.0 52 | return result 53 | 54 | def deRotate(seg): 55 | box_vtx = cap.minAreaRectImage(seg) 56 | pts = sorted(box_vtx, key=lambda vtx: vtx[1], reverse=True)[:2] 57 | slope = findLineSlope(*pts) 58 | if slope < 20.0: 59 | seg = doRotate(seg, -slope, fillval=0, resize=True) 60 | seg = cap.getSubImage(seg, cap.findNonBlackRect(seg, thresh=1)) 61 | return seg 62 | 63 | def segment(image, addr, extras): 64 | clone = cv.CloneImage(image) 65 | log = cap.logger(extras, image) 66 | components = cap.findCCs(image, erasecol=255, doContinue=lambda col: col == 255, doSkip=lambda comp: comp[0] <= 20) 67 | #components = cap.spltCCs(components, cap.partsFromSegW(components, 20), projRadius=5, thresh=1) 68 | log.log(cap.drawComponents(clone, components)) 69 | while len(components) > nSegs: 70 | smallest = cap.argmin(components, itemgetter(0)) 71 | del(components[smallest]) 72 | assert(len(components) == nSegs) 73 | log.log(cap.drawComponents(clone, components)) 74 | segments = map(lambda comp: comp[3], components) 75 | log.log(cap.joinImagesH(segments)) 76 | segments = map(deRotate, segments) 77 | log.log(cap.joinImagesH(segments)) 78 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_SEGMENT) 79 | return segments -------------------------------------------------------------------------------- /blue/train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys 21 | from pyfann import libfann 22 | from lconsts import segW, segH, num_input, num_output, charset, train_file, ann_file 23 | 24 | sys.path.append("..") 25 | 26 | from cap import resizeFit as adjustSize, segment_dir 27 | 28 | segments = os.listdir(segment_dir) 29 | 30 | f = open(train_file, "w") 31 | f.write("%d %d %d\n" % (len(segments), num_input, num_output)) 32 | 33 | 34 | for name in segments: 35 | image = cv.LoadImage(os.path.join(segment_dir, name), cv.CV_LOAD_IMAGE_GRAYSCALE) 36 | image = adjustSize(image, (segW, segH)) 37 | for y in range(image.height): 38 | for x in range(image.width): 39 | n = image[y, x] / 159.375 - 0.8 40 | f.write("%f " % n) 41 | f.write("\n") 42 | c = os.path.splitext(name)[0][0] 43 | n = charset.index(c) 44 | f.write("-1 " * n + "1" + " -1" * (num_output - n - 1) + "\n") 45 | 46 | f.close() 47 | 48 | print "Samples: %d" % len(segments) 49 | print "Input: %d" % num_input 50 | print "Output: %d" % num_output 51 | 52 | connection_rate = 1.0 53 | learning_rate = 0.3 54 | num_neurons_hidden = num_input / 3 55 | 56 | desired_error = 0.00001 57 | max_iterations = 10000 58 | iterations_between_reports = 20 59 | 60 | ann = libfann.neural_net() 61 | ann.create_sparse_array(connection_rate, (num_input, num_neurons_hidden, num_output)) 62 | ann.set_learning_rate(learning_rate) 63 | ann.set_activation_function_hidden(libfann.SIGMOID_SYMMETRIC_STEPWISE) 64 | ann.set_activation_function_output(libfann.SIGMOID_SYMMETRIC_STEPWISE) 65 | 66 | ann.train_on_file(train_file, max_iterations, iterations_between_reports, desired_error) 67 | 68 | ann.save(ann_file) -------------------------------------------------------------------------------- /cap/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | from general import * 21 | from consts import * 22 | from cvext import * 23 | from preprocess import * 24 | from segment import * 25 | from recognise import * 26 | from extras import * -------------------------------------------------------------------------------- /cap/consts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | preprocess_dir = "preprocessed" 21 | segment_dir = "segmented" 22 | recognise_dir = "recognised" 23 | success_dir = "success" 24 | mismatch_dir = "mismatch" 25 | extras_dir = "extras" 26 | 27 | defext = ".png" 28 | 29 | CAP_STAGE_PRE = 0 30 | CAP_STAGE_PREPROCESS = 0 31 | CAP_STAGE_SEG = 1 32 | CAP_STAGE_SEGMENT = 1 33 | CAP_STAGE_REC = 2 34 | CAP_STAGE_RECOGNISE = 2 35 | 36 | CAP_EXTRAS_OFF = 0 37 | CAP_EXTRAS_SHOW = 1 38 | CAP_EXTRAS_SAVE = 2 -------------------------------------------------------------------------------- /cap/cvext.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv 21 | from math import ceil, sin, cos, radians as rad 22 | 23 | def getSubImage(image, rect): 24 | region = cv.GetSubRect(image, rect) 25 | image = cv.CreateImage(cv.GetSize(region), image.depth, image.nChannels) 26 | cv.Copy(region, image, None) 27 | return image 28 | 29 | def copyTo(src, dst, point, mask=None): 30 | if not (point[0] + src.width <= dst.width and point[1] + src.height <= dst.height): 31 | msg = "Source image is too large: %dx%d, maximum is %dx%d" % (src.width, src.height, \ 32 | dst.width - point[0], dst.height - point[1]) 33 | raise cv.error(msg) 34 | try: 35 | region = cv.GetSubRect(dst, (point[0], point[1], src.width, src.height)) 36 | except: 37 | print "cv.GetSubRect failure, arguments: " + str((point[0], point[1], src.width, src.height)) 38 | raise 39 | cv.Copy(src, region, mask) 40 | 41 | def doResize(image, factor, method=cv.CV_INTER_CUBIC): 42 | result = cv.CreateImage((int(image.width * factor), int(image.height * factor)), image.depth, image.nChannels) 43 | cv.Resize(image, result, method) 44 | return result 45 | 46 | def doRotate(image, alpha, fillval=0, resize=True, interpolation=cv.CV_INTER_CUBIC): 47 | matrix = cv.CreateMat(2, 3, cv.CV_32FC1) 48 | w, h = cv.GetSize(image) 49 | center = ((w - 1) / 2.0, (h - 1) / 2.0) 50 | cv.GetRotationMatrix2D(center, alpha, 1.0, matrix) 51 | if resize: 52 | angle = rad(abs(alpha)) 53 | nw = w * cos(angle) + h * sin(angle) 54 | nh = w * sin(angle) + h * cos(angle) 55 | ncenter = (nw / 2.0, nh / 2.0) 56 | matrix[0, 2] += ncenter[0] - center[0] 57 | matrix[1, 2] += ncenter[1] - center[1] 58 | size = (int(ceil(nw)), int(ceil(nh))) 59 | else: 60 | size = cv.GetSize(image) 61 | result = cv.CreateImage(size, image.depth, image.nChannels) 62 | cv.WarpAffine(image, result, matrix, interpolation + cv.CV_WARP_FILL_OUTLIERS, fillval) 63 | return result 64 | 65 | def roundXY(pt): 66 | return (cv.Round(pt[0]), cv.Round(pt[1])) 67 | 68 | def minAreaRectImage(image, returnPoints=True): 69 | points = [] 70 | for x in xrange(image.width): 71 | for y in xrange(image.height): 72 | if image[y, x] > 128: points.append((x, y)) 73 | box = cv.MinAreaRect2(points) 74 | if not returnPoints: 75 | return box 76 | box_vtx = map(roundXY, cv.BoxPoints(box)) 77 | return box_vtx 78 | -------------------------------------------------------------------------------- /cap/extras.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, types, cv, cvext 21 | from operator import itemgetter 22 | from consts import * 23 | 24 | def getFilename(addr): 25 | return os.path.splitext(os.path.basename(addr))[0] 26 | 27 | def addFakeChannels(image): 28 | if image.nChannels == 3: 29 | return image 30 | if image.nChannels != 1: 31 | raise ValueError("Input image must be 1- or 3-channel.") 32 | result = cv.CreateImage(cv.GetSize(image), image.depth, 3) 33 | cv.CvtColor(image, result, cv.CV_GRAY2BGR) 34 | return result 35 | 36 | def joinImagesV(images, bgcolor=128): 37 | totalHeight = sum([image.height for image in images]) 38 | maxWidth = max([image.width for image in images]) 39 | maxNChannels = max([image.nChannels for image in images]) 40 | if maxNChannels == 3: 41 | images = map(addFakeChannels, images) 42 | bgcolor = cv.ScalarAll(bgcolor) 43 | total = len(images) 44 | result = cv.CreateImage((maxWidth, totalHeight + total - 1), images[0].depth, images[0].nChannels) 45 | cv.Set(result, bgcolor) 46 | curH = 0 47 | for index in xrange(len(images)): 48 | image = images[index] 49 | off = (maxWidth - image.width) / 2 50 | cvext.copyTo(image, result, (off, curH), None) 51 | curH += image.height + 1 52 | return result 53 | 54 | def joinImagesH(images, bgcolor=128): 55 | totalWidth = sum([image.width for image in images]) 56 | maxHeight = max([image.height for image in images]) 57 | maxNChannels = max([image.nChannels for image in images]) 58 | if maxNChannels == 3: 59 | images = map(addFakeChannels, images) 60 | bgcolor = cv.ScalarAll(bgcolor) 61 | total = len(images) 62 | result = cv.CreateImage((totalWidth + total - 1, maxHeight), images[0].depth, images[0].nChannels) 63 | cv.Set(result, bgcolor) 64 | curW = 0 65 | for index in xrange(len(images)): 66 | image = images[index] 67 | off = (maxHeight - image.height) / 2 68 | cvext.copyTo(image, result, (curW, off), None) 69 | curW += image.width + 1 70 | return result 71 | 72 | def drawComponents(image, components, startcol=192, stepcol=8): 73 | result = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 3) 74 | cv.CvtColor(image, result, cv.CV_GRAY2BGR) 75 | if len(components) == 0: return result 76 | if type(components[0][2]) == types.TupleType: 77 | rects = map(itemgetter(2), components) 78 | else: 79 | rects = components 80 | for index, rect in enumerate(rects): 81 | pt1 = (rect[0], rect[1]) 82 | pt2 = (rect[0] + rect[2], rect[1] + rect[3]) 83 | cv.Rectangle(result, pt1, pt2, (0, 0, startcol + stepcol * index), 1) 84 | return result 85 | 86 | suffixes = {CAP_STAGE_PRE:"pre", CAP_STAGE_SEG:"seg", CAP_STAGE_REC:"rec"} 87 | titles = {CAP_STAGE_PRE:"Preprocessing", CAP_STAGE_SEG:"Segmentation", CAP_STAGE_REC:"Recognition"} 88 | 89 | def getSuffix(stage): 90 | try: suffix = suffixes[stage] 91 | except KeyError: raise ValueError("Incorrect stage parameter") 92 | return suffix 93 | 94 | def getTitle(stage): 95 | try: title = titles[stage] 96 | except KeyError: raise ValueError("Incorrect stage parameter") 97 | return title 98 | 99 | def processExtras(steps, addr, extras, stage): 100 | if extras == CAP_EXTRAS_OFF: 101 | return 102 | result = joinImagesV(steps) 103 | if extras == CAP_EXTRAS_SAVE: 104 | name = getFilename(addr) 105 | suf = getSuffix(stage) 106 | #newaddr = os.path.join(extras_dir, name + "_" + suf) 107 | #for index, image in enumerate(steps): 108 | # cv.SaveImage(newaddr + str(index) + defext, image) 109 | newaddr = os.path.join(extras_dir, name + "_" + suf + defext) 110 | cv.SaveImage(newaddr, result) 111 | elif extras == CAP_EXTRAS_SHOW: 112 | title = getTitle(stage) 113 | cv.NamedWindow(title + " steps", 0) 114 | cv.ShowImage(title + " steps", result) 115 | 116 | class logger: 117 | def __init__(self, extras, image=None, clone=True): 118 | self.steps = [] 119 | if extras == CAP_EXTRAS_OFF: 120 | self.log = self.dontLog 121 | else: 122 | self.log = self.doLog 123 | if image is not None: 124 | self.log(image, clone) 125 | def dontLog(self, image, clone=True): 126 | pass 127 | def doLog(self, image, clone=True): 128 | if clone: self.steps.append(cv.CloneImage(image)) 129 | else: self.steps.append(image) -------------------------------------------------------------------------------- /cap/general.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | from numpy import vectorize 21 | 22 | identity = lambda x: x 23 | def wrap(key): 24 | return identity if key is None else key 25 | 26 | def find(lst, val, key=None): 27 | key = wrap(key) 28 | for i in xrange(len(lst)): 29 | if key(lst[i]) == val: 30 | return i 31 | return None 32 | 33 | def index(lst, key=None): 34 | key = wrap(key) 35 | for i in xrange(len(lst)): 36 | if key(lst[i]): 37 | return i 38 | return None 39 | 40 | def argmin(lst, key=None): 41 | key = wrap(key) 42 | mi = 0 43 | m = key(lst[0]) 44 | for i in xrange(1, len(lst)): 45 | val = key(lst[i]) 46 | if val < m: 47 | m = val 48 | mi = i 49 | return mi 50 | 51 | def argmax(lst, key=None): 52 | key = wrap(key) 53 | mi = 0 54 | m = key(lst[0]) 55 | for i in xrange(1, len(lst)): 56 | val = key(lst[i]) 57 | if val > m: 58 | m = val 59 | mi = i 60 | return mi 61 | 62 | def amap(func, array): 63 | vfunc = vectorize(func) 64 | return vfunc(array) -------------------------------------------------------------------------------- /cap/preprocess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv 21 | from segment import shiftRect 22 | 23 | # IPL_BORDER_CONSTANT = 0 24 | # IPL_BORDER_REPLICATE = 1 25 | 26 | def repaintCCs(image, doRepaint=None, returnMask=False, resizeMask=True, doFillBackground=True, bgPoint=(0, 0), newcol=255, connectivity=4): 27 | if doRepaint is None: 28 | doRepaint = lambda comp, col: False 29 | resultMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) 30 | tempMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) 31 | visitMask = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) 32 | cv.Zero(resultMask) 33 | cv.Zero(tempMask) 34 | cv.Zero(visitMask) 35 | if doFillBackground: 36 | cv.FloodFill(image, bgPoint, 0, 0, 0, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), visitMask) 37 | for x in xrange(image.width): 38 | for y in xrange(image.height): 39 | if visitMask[y + 1, x + 1] == 255: 40 | continue 41 | comp = cv.FloodFill(image, (x, y), 0, 0, 0, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), tempMask) 42 | region = shiftRect(comp[2], 1, 1) 43 | cv.SetImageROI(tempMask, region) 44 | cv.SetImageROI(visitMask, region) 45 | cv.Or(tempMask, visitMask, visitMask) 46 | if doRepaint(comp, image[y, x]): 47 | cv.SetImageROI(resultMask, region) 48 | cv.Or(tempMask, resultMask, resultMask) 49 | cv.ResetImageROI(resultMask) 50 | cv.Zero(tempMask) 51 | cv.ResetImageROI(tempMask) 52 | cv.ResetImageROI(visitMask) 53 | if returnMask: 54 | if resizeMask: return cap.getSubImage(resultMask, (1, 1, image.width, image.height)) 55 | else: return resultMask 56 | else: 57 | cv.SetImageROI(resultMask, (1, 1, image.width, image.height)) 58 | cv.Set(image, newcol, resultMask) 59 | return image 60 | 61 | def smoothNoise1(image, bgcolor=255): 62 | temp = cv.CreateImage((image.width + 2, image.height + 2), image.depth, image.nChannels) 63 | result = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 64 | cv.CopyMakeBorder(image, temp, (1, 1), 0, bgcolor) 65 | for x in xrange(1, image.width + 1): 66 | for y in xrange(1, image.height + 1): 67 | if temp[y + 1, x] == temp[y - 1, x] and temp[y, x] != temp[y + 1, x]: 68 | result[y - 1, x - 1] = temp[y + 1, x] 69 | elif temp[y, x + 1] == temp[y, x - 1] and temp[y, x] != temp[y, x + 1]: 70 | result[y - 1, x - 1] = temp[y, x + 1] 71 | else: 72 | result[y - 1, x - 1] = temp[y, x] 73 | return result -------------------------------------------------------------------------------- /cap/recognise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv 21 | from pyfann import libfann 22 | from cvext import copyTo 23 | from general import argmax 24 | 25 | def loadAnn(ann_file): 26 | ann = libfann.neural_net() 27 | ann.create_from_file(ann_file) 28 | return ann 29 | 30 | def flattenImage(image): 31 | lst = [] 32 | for y in range(image.height): 33 | for x in range(image.width): 34 | n = image[y, x] / 127.5 - 1.0 35 | lst.append(n) 36 | return lst 37 | 38 | def resizeNaive(image, size): 39 | result = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1) 40 | cv.Resize(image, result, cv.CV_INTER_CUBIC) 41 | return result 42 | 43 | def resizeProp(image, (segW, segH)): 44 | result = cv.CreateImage((segW, segH), image.depth, image.nChannels) 45 | cv.Zero(result) 46 | if image.width <= segW and image.height <= segH: 47 | offW = (segW - image.width) / 2 48 | offH = (segH - image.height) / 2 49 | copyTo(image, result, (offW, offH), None) 50 | else: 51 | scaleW = float(segW) / float(image.width) 52 | newH = image.height * scaleW 53 | if newH <= segH: 54 | offH = (segH - newH) / 2.0 55 | rect = (0, int(offH), segW, int(newH)) 56 | else: 57 | scaleH = float(segH) / float(image.height) 58 | newW = image.width * scaleH 59 | offW = (segW - newW) / 2.0 60 | rect = (int(offW), 0, int(newW), segH) 61 | cv.SetImageROI(result, rect) 62 | cv.Resize(image, result, cv.CV_INTER_CUBIC) 63 | cv.ResetImageROI(result) 64 | return result 65 | 66 | def resizeFit(image, (segW, segH)): 67 | result = cv.CreateImage((segW, segH), image.depth, image.nChannels) 68 | cv.Zero(result) 69 | if image.width > segW: 70 | if image.height > segH: 71 | cv.Resize(image, result, cv.CV_INTER_CUBIC) 72 | else: 73 | temp = cv.CreateImage((segW, image.height), image.depth, image.nChannels) 74 | cv.Resize(image, temp, cv.CV_INTER_CUBIC) 75 | offH = (segH - image.height) / 2 76 | copyTo(temp, result, (0, offH), None) 77 | else: 78 | if image.height > segH: 79 | temp = cv.CreateImage((image.width, segH), image.depth, image.nChannels) 80 | cv.Resize(image, temp, cv.CV_INTER_CUBIC) 81 | offW = (segW - image.width) / 2 82 | copyTo(temp, result, (offW, 0), None) 83 | else: 84 | offW = (segW - image.width) / 2 85 | offH = (segH - image.height) / 2 86 | copyTo(image, result, (offW, offH), None) 87 | return result 88 | 89 | def recogniseChar(image, ann, charset): 90 | result = ann.run(flattenImage(image)) 91 | return charset[argmax(result)] 92 | 93 | def defaultRecognise(segments, addr, extras, ann, size, charset, resizer): 94 | segments = map(lambda seg: resizer(seg, size), segments) 95 | return "".join(map(lambda seg: recogniseChar(seg, ann, charset), segments)) -------------------------------------------------------------------------------- /cap/segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cvext, general 21 | from operator import itemgetter, attrgetter 22 | from numpy import linspace 23 | from types import TupleType, ListType 24 | 25 | def unwrap(components): 26 | t1 = type(components[0]) 27 | if (t1 == TupleType or t1 == ListType): 28 | t2 = type(components[0][3]) 29 | if t2 == cv.iplimage or t2 == cv.cvmat: 30 | return map(itemgetter(3), components) 31 | elif t1 == cv.iplimage or t1 == cv.cvmat: 32 | return components 33 | 34 | def shiftRect(rect, x, y): 35 | return (rect[0] + x, rect[1] + y, rect[2], rect[3]) 36 | 37 | def findCCs(image, erasecol=0, doContinue=None, doSkip=None, bRange=0, connectivity=8): 38 | """ 39 | Finds all connected components in the image. 40 | doContinue is a function applied to the color of every new pixel in the image. 41 | If it is true, this pixel is ignored. Default: <= 128 42 | doSkip is a function applied to every new connected component found by the 43 | function. If it is true, this component will not be included in the result. 44 | Default: do not skip anything. 45 | """ 46 | if doContinue is None: 47 | doContinue = lambda col: col <= 128 48 | if doSkip is None: 49 | doSkip = lambda comp: False 50 | mask = cv.CreateImage((image.width + 2, image.height + 2), cv.IPL_DEPTH_8U, 1) 51 | cv.Zero(mask) 52 | components = [] 53 | for x in range(image.width): 54 | for y in range(image.height): 55 | if doContinue(image[y, x]): 56 | continue 57 | comp = cv.FloodFill(image, (x, y), 0, bRange, bRange, connectivity + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), mask) # here 3rd argument is ignored 58 | region = shiftRect(comp[2], 1, 1) 59 | if not doSkip(comp): 60 | seg = cvext.getSubImage(mask, region) 61 | components.append((comp[0], comp[1], comp[2], seg)) 62 | cv.SetImageROI(image, comp[2]) 63 | cv.SetImageROI(mask, region) 64 | cv.Set(image, erasecol, mask) 65 | cv.Zero(mask) 66 | cv.ResetImageROI(image) 67 | cv.ResetImageROI(mask) 68 | return components 69 | 70 | def rectsIntersectH(rect1, rect2): 71 | minW3 = min(rect1[2], rect2[2]) / 3 72 | l1 = rect1[0] 73 | l2 = rect2[0] 74 | r1 = rect1[0] + rect1[2] 75 | r2 = rect2[0] + rect2[2] 76 | return (l2 < r1 - minW3 and r2 > l1 + minW3) or \ 77 | (l1 < r2 - minW3 and r1 > l2 + minW3) 78 | 79 | def distV(rect1, rect2): 80 | t1, b1 = rect1[1], rect1[1] + rect1[3] 81 | t2, b2 = rect2[1], rect2[1] + rect2[3] 82 | if b1 < t2: return t2 - b1 83 | if b2 < t1: return t1 - b2 84 | return 0 85 | 86 | def distH(rect1, rect2): 87 | l1, r1 = rect1[0], rect1[0] + rect1[2] 88 | l2, r2 = rect2[0], rect2[0] + rect2[2] 89 | if r1 < l2: return l2 - r1 90 | if r2 < l1: return l1 - r2 91 | return 0 92 | 93 | def joinComponents(components): 94 | rects = [comp[2] for comp in components] 95 | rect = (min([rect[0] for rect in rects]), min([rect[1] for rect in rects]), \ 96 | max([rect[0] + rect[2] for rect in rects]), max([rect[1] + rect[3] for rect in rects])) 97 | resW = rect[2] - rect[0] 98 | resH = rect[3] - rect[1] 99 | result = cv.CreateImage((resW, resH), cv.IPL_DEPTH_8U, 1) 100 | cv.Zero(result) 101 | for comp in components: 102 | region = cv.GetSubRect(result, shiftRect(comp[2], -rect[0], -rect[1])) 103 | cv.Or(comp[3], region, region, None) 104 | return [sum([comp[0] for comp in components]), 255.0, \ 105 | (rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1]), result] 106 | 107 | def joinCCs(components, rectsIntersect): 108 | i = 0 109 | while i < len(components) - 1: 110 | brothers = filter(lambda j: rectsIntersect(components[i][2], components[j][2]), xrange(i+1, len(components))) 111 | if brothers == []: 112 | i += 1 113 | continue 114 | brothers.append(i) 115 | family = joinComponents(map(lambda bro: components[bro], brothers)) 116 | components = [components[j] for j in xrange(len(components)) if j not in brothers] 117 | components[i:i] = [family] 118 | return components 119 | 120 | def splitAt(image, splitters): 121 | if splitters == []: 122 | return [image] 123 | segments = [] 124 | regions = [] 125 | for i in xrange(len(splitters) - 1): 126 | region = (splitters[i], 0, splitters[i+1] - splitters[i], image.height) 127 | regions.append(region) 128 | seg = cvext.getSubImage(image, region) 129 | segments.append(seg) 130 | return segments, regions 131 | 132 | def projectDown(image): 133 | proj = [] 134 | for x in range(image.width): 135 | col = cv.GetCol(image, x) 136 | sum = cv.Sum(col) 137 | proj.append(sum) 138 | return proj 139 | 140 | def splitIntoNParts(image, parts, projRadius): 141 | splitters = linspace(0, image.width - 1, parts + 1) 142 | projection = projectDown(image) 143 | def adjust(splitter): 144 | if splitter == 0 or splitter == image.width - 1: 145 | return splitter 146 | neighborhood = projection[splitter - projRadius : splitter + projRadius + 1] 147 | return general.argmin(neighborhood) + splitter - projRadius 148 | splitters = general.amap(adjust, splitters.astype(int)) 149 | segments, regions = splitAt(image, splitters) 150 | return segments, regions 151 | 152 | CAP_BOUND_LEFT = 0 153 | CAP_BOUND_RIGHT = 1 154 | CAP_BOUND_TOP = 2 155 | CAP_BOUND_BOTTOM = 3 156 | 157 | def getBound(image, bound, thresh=1, colthresh=0, start=None, stop=None): 158 | if bound == CAP_BOUND_LEFT or bound == CAP_BOUND_RIGHT: 159 | if bound == CAP_BOUND_LEFT: 160 | if start is None: start = 0 161 | if stop is None: stop = image.width 162 | step = 1 163 | else: 164 | if start is None: start = image.width - 1 165 | if stop is None: stop = -1 166 | step = -1 167 | for x in xrange(start, stop, step): 168 | n = 0 169 | for y in xrange(image.height): 170 | if image[y, x] > colthresh: 171 | n += 1 172 | if n >= thresh: 173 | return x 174 | return start 175 | elif bound == CAP_BOUND_TOP or bound == CAP_BOUND_BOTTOM: 176 | if bound == CAP_BOUND_TOP: 177 | if start is None: start = 0 178 | if stop is None: stop = image.height 179 | step = 1 180 | else: 181 | if start is None: start = image.height - 1 182 | if stop is None: stop = -1 183 | step = -1 184 | for y in xrange(start, stop, step): 185 | n = 0 186 | for x in xrange(image.width): 187 | if image[y, x] > colthresh: 188 | n += 1 189 | if n >= thresh: 190 | return y 191 | return start 192 | else: raise ValueError("Cannot interpret 'bound' argument (%d)" % (bound)) 193 | 194 | def findNonBlackRect(image, thresh, colthresh=0): 195 | newTop = getBound(image, CAP_BOUND_TOP, thresh, colthresh) 196 | newBottom = getBound(image, CAP_BOUND_BOTTOM, thresh, colthresh) 197 | newLeft = getBound(image, CAP_BOUND_LEFT, thresh, colthresh) 198 | newRight = getBound(image, CAP_BOUND_RIGHT, thresh, colthresh) 199 | return (newLeft, newTop, newRight - newLeft, newBottom - newTop) 200 | 201 | def cutNonBlackImage(image, thresh=1, colthresh=0): 202 | newRect = findNonBlackRect(image, thresh, colthresh) 203 | if newRect[2] == 0 or newRect[3] == 0: 204 | return None 205 | region = cvext.getSubImage(image, newRect) 206 | return region 207 | 208 | def cutNonBlack(comp, thresh, colthresh=0): 209 | image = comp[3] 210 | rect = comp[2] 211 | newRect = findNonBlackRect(image, thresh, colthresh) 212 | if newRect[2] == 0 or newRect[3] == 0: 213 | return None 214 | region = cvext.getSubImage(image, newRect) 215 | newRect = shiftRect(newRect, rect[0], rect[1]) 216 | return (cv.CountNonZero(region), 255.0, newRect, region) 217 | 218 | def partsFromSegW(components, segW): 219 | return map(lambda comp: comp[3].width / segW + 1, components) 220 | 221 | # Doesn't work, needs thinking on 222 | #expansions = {} 223 | # 224 | #def getExpansion(n): 225 | # if n in expansions: 226 | # return expansions[n] 227 | # cur = [(1, )] 228 | # for i in xrange(1, n): 229 | # a = deque(cur) 230 | # b = deque(cur) 231 | # a.append((1, ) * i) 232 | # b.appendleft((i, )) 233 | # cur = map(lambda x, y: ((x[0] + 1) + x[1:]), a, b) 234 | # expansions[n] = cur 235 | # return cur 236 | 237 | five = \ 238 | ((5, ), \ 239 | (1, 4), (2, 3), (3, 2), (4, 1), \ 240 | (1, 1, 3), (1, 3, 1), (3, 1, 1), (2, 2, 1), (2, 1, 2), (1, 2, 2), \ 241 | (1, 1, 1, 2), (1, 1, 2, 1), (1, 2, 1, 1), (2, 1, 1, 1), \ 242 | (1, 1, 1, 1, 1)) 243 | 244 | five3 = filter(lambda exp: len(exp) == 3, five) 245 | 246 | def distance(pt1, pt2): 247 | if len(pt1) != len(pt2): 248 | raise ValueError("Points must be of the same dimensionality.") 249 | return sum([(x1 - x2)**2 for (x1, x2) in zip(pt1, pt2)]) 250 | 251 | 252 | def partsFromnSegs5(components): 253 | segments = unwrap(components) 254 | if len(segments) == 5: 255 | return (1, 1, 1, 1, 1) 256 | elif len(segments) == 4: 257 | widths = map(attrgetter("width"), segments) 258 | widest = general.argmax(widths) 259 | result = [1] * 4 260 | result[widest] = 2 261 | return result 262 | elif len(segments) == 3: 263 | widths = map(attrgetter("width"), segments) 264 | narrowest = float(min(widths)) 265 | reduced = map(lambda width: width / narrowest, widths) 266 | distances = map(lambda exp: distance(exp, reduced), five3) 267 | #print widths, narrowest, reduced, zip(distances, five3) 268 | return five3[general.argmin(distances)] 269 | elif len(segments) == 2: 270 | w0, w1 = segments[0].width, segments[1].width 271 | frac = float(w0) / float(w1) 272 | if frac < 1.0: frac = 1.0 / frac 273 | if frac > 2.75: return (4, 1) if w0 > w1 else (1, 4) 274 | else: return (3, 2) if w0 > w1 else (2, 3) 275 | elif len(segments) == 1: 276 | return (5, ) 277 | else: return (1, ) * len(segments) # raise ValueError("Incorrect number of components: %d" % (len(segments))) 278 | 279 | def spltCCs(components, allParts, projRadius, thresh=2): 280 | index = 0 281 | for parts in allParts: 282 | assert(parts >= 1) 283 | comp = components[index] 284 | seg = comp[3] 285 | rect = comp[2] 286 | if parts > 1: 287 | segments, rects = splitIntoNParts(seg, parts, projRadius) 288 | rects = map(lambda rect1: shiftRect(rect1, rect[0], rect[1]), rects) 289 | mapper = lambda segIndex: (0.0, 255.0, \ 290 | rects[segIndex], segments[segIndex]) 291 | comp = map(mapper, xrange(parts)) 292 | comp = map(lambda comp: cutNonBlack(comp, thresh), comp) 293 | comp = filter(lambda comp: comp is not None, comp) 294 | components[index: index + 1] = comp 295 | index += parts 296 | return components -------------------------------------------------------------------------------- /captchure.komodoproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | *.*~;*.bak;*.tmp;CVS;.#*;*.pyo;*.pyc;.svn;_svn;.git;.hg;.bzr;*%*;tmp*.html;.DS_Store;*.swp;*.kpf;*.komodoproject;*.komodotools 7 | 8 | 1 9 | 10 | 11 | 12 | 1 13 | 14 | cap 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /demo.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | echo RUNNING RED 4 | main.py red --directory testset 5 | 6 | echo RUNNING GREEN 7 | main.py green --directory testset 8 | 9 | echo RUNNING BLUE 10 | main.py blue --directory testset --mode color 11 | 12 | echo RUNNING YELLOW 13 | main.py yellow --directory testset --mode color -------------------------------------------------------------------------------- /deprecated/clear.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import sys, os 21 | from globConst import ann_file, train_file, segment_dir 22 | 23 | if len(sys.argv) == 1: 24 | sys.exit(0) 25 | 26 | def clear_pyc(): 27 | files = os.listdir(".") 28 | for name in files: 29 | if name.endswith(".pyc"): 30 | os.remove(name) 31 | 32 | def clear_data(): 33 | if os.path.exists(train_file): os.remove(train_file) 34 | if os.path.exists(ann_file): os.remove(ann_file) 35 | 36 | def clear_segments(): 37 | files = os.listdir(segment_dir) 38 | for name in files: 39 | os.remove(os.path.join(segment_dir, name)) 40 | 41 | if sys.argv[1] == "pyc": clear_pyc() 42 | elif sys.argv[1] == "data": clear_data() 43 | elif sys.argv[1] == "segments": clear_segments() 44 | elif sys.argv[1] == "all": 45 | clear_pyc() 46 | clear_data() 47 | clear_segments() -------------------------------------------------------------------------------- /deprecated/deprecated.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | tooWide = filter(lambda index: components[index].width > rsegWMax, range(len(components))) 21 | while len(tooWide) > 1: 22 | index = tooWide[0] 23 | image = components[index] 24 | parts = image.width / rsegWMax + 1 25 | result = splitIntoNParts(image, parts) 26 | components[index:index+1] = result 27 | del(tooWide[0]) 28 | tooWide = map(lambda index: index + parts - 1, tooWide) 29 | if len(tooWide) == 1: 30 | if len(components) != nSegs: 31 | widestIndex = tooWide[0] 32 | image = components[widestIndex] 33 | parts = nSegs - len(components) + 1 34 | result = splitIntoNParts(image, parts) 35 | components[widestIndex:widestIndex+1] = result 36 | 37 | def saveImagePlot(image, title, peaks): 38 | anglesLo = np.arange(-30, 30, 0.5) # 0 39 | anglesR = np.arange( 60, 120, 0.5) # 90 40 | anglesUp = np.arange(150, 210, 0.5) # 180 41 | anglesL = np.arange(240, 300, 0.5) # 270 42 | 43 | appr = approximator(cv.GetSize(image)) 44 | ratingsUp = appr.rateAll(image, anglesUp) 45 | ratingsLo = appr.rateAll(image, anglesLo) 46 | ratingsL = appr.rateAll(image, anglesL) 47 | ratingsR = appr.rateAll(image, anglesR) 48 | 49 | plt.plot(anglesLo, ratingsUp, 'b-') 50 | plt.plot(anglesLo, ratingsLo, 'r-') 51 | plt.plot(anglesLo, ratingsL, 'g-') 52 | plt.plot(anglesLo, ratingsR, 'y-') 53 | 54 | colors = ('b', 'r', 'g', 'y') 55 | offsets = (180.0, 0.0, 270.0, 90.0) 56 | for i in range(4): 57 | if peaks[i] is not None: 58 | plt.axvline(peaks[i] - offsets[i], color=colors[i]) 59 | 60 | plt.title(title) 61 | plt.xlabel("Line angle") 62 | plt.ylabel("Line rating") 63 | plt.savefig(os.path.join(plot_dir, title + ".png")) 64 | #plt.show() 65 | plt.clf() 66 | 67 | def rotatedProjectionWidth(image, alpha, projectionAngle): 68 | appr = approximator(cv.GetSize(image), -alpha + projectionAngle) 69 | appr.setCollisionPoint(image) 70 | pt1 = appr.pos1 71 | off1 = appr.collisionPoint 72 | appr.setAlpha(-alpha + projectionAngle + 180.0) 73 | appr.setCollisionPoint(image) 74 | pt2 = appr.pos1 75 | off2 = appr.collisionPoint 76 | h = abs(pt2 - pt1) - (off1 + off2) 77 | return h * cos(rad(alpha)) 78 | 79 | def saveProjectionPlot(image, original, title): 80 | plt.figure(num=1, figsize=(9, 9)) 81 | plt.subplot(311) 82 | angles = np.arange(-30, 30, 0.5) 83 | distances = map(lambda angle: rotatedProjectionWidth(image, angle, 90.0), angles) 84 | plt.plot(angles, distances) 85 | plt.title(title) 86 | plt.xlabel("Angle") 87 | plt.ylabel("Projection width") 88 | plt.subplot(312) 89 | plotCvImage(original) 90 | plt.subplot(313) 91 | plotCvImage(image) 92 | #plt.savefig(os.path.join(plot_dir, title + ".png")) 93 | plt.show() 94 | plt.clf() 95 | 96 | def clearDots1C(image, size): 97 | for x in xrange(image.width): 98 | for y in xrange(image.height): 99 | col = image[y, x] 100 | if col > 0 and col != 254: 101 | comp = cv.FloodFill(image, (x, y), 254, 0, 0, 4, None) 102 | if comp[0] <= size: 103 | cv.FloodFill(image, (x, y), 0, 0, 0, 4, None) 104 | 105 | b, g, r = doSplit(image) 106 | for ch in (b, g, r): 107 | cv.Threshold(ch, ch, 200, 255, cv.CV_THRESH_BINARY_INV) 108 | clearDots(ch, size) 109 | cv.Threshold(ch, ch, 128, 255, cv.CV_THRESH_BINARY_INV) 110 | mask = copyHeader1C(image) 111 | cv.Or(b, g, mask, None) 112 | cv.Or(r, mask, mask, None) 113 | cv.Set(image, cv.ScalarAll(255), mask) 114 | 115 | 116 | 117 | def copyHeader1C(image): 118 | return cv.CreateImage(cv.GetSize(image), image.depth, 1) 119 | 120 | def doSplit(image): 121 | c1, c2, c3 = copyHeader1C(image), copyHeader1C(image), copyHeader1C(image) 122 | cv.Split(image, c1, c2, c3, None) 123 | return c1, c2, c3 124 | 125 | def getBlackWhite(image): 126 | gs = cv.CreateImage(cv.GetSize(image), image.depth, 1) 127 | cv.CvtColor(image, gs, cv.CV_BGR2GRAY) 128 | bw = cv.CreateImage(cv.GetSize(image), image.depth, 1) 129 | cv.Threshold(gs, bw, 254, 255, cv.CV_THRESH_BINARY_INV) 130 | return bw 131 | 132 | """ 133 | 134 | def createMask(image): 135 | mask = cv.CreateImage((image.width + 2, image.height + 2), cv.IPL_DEPTH_8U, 1) 136 | cv.Zero(mask) 137 | return mask 138 | 139 | """ 140 | 141 | def segment(image, addr, extras): 142 | def splitIntoNParts(image, parts): 143 | splitters = np.linspace(0, image.width - 1, parts + 1) 144 | projection = prelude.projectDown(image) 145 | n = 4 146 | def adjust(splitter): 147 | if splitter == 0 or splitter == image.width - 1: 148 | return splitter 149 | neighborhood = projection[splitter - n : splitter + n + 1] 150 | return prelude.argmin(neighborhood) + splitter - n 151 | splitters = prelude.amap(adjust, splitters.astype(int)) 152 | result = prelude.splitAt(image, splitters) 153 | return result 154 | components = findConnectedComponents(image) 155 | while len(components) < nSegs: 156 | index = prelude.argmax(components, attrgetter("width")) 157 | image = components[index] 158 | parts = image.width / rsegW + 1 159 | result = splitIntoNParts(image, parts) 160 | components[index:index+1] = result 161 | components = map(adjustSize, components) 162 | return components 163 | 164 | def plotCvImage(image, interpolation='linear'): 165 | if image.nChannels == 1: 166 | image = Image.fromstring("L", cv.GetSize(image), image.tostring()) 167 | elif image.nChannels == 3: 168 | image = Image.fromstring("RGB", cv.GetSize(image), image.tostring()) 169 | plt.imshow(image.transpose(Image.FLIP_TOP_BOTTOM), cmap=plt.cm.gray, shape=image.size, interpolation=interpolation) 170 | 171 | while index < len(components): 172 | comp = components[index] 173 | seg = comp[3] 174 | rect = comp[2] 175 | if seg.width > maxW: 176 | parts = seg.width / maxW + 1 177 | segments, rects = splitIntoNParts(seg, parts, projRadius) 178 | rects = map(lambda rect1: shiftRect(rect1, rect[0], rect[1]), rects) 179 | mapper = lambda segIndex: (0.0, 255.0, \ 180 | rects[segIndex], segments[segIndex]) 181 | comp = map(mapper, xrange(parts)) 182 | comp = map(lambda comp: cutNonBlack(comp, thresh), comp) 183 | comp = filter(lambda comp: comp is not None, comp) 184 | components[index: index + 1] = comp 185 | index += parts 186 | else: index += 1 187 | return components 188 | 189 | """ 190 | # RGB, divided by 51 191 | gray = ((3,3,3), (3,2,3), (3,2,2), (2,2,2)) 192 | blue = ((1,1,3), (1,1,2), (0,1,2), (0,0,2)) 193 | lgreen = ((1,2,2), (1,3,2), (1,2,1), (0,2,1)) 194 | dgreen = ((1,1,1), (0,1,0), (0,0,0)) 195 | """ 196 | 197 | """ 198 | 199 | def splitChannels(image): 200 | ch1 = cv.CreateImage(cv.GetSize(image), image.depth, 1) 201 | ch2 = cv.CreateImage(cv.GetSize(image), image.depth, 1) 202 | ch3 = cv.CreateImage(cv.GetSize(image), image.depth, 1) 203 | ch4 = cv.CreateImage(cv.GetSize(image), image.depth, 1) 204 | ch5 = cv.CreateImage(cv.GetSize(image), image.depth, 1) 205 | cv.CmpS(image, mygray, ch1, cv.CV_CMP_EQ) 206 | cv.CmpS(image, myblue, ch2, cv.CV_CMP_EQ) 207 | cv.CmpS(image, mylgrn, ch3, cv.CV_CMP_EQ) 208 | cv.CmpS(image, mydgrn, ch4, cv.CV_CMP_EQ) 209 | cv.CmpS(image, myunkn, ch5, cv.CV_CMP_EQ) 210 | return ch1, ch2, ch3, ch4, ch5 211 | 212 | """ 213 | 214 | """ 215 | 216 | def mergeChannels(channels): 217 | result = cv.CreateImage(cv.GetSize(channels[0]), cv.IPL_DEPTH_8U, 1) 218 | temp = cv.CreateImage(cv.GetSize(channels[0]), cv.IPL_DEPTH_8U, 1) 219 | cv.Set(result, 255) 220 | for ch, col in zip(channels, mycolors): 221 | cv.Threshold(ch, temp, 128, 255, cv.CV_THRESH_BINARY_INV) 222 | cv.Set(result, col, temp) 223 | return result 224 | 225 | """ 226 | 227 | #angles = map(getRotationAngle, components) 228 | #angles = filter(lambda angle: angle is not None, angles) 229 | #alpha = 0.0 if len(angles) == 0 else sum(angles) / len(angles) 230 | #if abs(alpha) > 0.1: 231 | # segments = map(lambda seg: rotate(seg, -alpha, 0), segments) 232 | # segments = map(lambda seg: getSubImage(seg, findNonBlackRect(seg)), segments) 233 | # steps.append(joinImagesH(segments)) 234 | 235 | def findCol(image, left): 236 | if left: 237 | start, stop, step = 0, image.width, 1 238 | else: 239 | start, stop, step = image.width - 1, -1, -1 240 | for x in xrange(start, stop, step): 241 | col = cv.GetCol(image, x) 242 | if cv.CountNonZero(col) > 0: 243 | return x 244 | 245 | def findRow(image, top): 246 | if top: 247 | start, stop, step = 0, image.height, 1 248 | else: 249 | start, stop, step = image.height - 1, -1, -1 250 | for y in xrange(start, stop, step): 251 | row = cv.GetRow(image, y) 252 | if cv.CountNonZero(row) > 0: 253 | return y 254 | 255 | def findFirstLast(array): 256 | if array.width == 1: 257 | first = 0 258 | last = array.height - 1 259 | for y in xrange(array.height): 260 | if array[y, 0] == 255: 261 | first = y 262 | break 263 | for y in xrange(array.height - 1, -1, -1): 264 | if array[y, 0] == 255: 265 | last = y 266 | break 267 | return (first, last) 268 | elif array.height == 1: 269 | first = 0 270 | last = array.width - 1 271 | for x in xrange(array.width): 272 | if array[0, x] == 255: 273 | first = x 274 | break 275 | for x in xrange(array.width - 1, -1, -1): 276 | if array[0, x] == 255: 277 | last = x 278 | break 279 | return (first, last) 280 | 281 | def getRotationAngle(comp): 282 | def mean(x, y): 283 | return (x + y) / 2 284 | image = comp[3] 285 | leftCol = 0 286 | rightCol = image.width - 1 287 | topRow = 0 288 | bottomRow = image.height - 1 289 | left = mean(*findFirstLast(cv.GetCol(image, leftCol))) 290 | right = mean(*findFirstLast(cv.GetCol(image, rightCol))) 291 | top = mean(*findFirstLast(cv.GetRow(image, topRow))) 292 | bottom = mean(*findFirstLast(cv.GetRow(image, bottomRow))) 293 | lP = (leftCol, left) 294 | rP = (rightCol, right) 295 | tP = (top, topRow) 296 | bP = (bottom, bottomRow) 297 | lowerP, upperP = (lP, rP) if lP[1] > rP[1] else (rP, lP) 298 | lowerPts = (bP, lowerP) 299 | upperPts = (tP, upperP) 300 | #cv.Line(image, bP, lowerP, 96) 301 | #cv.Line(image, tP, upperP, 160) 302 | bottomSlope = findLineSlope(bP, lowerP) 303 | topSlope = findLineSlope(tP, upperP) 304 | #print bottomSlope, topSlope 305 | lim = 20.0 306 | def truncate(x): 307 | return x if -lim <= x <= lim else None 308 | topSlope = truncate(topSlope) 309 | bottomSlope = truncate(bottomSlope) 310 | if topSlope is None: 311 | return bottomSlope 312 | else: 313 | if bottomSlope is None: 314 | return topSlope 315 | else: 316 | return mean(topSlope, bottomSlope) 317 | 318 | def merge(gray, blue, lgrn, dgrn): 319 | result = cv.CreateImage(cv.GetSize(gray), gray.depth, gray.nChannels) 320 | cv.Set(result, mygray, gray) 321 | cv.Set(result, myblue, blue) 322 | cv.Set(result, mylgrn, lgrn) 323 | cv.Set(result, mydgrn, dgrn) 324 | return result 325 | 326 | 327 | """ # this piece of code makes sure that the highest possible quality is achieved 328 | presult = result 329 | while result is not None: 330 | presult = result 331 | tLetter += 1 332 | result = doThis() 333 | result = presult 334 | while result is not None: 335 | presult = result 336 | rBright += 1 337 | result = doThis() 338 | result = presult 339 | """ 340 | 341 | def findConnectedComponents(image, size): 342 | mask = cv.CreateImage((image.width + 2, image.height + 2), cv.IPL_DEPTH_8U, 1) 343 | cv.Zero(mask) 344 | components = [] 345 | data = [] 346 | for x in range(image.width): 347 | for y in range(image.height): 348 | if image[y, x] <= 128: 349 | continue 350 | comp = cv.FloodFill(image, (x, y), 255, 0, 0, 8 + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), mask) 351 | if comp[0] <= size: 352 | continue 353 | seg = cv.GetSubRect(mask, shiftRect(comp[2], 1, 1)) 354 | seg = prelude.matToImage(seg, cv.IPL_DEPTH_8U, 1) 355 | comp = list(comp) 356 | comp.append(seg) 357 | components.append(comp) 358 | cv.Zero(mask) 359 | cv.FloodFill(image, (x, y), 0, 0, 0, 8, None) 360 | return components 361 | 362 | def removeNoise(image, log): 363 | noiseMask = getNoiseMask(image, 15, 4) 364 | whiteMask = findColor(image, white) 365 | unknMask = findColor(image, myunkn) 366 | mask1 = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) 367 | cv.Or(noiseMask, unknMask, mask1) 368 | log.log(mask1) 369 | cv.Or(mask1, whiteMask, mask1) 370 | image = doInpaint(image, mask1) 371 | log.log(image) 372 | cv.Set(image, 255, whiteMask) 373 | log.log(image) 374 | noiseMask = getNoiseMask(image, 15, 4) 375 | image = doInpaint(image, noiseMask) 376 | log.log(image) 377 | return image 378 | 379 | """ 380 | kerW, kerH = 19, 19 381 | b = float(kerW * kerH) / 10.0 382 | kerCX, kerCY = kerW // 2, kerH // 2 383 | kerCX2 = kerCX // 2 384 | kerCX14 = kerCX // 4 385 | kerCX34 = kerCX * 3 // 4 386 | kernel = cv.CreateMat(kerW, kerH, cv.CV_32FC1) 387 | for x in xrange(kerW): 388 | for y in xrange(kerH): 389 | dist = sqrt((x - kerCX)**2 + (y - kerCY)**2) 390 | kernel[y, x] = (kerCX2 - abs(kerCX2 - dist)) / b if kerCX14 < dist < kerCX34 else 0.0 391 | cv.Mul(kernel, kernel, kernel) 392 | """ 393 | """ 394 | result = cv.CreateImage(cv.GetSize(ch), cv.IPL_DEPTH_32F, 1) 395 | cv.Filter2D(ch, result, kernel) 396 | #cv.Mul(result, result, result) 397 | cv.SaveImage("channel.png", ch) 398 | cv.SaveImage("image.png", result) 399 | cv.NamedWindow("Filter", 1) 400 | cv.ShowImage("Filter", result) 401 | cv.WaitKey(0) 402 | """ -------------------------------------------------------------------------------- /deprecated/filter_segments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os 21 | 22 | dir1 = "segments" 23 | dir2 = "segmented" 24 | 25 | segs = os.listdir(dir1) 26 | 27 | for seg in os.listdir(dir2): 28 | if seg in segs: 29 | pass#os.remove(os.path.join(dir1, seg)) 30 | else: 31 | os.remove(os.path.join(dir2, seg)) -------------------------------------------------------------------------------- /deprecated/recognise_naive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cap 21 | from lconsts import ann_file, charset, segSize 22 | 23 | ann = cap.loadAnn(ann_file) 24 | 25 | def recognise(segments, addr, extras): 26 | return cap.defaultRecognise(segments, addr, extras, ann, segSize, charset, cap.resizeFit) -------------------------------------------------------------------------------- /deprecated/recognise_seg_naive.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from operator import itemgetter 22 | from lconsts import mycolors, nSegs, segSize, ann_file, charset 23 | from cap import resizeFit as adjustSize 24 | 25 | minW = 15 26 | maxW = 40 27 | 28 | ann = cap.loadAnn(ann_file) 29 | colors = map(lambda col: 255 - col, mycolors) 30 | 31 | def findBounds(image, right, w): 32 | left = right - w + 1 33 | cols = cv.GetCols(image, left, right + 1) 34 | top = cap.getBound(cols, cap.CAP_BOUND_TOP) 35 | bottom = cap.getBound(cols, cap.CAP_BOUND_BOTTOM) 36 | return (left, top, w, bottom - top) 37 | 38 | def extractCol(image, col): 39 | result = cv.CreateImage(cv.GetSize(image), cv.IPL_DEPTH_8U, 1) 40 | cv.CmpS(image, col, result, cv.CV_CMP_EQ) 41 | return result 42 | 43 | def getChannels(image): 44 | return map(lambda col: extractCol(image, col), colors) 45 | 46 | def findColors(image): 47 | flags = [False, False, False, False] 48 | for x in xrange(image.width): 49 | for y in xrange(image.height): 50 | col = image[y, x] 51 | if col == 0: continue 52 | flags[cap.find(colors, col)] = True 53 | return flags 54 | 55 | def getSegment(channel, image, rect, bgcolor=96): 56 | seg = cap.getSubImage(channel, rect) 57 | original = cv.GetSubRect (image, rect) 58 | for x in xrange(original.width): 59 | for y in xrange(original.height): 60 | if original[y, x] != 0 and seg[y, x] != 255: 61 | seg[y, x] = bgcolor 62 | return seg 63 | 64 | 65 | def recognise(image, addr, extras): 66 | result = "" 67 | x = image.width - 1 68 | channels = getChannels(image) 69 | bestBounds = [] 70 | #cv.NamedWindow("pic", 1) 71 | #cv.NamedWindow("cols", 0) 72 | while len(result) < nSegs and x >= minW: 73 | x = cap.getBound(image, cap.CAP_BOUND_RIGHT, start=x) 74 | ratings = [] 75 | for w in xrange(minW, min(maxW + 1, x)): 76 | bounds = findBounds(image, x, w) 77 | subImage = cap.getSubImage(image, bounds) 78 | flags = findColors(subImage) 79 | for index, flag in enumerate(flags): 80 | if not flag: continue 81 | seg = getSegment(channels[index], image, bounds) 82 | seg = cap.flattenImage(adjustSize(seg, segSize)) 83 | guesses = ann.run(seg) 84 | charIndex = cap.argmax(guesses) 85 | ratings.append((guesses[charIndex], charIndex, index, bounds, seg)) 86 | best = max(ratings, key=itemgetter(0)) 87 | result += charset[best[1]] 88 | bestChannel = channels[best[2]] 89 | cv.SetImageROI(bestChannel, best[3]) 90 | cv.Set(bestChannel, 96, bestChannel) 91 | cv.ResetImageROI(bestChannel) 92 | bestBounds.append(best[3]) 93 | bestW = best[3][2] 94 | x -= bestW 95 | #print ann.run(best[4]) 96 | cap.processExtras([cap.drawComponents(image, bestBounds)], addr, extras, cap.CAP_STAGE_RECOGNISE) 97 | return result[::-1] -------------------------------------------------------------------------------- /deprecated/test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, sys, copy, shutil, main 21 | sys.path.append("beeline") 22 | import train 23 | 24 | original_spoilers = copy.copy(train.spoilers) 25 | 26 | minerror = 10.0 27 | 28 | for index in xrange(len(original_spoilers)): 29 | print "%d: " % (index), 30 | train.spoilers = original_spoilers[:index] + original_spoilers[index+1:] 31 | rootDir = os.getcwd() 32 | os.chdir("beeline") 33 | train.train() 34 | os.chdir(rootDir) 35 | error = main.main(["beeline", "--directory", "testset", "--mode", "color"]) 36 | print error, 37 | if error < minerror: 38 | shutil.copyfile("beeline\\ann.net", "beeline\\beeline_" + str(int(error * 100)) + "_" + str(index) + ".net") 39 | print "saved" -------------------------------------------------------------------------------- /deprecated/test_red.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys, random 21 | from preprocess import preprocess 22 | from segment import segment 23 | from recognise import recognise 24 | from globConst import sample_dir, test_dir 25 | 26 | if len(sys.argv) == 1: 27 | folder = test_dir 28 | contents = os.listdir(folder) 29 | name = os.path.join(folder, contents[random.randint(0, len(contents) - 1)]) 30 | elif sys.argv[1] == "sample": 31 | folder = sample_dir 32 | contents = os.listdir(folder) 33 | name = os.path.join(folder, contents[random.randint(0, len(contents) - 1)]) 34 | else: 35 | name = sys.argv[1] 36 | 37 | image = cv.LoadImage(name, cv.CV_LOAD_IMAGE_GRAYSCALE) 38 | cv.NamedWindow("Original", 1) 39 | cv.ShowImage("Original", image) 40 | pp_image = preprocess(image) 41 | print "%s: preprocessed" % name 42 | cv.NamedWindow("Preprocessed", 1) 43 | cv.ShowImage("Preprocessed", pp_image) 44 | cv.WaitKey(0) 45 | segments = segment(pp_image) 46 | print "%s: segmented -> %d" % (name, len(segments)) 47 | for i in range(len(segments)): 48 | cv.NamedWindow(str(i), 1) 49 | cv.ShowImage(str(i), segments[i]) 50 | cv.WaitKey(0) 51 | chars = map(recognise, segments) 52 | result = "".join(map(str, chars)) 53 | print "%s: recognised -> %s" % (name, result) 54 | cv.WaitKey(0) -------------------------------------------------------------------------------- /deprecated/threshold.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys, random 21 | from globConst import sample_dir 22 | 23 | if len(sys.argv) == 1: 24 | folder = test_dir 25 | contents = os.listdir(folder) 26 | name = os.path.join(folder, contents[random.randint(0, len(contents) - 1)]) 27 | elif sys.argv[1] == "sample": 28 | folder = sample_dir 29 | contents = os.listdir(folder) 30 | name = os.path.join(folder, contents[random.randint(0, len(contents) - 1)]) 31 | else: 32 | name = sys.argv[1] 33 | 34 | print name 35 | 36 | class analyzer: 37 | def __init__(self, image): 38 | self.image = image 39 | self.clone = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 40 | self.tLetter = 64 41 | self.rBright = 30 42 | def clearNoise(self, image): 43 | for x in range(image.width): 44 | for y in range(image.height): 45 | if image[y, x] == 0: 46 | continue 47 | if image[y, x] < self.tLetter: 48 | cv.FloodFill(image, (x, y), 0, self.rBright, self.rBright, 8, None) 49 | cv.Threshold(image, image, 1, 255, cv.CV_THRESH_BINARY_INV) 50 | def reDraw(self): 51 | cv.Copy(self.image, self.clone) 52 | self.clearNoise(self.clone) 53 | cv.ShowImage("Threshold", self.clone) 54 | def onChangeLetter(self, ntLetter): 55 | self.tLetter = ntLetter 56 | self.reDraw() 57 | def onChangeBright(self, nrBright): 58 | self.rBright = nrBright 59 | self.reDraw() 60 | def run(self): 61 | cv.NamedWindow("Threshold", 1) 62 | cv.ShowImage("Threshold", image) 63 | cv.CreateTrackbar("tLetter", "Threshold", self.tLetter, 255, self.onChangeLetter) 64 | cv.CreateTrackbar("rBright", "Threshold", self.rBright, 255, self.onChangeBright) 65 | self.reDraw() 66 | cv.WaitKey(0) 67 | 68 | 69 | image = cv.LoadImage(name, cv.CV_LOAD_IMAGE_GRAYSCALE) 70 | analyzer(image).run() -------------------------------------------------------------------------------- /green/lconsts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | imgW = 450 21 | imgH = 175 22 | 23 | nSegs = 4 24 | 25 | segW = 30 26 | segH = 30 27 | segSize = (segW, segH) 28 | 29 | rsegW = 90 30 | rsegH = 90 31 | 32 | charset = "23456789abcdefkmnpqsuvwxyz" 33 | 34 | num_input = segW * segH 35 | num_output = len(charset) 36 | 37 | train_file = "ann.train" 38 | ann_file = "ann.net" 39 | 40 | segment_dir = "segments" -------------------------------------------------------------------------------- /green/preprocess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from math import tan, pi, radians as rad 22 | from numpy import linspace 23 | 24 | class approximator: 25 | def __init__(self, (w, h), alpha = None): 26 | self.w = w 27 | self.h = h 28 | if alpha is not None: 29 | self.setAlpha(alpha) 30 | def endPointsH(self, off): 31 | pt1 = (0, self.pos1 + self.step * off) 32 | pt2 = (self.w - 1, self.pos2 + self.step * off) 33 | return (pt1, pt2) 34 | def endPointsV(self, off): 35 | pt1 = (self.pos1 + self.step * off, 0) 36 | pt2 = (self.pos2 + self.step * off, self.h - 1) 37 | return (pt1, pt2) 38 | def coords(self, off): 39 | (pt1x, pt1y), (pt2x, pt2y) = self.endPoints(off) 40 | try: 41 | return cv.ClipLine((self.w, self.h), (int(pt1x), int(pt1y)), (int(pt2x), int(pt2y))) 42 | except: 43 | print off, self.alpha 44 | raise 45 | def setAlpha(self, alpha): 46 | alpha = alpha % 360 47 | self.alpha = alpha 48 | if alpha < 45.0: # 1 49 | self.pos1 = self.h - 1 + self.w * tan(rad(alpha)) 50 | self.pos2 = self.h - 1 51 | self.step = -1 52 | self.endPoints = self.endPointsH 53 | self.span = self.h 54 | return 55 | if 45.0 <= alpha < 90.0: # 2 56 | self.pos1 = self.w - 1 + self.h / tan(rad(alpha)) 57 | self.pos2 = self.w - 1 58 | self.step = -1 59 | self.endPoints = self.endPointsV 60 | self.span = self.w 61 | return 62 | if 90.0 <= alpha < 135.0: # 3 63 | self.pos1 = self.w - 1 64 | self.pos2 = self.w - 1 - self.h / tan(rad(alpha)) 65 | self.step = -1 66 | self.endPoints = self.endPointsV 67 | self.span = self.w 68 | return 69 | if 135.0 <= alpha < 180.0: # 4 70 | self.pos1 = self.w * tan(rad(alpha)) # this is correct since tan(pi - x) = -tan x 71 | self.pos2 = 0 72 | self.step = 1 73 | self.endPoints = self.endPointsH 74 | self.span = self.h 75 | return 76 | if 180.0 <= alpha < 225.0: # 5 77 | self.pos1 = 0 78 | self.pos2 = -self.w * tan(rad(alpha)) 79 | self.step = 1 80 | self.endPoints = self.endPointsH 81 | self.span = self.h 82 | return 83 | if 225.0 <= alpha < 270.0: # 6 84 | self.pos1 = 0 85 | self.pos2 = -self.h / tan(rad(alpha)) 86 | self.step = 1 87 | self.endPoints = self.endPointsV 88 | self.span = self.w 89 | return 90 | if 270.0 <= alpha < 315.0: # 7 91 | self.pos1 = self.h / tan(rad(alpha)) # this is correct since tan(x - 3/2 * pi) = -cot x 92 | self.pos2 = 0 93 | self.step = 1 94 | self.endPoints = self.endPointsV 95 | self.span = self.w 96 | return 97 | if 315.0 <= alpha: # 8 98 | self.pos1 = self.h - 1 99 | self.pos2 = self.h - 1 - self.w * tan(rad(alpha)) 100 | self.step = -1 101 | self.endPoints = self.endPointsH 102 | self.span = self.h 103 | return 104 | raise ValueError("Weird Python behavior at angle: " + str(alpha)) 105 | def testAt(self, image, off): 106 | crd = self.coords(off) 107 | if crd is None: 108 | return 0 109 | iter = cv.InitLineIterator(image, *crd) 110 | return sum(iter) 111 | def setCollisionPoint(self, image): 112 | for off in xrange(self.span): 113 | tst = self.testAt(image, off) 114 | if tst != 0: 115 | self.collisionPoint = off 116 | return tst 117 | return 0 118 | def rate(self, image): 119 | n = 8 120 | tests = [self.setCollisionPoint(image)] 121 | for y in xrange(self.collisionPoint + 1, self.collisionPoint + n): 122 | tests.append(self.testAt(image, y)) 123 | self.rating = sum(tests) 124 | return self.rating 125 | def rateAt(self, image, alpha): 126 | self.setAlpha(alpha) 127 | return self.rate(image) 128 | def approximate(self, image, alpha, range): 129 | angles = linspace(alpha - range, alpha + range, range + 1 + range) 130 | ratings = cap.amap(lambda alpha: self.rateAt(image, alpha), angles) 131 | return angles[ratings.argmax()] 132 | def draw(self, image): 133 | a, b = self.coords(self.collisionPoint) 134 | cv.Line(image, a, b, (0, 0, 192), 3, cv.CV_AA) 135 | 136 | def rotAngle(image): 137 | dark = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 138 | cv.Erode(image, dark, None, 2) 139 | cv.Threshold(dark, dark, 224, 255, cv.CV_THRESH_BINARY_INV) 140 | appr = approximator(cv.GetSize(dark)) 141 | alpha = appr.approximate(dark, 180.0, 10.0) 142 | appr.setAlpha(alpha) 143 | appr.setCollisionPoint(dark) 144 | forLog = cv.CreateImage(cv.GetSize(dark), cv.IPL_DEPTH_8U, 3) 145 | cv.CvtColor(dark, forLog, cv.CV_GRAY2BGR) 146 | appr.draw(forLog) 147 | return alpha + 180.0, forLog 148 | 149 | def clearNoise(image, tLetter=64, rBright=30): 150 | if tLetter <= 0: 151 | raise ValueError("tLetter = " + str(tLetter)) 152 | if rBright <= 0: 153 | raise ValueError("rBright = " + str(rBright)) 154 | def doThis(): 155 | result = cv.CloneImage(image) 156 | for x in xrange(result.width): 157 | for y in xrange(result.height): 158 | if result[y, x] == 0: 159 | continue 160 | if result[y, x] < tLetter: 161 | cv.FloodFill(result, (x, y), 0, rBright, rBright, 8, None) 162 | if result[0, 0] != image[0, 0] or \ 163 | result[result.height - 1, 0] != image[image.height - 1, 0] or \ 164 | result[0, result.width - 1] != image[0, image.width - 1] or \ 165 | result[result.height - 1, result.width - 1] != image[image.height - 1, image.width - 1]: 166 | return None 167 | return result 168 | result = doThis() 169 | while result is None: 170 | rBright -= 1 171 | result = doThis() 172 | cv.Threshold(result, result, 1, 255, cv.CV_THRESH_BINARY_INV) 173 | return result 174 | 175 | 176 | def preprocess(image, addr, extras): 177 | log = cap.logger(extras, image) 178 | alpha, dark = rotAngle(image) 179 | log.log(dark, False) 180 | clear = clearNoise(image) 181 | log.log(clear, False) 182 | straight = cap.doRotate(clear, -alpha, fillval=0, resize=False, interpolation=cv.CV_INTER_NN) 183 | #cv.Threshold(straight, straight, 128, 255, cv.CV_THRESH_BINARY) 184 | log.log(straight) 185 | cv.Dilate(straight, straight) 186 | cv.Erode(straight, straight) 187 | log.log(straight) 188 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_PREPROCESS) 189 | return straight -------------------------------------------------------------------------------- /green/recognise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cap 21 | from lconsts import ann_file, charset, segSize 22 | 23 | ann = cap.loadAnn(ann_file) 24 | 25 | def recognise(segments, addr, extras): 26 | return cap.defaultRecognise(segments, addr, extras, ann, segSize, charset, cap.resizeFit) -------------------------------------------------------------------------------- /green/segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from lconsts import segW, segH, nSegs 22 | 23 | def segment(image, addr, extras): 24 | clone = cv.CloneImage(image) 25 | log = cap.logger(extras, image) 26 | components = cap.findCCs(image, erasecol=0, doContinue=None, doSkip=lambda comp: comp[0] <= 25) 27 | log.log(cap.drawComponents(clone, components)) 28 | if len(components) != nSegs: 29 | components = cap.joinCCs(components, cap.rectsIntersectH) 30 | log.log(cap.drawComponents(clone, components)) 31 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_SEGMENT) 32 | assert(len(components) == nSegs) 33 | segments = map(lambda comp: comp[3], components) 34 | return segments -------------------------------------------------------------------------------- /green/train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv 21 | from pyfann import libfann 22 | from lconsts import segW, segH, num_input, num_output, charset, train_file, ann_file 23 | 24 | sys.path.append("..") 25 | 26 | from cap import resizeFit as adjustSize, segment_dir 27 | 28 | segments = os.listdir(segment_dir) 29 | 30 | f = open(train_file, "w") 31 | f.write("%d %d %d\n" % (len(segments), num_input, num_output)) 32 | 33 | 34 | for name in segments: 35 | image = cv.LoadImage(os.path.join(segment_dir, name), cv.CV_LOAD_IMAGE_GRAYSCALE) 36 | image = adjustSize(image, (segW, segH)) 37 | for y in range(image.height): 38 | for x in range(image.width): 39 | n = image[y, x] / 159.375 - 0.8 40 | f.write("%f " % n) 41 | f.write("\n") 42 | c = os.path.splitext(name)[0][0] 43 | n = charset.index(c) 44 | f.write("-1 " * n + "1" + " -1" * (num_output - n - 1) + "\n") 45 | 46 | f.close() 47 | 48 | print "Samples: %d" % len(segments) 49 | print "Input: %d" % num_input 50 | print "Output: %d" % num_output 51 | 52 | connection_rate = 1.0 53 | learning_rate = 0.3 54 | num_neurons_hidden = num_input / 3 55 | 56 | desired_error = 0.00001 57 | max_iterations = 10000 58 | iterations_between_reports = 20 59 | 60 | ann = libfann.neural_net() 61 | ann.create_sparse_array(connection_rate, (num_input, num_neurons_hidden, num_output)) 62 | ann.set_learning_rate(learning_rate) 63 | ann.set_activation_function_hidden(libfann.SIGMOID_SYMMETRIC_STEPWISE) 64 | ann.set_activation_function_output(libfann.SIGMOID_SYMMETRIC_STEPWISE) 65 | 66 | ann.train_on_file(train_file, max_iterations, iterations_between_reports, desired_error) 67 | 68 | ann.save(ann_file) -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap, os, sys, types, random 21 | from optparse import OptionParser, OptionValueError 22 | 23 | 24 | def makeParser(): 25 | """Create an instance of OptionParser and fill it with appropriate options.""" 26 | parser = OptionParser(prog="Captchure", version="%prog 0.1", usage="main.py {-d DIR|-f FILE} [options]") 27 | 28 | parser.add_option("-d", "--dir", "--directory", action="store", type="string", metavar="DIR", dest="directory", default="", \ 29 | help="Subdirectory of the module folder that contains images to process. These images are called 'the dataset'.") 30 | parser.add_option("-r", "--random", action="store_true", dest="random", default=False, \ 31 | help="A randomly selected image will be taken from the dataset. It can't be used together with --file.") 32 | parser.add_option("-f", "--file", action="store", type="string", metavar="FILE", dest="file", default="", \ 33 | help="Process a specific FILE given as a parameter to this option.\n It can't be used together with --random.") 34 | parser.add_option("-m", "--mode", action="store", type="choice", choices=["gs", "grayscale", "c", "color"], metavar="MODE", dest="mode", default="gs", \ 35 | help="The image loading mode. Can be either 'grayscale' ('gs') or 'color' ('c'). Default: grayscale.") 36 | parser.add_option("-s", "--save", action="append", type="choice", choices=["preprocessed", "segmented", "recognised", "p", "s", "r"], metavar="STAGE", dest="save", \ 37 | help="Specify stages where intermediate results are saved. Can be either 'preprocessed', 'segmented' or 'recognised'.") 38 | parser.add_option("-p", "--preprocess", action="append_const", const=cap.CAP_STAGE_PREPROCESS, dest="stages", \ 39 | help="Preprocess the dataset.") 40 | parser.add_option("-g", "--segment", action="append_const", const=cap.CAP_STAGE_SEGMENT, dest="stages", \ 41 | help="Segment the dataset.") 42 | parser.add_option("-c", "--recognise", action="append_const", const=cap.CAP_STAGE_RECOGNISE, dest="stages", \ 43 | help="Recognise the dataset.") 44 | parser.add_option("-e", "--extras", action="store", type="choice", choices=["save", "show", "off"], metavar="ACTION", dest="extras", \ 45 | help="Enable or disable generating of extra information, such as steps performed. Can be either 'off', 'show' or 'save'.") 46 | parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False, \ 47 | help="Disable showing images after each stage.") 48 | # Also, a recognition engine directory should be provided as an argument. 49 | return parser 50 | 51 | class optsort: 52 | """Post-processor of the result obtained by OptionParser.""" 53 | def setConsts(self): 54 | # Color mode 55 | self.grayscaleKeys = ["gs", "grayscale"] 56 | self.colorKeys = ["c", "color"] 57 | 58 | # Stages 59 | self.preprocessKeys = ["pre", "preprocess", "preprocessed"] 60 | self.segmentKeys = ["seg", "segment", "segmented"] 61 | self.recogniseKeys = ["rec", "recognise", "recognised"] 62 | 63 | # Extras 64 | self.extrasKeys = {"off": cap.CAP_EXTRAS_OFF, "show": cap.CAP_EXTRAS_SHOW, "save": cap.CAP_EXTRAS_SAVE} 65 | 66 | def __init__(self, (options, args)): 67 | # Check for trivial errors 68 | if options.random and options.file != "": 69 | raise OptionValueError("--random and --file are mutually exclusive") 70 | if args == [] or not os.path.exists(args[0]) or not os.path.isdir(args[0]): 71 | raise OptionValueError("A recognition engine directory must be provided as an argument") 72 | if options.directory == "" and options.file == "": 73 | raise OptionValueError("Some input files must be provided using the -d or -f keys.") 74 | 75 | # Set constants 76 | self.setConsts() 77 | 78 | # Set recognition engine 79 | self.engine = args[0] 80 | 81 | # Set required stages 82 | if options.stages is None: # default 83 | options.stages = [cap.CAP_STAGE_PREPROCESS, cap.CAP_STAGE_SEGMENT, cap.CAP_STAGE_RECOGNISE] 84 | self.preprocess = cap.CAP_STAGE_PREPROCESS in options.stages 85 | self.segment = cap.CAP_STAGE_SEGMENT in options.stages 86 | self.recognise = cap.CAP_STAGE_RECOGNISE in options.stages 87 | 88 | # Set color mode 89 | if options.mode in self.grayscaleKeys: self.mode = cv.CV_LOAD_IMAGE_GRAYSCALE 90 | elif options.mode in self.colorKeys: self.mode = cv.CV_LOAD_IMAGE_COLOR 91 | else: raise OptionValueError("Incorrect mode parameter.") 92 | 93 | # Set files to be processed 94 | if options.file != "": 95 | directory, names = os.path.split(options.file) 96 | self.directory = os.path.join(options.directory, directory) 97 | self.names = [names] 98 | self.total = 1 99 | self.single = True 100 | elif options.directory != "": 101 | self.directory = options.directory 102 | self.names = os.listdir(os.path.join(self.engine, self.directory)) 103 | if options.random: 104 | self.names = [self.names[random.randint(0, len(self.names) - 1)]] 105 | self.total = 1 106 | self.single = True 107 | else: 108 | self.total = len(self.names) 109 | self.single = False 110 | else: raise OptionValueError("Something weird is going on...") 111 | 112 | # Set saving options 113 | if options.save is None: 114 | options.save = [] 115 | self.savePreprocess = any([key in options.save for key in self.preprocessKeys]) 116 | self.saveSegment = any([key in options.save for key in self.segmentKeys]) 117 | self.saveRecognise = any([key in options.save for key in self.recogniseKeys]) 118 | 119 | # Set showing options 120 | self.show = self.single and not options.quiet 121 | self.autosize = 0 122 | 123 | # Set extras options 124 | if options.extras is not None: 125 | self.extras = self.extrasKeys[options.extras] 126 | else: 127 | if self.single: self.extras = cap.CAP_EXTRAS_SHOW 128 | else: self.extras = cap.CAP_EXTRAS_OFF 129 | 130 | class cReport: 131 | """Used within the mainLoop() function to collect stats.""" 132 | def __init__(self): 133 | self.loading = [] 134 | self.preprocessing = [] 135 | self.segmentation = [] 136 | self.recognition = [] 137 | self.saving = [] 138 | 139 | self.successes = 0 140 | self.mismatches = 0 141 | self.distances = [] 142 | def printNicely(self, lst, name): 143 | if lst == []: 144 | return 145 | print "%s (%d): " % (name, len(lst)) 146 | print "", 147 | if len(lst) <= 7: 148 | print "\n ".join(lst) 149 | else: 150 | print "\n ".join(lst[:3]) 151 | print " ..." 152 | print "", 153 | print "\n ".join(lst[-3:]) 154 | def printErrors(self): 155 | self.printNicely(self.loading, "Loading") 156 | self.printNicely(self.preprocessing, "Preprocessing") 157 | self.printNicely(self.segmentation, "Segmentation") 158 | self.printNicely(self.recognition, "Recognition") 159 | self.printNicely(self.saving, "Saving") 160 | def printRecStats(self, total): 161 | print "Total: %d" % (total) 162 | print "Successes: %d, %d%%" % (self.successes, 100 * self.successes / total) 163 | print "Mismatches: %d, %d%%" % (self.mismatches, 100 * self.mismatches / total) 164 | if self.mismatches + self.successes != 0: 165 | totaldist = float(sum(self.distances)) 166 | self.error = totaldist / (self.mismatches + self.successes) 167 | print "Average error: %f" % (self.error) 168 | if self.mismatches != 0: 169 | print "Average nonzero error: %f" % (totaldist / self.mismatches) 170 | 171 | def importModules(options): 172 | """Imports all modules specified in the first argument (and optsort instance) into the global namespace. 173 | The second argument is a directory which contains all of the modules being imported. 174 | Note: sys.path and cwd must be already set as appropriate!""" 175 | if options.preprocess: 176 | try: _temp = __import__("preprocess", fromlist=["preprocess"]) # from preprocess import preprocess 177 | except ImportError: 178 | print "Cannot import preprocessing module for '%s'" % (options.engine) 179 | raise 180 | global preprocess 181 | preprocess = _temp.preprocess 182 | if options.segment: 183 | try: _temp = __import__("segment", fromlist=["segment"]) # from segment import segment 184 | except ImportError: 185 | print "Cannot import segmentation module for '%s'" % (options.engine) 186 | raise 187 | global segment 188 | segment = _temp.segment 189 | if options.recognise: 190 | try: _temp = __import__("recognise", fromlist=["recognise"]) # from recognise import recognise 191 | except ImportError: 192 | print "Cannot import recognition module for '%s'" % (options.engine) 193 | raise 194 | global recognise 195 | recognise = _temp.recognise 196 | 197 | def findFilename(prefix, ext): 198 | """Inserts a numeric suffix between the given prefix and extension so that the resulting 199 | filename is guaranteed not to exist.""" 200 | j = 0 201 | while os.path.exists(prefix + str(j) + ext): j += 1 202 | return prefix + str(j) + ext 203 | 204 | def saveResult(result, directory, pre): 205 | """Saves the result of either preprocessing or segmentation into the given directory using 206 | the given prefix and the default extension (defext in cap.consts). The exact method of saving is 207 | determined by the type of the result - it can be either a list or an iplimage.""" 208 | t = type(result) 209 | if t is types.ListType or t is types.TupleType: 210 | for index, image in enumerate(result): 211 | c = pre[len(pre) - 1] if index >= len(pre) else pre[index] 212 | prefix = os.path.join(directory, c + "_" + pre + "_") 213 | newname = findFilename(prefix, cap.defext) 214 | cv.SaveImage(newname, image) 215 | elif t is cv.iplimage: 216 | cv.SaveImage(os.path.join(directory, pre + cap.defext), result) 217 | else: raise TypeError("Incorrect result type: %s" % (str(t))) 218 | 219 | def showResult(result, stage, wait, autosize): 220 | """Shows the result of either preprocessing or segmentation using the OpenCV's HighGUI module. 221 | The method of showing is determined by the type of the result - it can be either a list or an 222 | iplimage. The parameters let you control the title of the window(s) the result will be shown in, 223 | whether cv.WaitKey(0) should be called or not and whether the window should be autosized.""" 224 | title = cap.getTitle(stage) 225 | t = type(result) 226 | if t is types.ListType or t is types.TupleType: 227 | for index, image in enumerate(result): 228 | cv.NamedWindow(title + str(index), autosize) 229 | cv.ShowImage(title + str(index), image) 230 | elif t is cv.iplimage: 231 | cv.NamedWindow(title, autosize) 232 | cv.ShowImage(title, result) 233 | else: raise TypeError("Incorrect result type: %s" % (str(t))) 234 | if wait: cv.WaitKey(0) 235 | 236 | def levenshtein_distance(first, second): 237 | """Find the Levenshtein distance between two strings.""" 238 | if len(first) > len(second): 239 | first, second = second, first 240 | if len(second) == 0: 241 | return len(first) 242 | first_length = len(first) + 1 243 | second_length = len(second) + 1 244 | distance_matrix = [[0] * second_length for x in range(first_length)] 245 | for i in range(first_length): 246 | distance_matrix[i][0] = i 247 | for j in range(second_length): 248 | distance_matrix[0][j]=j 249 | for i in xrange(1, first_length): 250 | for j in range(1, second_length): 251 | deletion = distance_matrix[i-1][j] + 1 252 | insertion = distance_matrix[i][j-1] + 1 253 | substitution = distance_matrix[i-1][j-1] 254 | if first[i-1] != second[j-1]: 255 | substitution += 1 256 | distance_matrix[i][j] = min(insertion, deletion, substitution) 257 | return distance_matrix[first_length-1][second_length-1] 258 | 259 | def mainLoop(options): 260 | """The Most Important Function Which Does Everything.""" 261 | rep = cReport() 262 | for index, name in enumerate(options.names): 263 | pre = os.path.splitext(name)[0] 264 | addr = os.path.join(options.directory, name) 265 | if not options.single: 266 | print "%d/%d:" % (index + 1, options.total), 267 | print "%s ->" % (name), 268 | # Loading 269 | try: 270 | raw_image = cv.LoadImage(addr, options.mode) 271 | except KeyboardInterrupt: 272 | print "Interrupted by user." 273 | sys.exit(0) 274 | except: 275 | print "FAILED TO LOAD" 276 | rep.loading.append(name) 277 | if options.single: raise 278 | else: continue 279 | if options.show: 280 | cv.NamedWindow("Raw", options.autosize) 281 | cv.ShowImage("Raw", raw_image) 282 | if options.preprocess: 283 | # Preprocessing 284 | thisIsLastStage = (not options.segment) and (not options.recognise) 285 | try: 286 | preprocessed = preprocess(cv.CloneImage(raw_image), addr, options.extras) 287 | except KeyboardInterrupt: 288 | print "Interrupted by user." 289 | sys.exit(0) 290 | except: 291 | print "FAILED TO PREPROCESS" 292 | rep.preprocessing.append(name) 293 | if options.single: 294 | cv.WaitKey(0) 295 | raise 296 | else: continue 297 | if options.show: 298 | showResult(preprocessed, cap.CAP_STAGE_PREPROCESS, thisIsLastStage, options.autosize) 299 | if options.savePreprocess: 300 | # Saving preprocessed 301 | try: 302 | saveResult(preprocessed, cap.preprocess_dir, pre) 303 | except KeyboardInterrupt: 304 | print "Interrupted by user." 305 | sys.exit(0) 306 | except: 307 | print "FAILED TO SAVE PREPROCESSED" 308 | rep.saving.append(name) 309 | if options.single: raise 310 | else: continue 311 | if thisIsLastStage: 312 | print "ok" 313 | #if single and options.quiet and extras == "show": cv.WaitKey(0) 314 | else: 315 | preprocessed = raw_image 316 | if options.segment: 317 | # Segmenting 318 | thisIsLastStage = not options.recognise 319 | try: 320 | segmented = segment(preprocessed, addr, options.extras) 321 | except KeyboardInterrupt: 322 | print "Interrupted by user." 323 | sys.exit(0) 324 | except: 325 | print "FAILED TO SEGMENT" 326 | rep.segmentation.append(name) 327 | if options.single: 328 | cv.WaitKey(0) 329 | raise 330 | else: continue 331 | if options.show: 332 | showResult(segmented, cap.CAP_STAGE_SEGMENT, thisIsLastStage, options.autosize) 333 | #if extras == "show" and thisIsLastStage: cv.WaitKey(0) 334 | if options.saveSegment: 335 | # Saving segmented 336 | try: 337 | saveResult(segmented, cap.segment_dir, pre) 338 | except KeyboardInterrupt: 339 | print "Interrupted by user." 340 | sys.exit(0) 341 | except: 342 | print "FAILED TO SAVE SEGMENTED" 343 | rep.saving.append(name) 344 | if options.single: raise 345 | else: continue 346 | if thisIsLastStage: print "ok" 347 | else: 348 | segmented = [preprocessed] 349 | if options.recognise: 350 | # Recognising 351 | try: 352 | recognised = recognise(segmented, addr, options.extras) 353 | except KeyboardInterrupt: 354 | print "Interrupted by user." 355 | sys.exit(0) 356 | except: 357 | print "FAILED TO RECOGNISE" 358 | rep.recognition.append(name) 359 | if options.single: 360 | cv.WaitKey(0) 361 | raise 362 | else: continue 363 | if recognised == pre: 364 | rep.successes += 1 365 | else: 366 | dist = levenshtein_distance(pre, recognised) 367 | rep.distances.append(dist) 368 | rep.mismatches += 1 369 | print recognised, 370 | if options.saveRecognise: 371 | # Saving recognised 372 | try: 373 | newname = recognised + "_" + pre 374 | subdir = cap.success_dir if recognised == pre else cap.mismatch_dir 375 | saveResult(raw_image, os.path.join(cap.recognise_dir, subdir), pre) 376 | except KeyboardInterrupt: 377 | print "Interrupted by user." 378 | sys.exit(0) 379 | except: 380 | print "FAILED TO SAVE RECOGNISED" 381 | rep.saving.append(name) 382 | if options.single: raise 383 | else: continue 384 | print "ok" if pre == recognised else ("MISMATCH (%d)" % dist) 385 | if options.single: 386 | cv.WaitKey(0) 387 | return rep 388 | 389 | def main(args): 390 | """Accepts a list of command-line parameters except the first one and calls 391 | all internal functions as needed.""" 392 | parser = makeParser() 393 | options = optsort(parser.parse_args(args)) 394 | rootDir = os.getcwd() 395 | engineDir = os.path.join(rootDir, options.engine) 396 | sys.path.append(engineDir) 397 | os.chdir(engineDir) 398 | importModules(options) 399 | report = mainLoop(options) 400 | if not options.single: 401 | print "Done." 402 | report.printErrors() 403 | if options.recognise: 404 | report.printRecStats(options.total) 405 | os.chdir(rootDir) 406 | if __name__ != "__main__" and report.successes + report.mismatches != 0: 407 | return report.error 408 | 409 | if __name__ == "__main__": 410 | main(sys.argv[1:]) -------------------------------------------------------------------------------- /red/lconsts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | imgW = 83 21 | imgH = 23 22 | 23 | factor = 2 24 | 25 | rimgW = imgW * factor 26 | rimgH = imgH * factor 27 | 28 | nSegs = 5 29 | 30 | segW = 18 31 | segH = 18 32 | segSize = (segW, segH) 33 | 34 | num_input = segW * segH 35 | num_output = 30 36 | 37 | charset = "2345689abcdefghjkmnpqrstuvwxyz" 38 | 39 | ann_file = "ann.net" 40 | train_file = "ann.train" -------------------------------------------------------------------------------- /red/preprocess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from math import cos, pi 22 | from lconsts import factor, rimgW, rimgH 23 | 24 | mapX = cv.CreateImage((rimgW, rimgH), cv.IPL_DEPTH_32F, 1) 25 | for y in xrange(mapX.height): 26 | for x in xrange(mapX.width): 27 | mapX[y, x] = x 28 | 29 | t = 4.0 # top offset 30 | scale1 = 2.3 31 | step1 = 27.0 32 | h = 16.0 # character height 33 | stretch = rimgW * 10.0 34 | 35 | ft = t * factor 36 | fscale1 = scale1 * factor 37 | fh = h * factor 38 | fstep1 = pi / (step1 * factor) 39 | 40 | mapY = cv.CreateImage((rimgW, rimgH), cv.IPL_DEPTH_32F, 1) 41 | for y in xrange(mapY.height): 42 | for x in xrange(mapY.width): 43 | q = fscale1 * (1 + cos(fstep1 * x)) 44 | mapY[y, x] = ((y - ft) * ((fh - q) / fh) + q) * (1 + x / stretch) + ft 45 | 46 | #cv.SaveImage("_mapy.png", mapY) 47 | 48 | def undistort(image): 49 | result = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 50 | cv.Remap(image, result, mapX, mapY, cv.CV_INTER_CUBIC + cv.CV_WARP_FILL_OUTLIERS, cv.ScalarAll(0)) 51 | return result 52 | 53 | """ 54 | test = cv.CreateImage((rimgW, rimgH), cv.IPL_DEPTH_8U, 1) 55 | cv.Zero(test) 56 | for y in (i for i in xrange(test.height) if i % 4 < 2): 57 | row = cv.GetRow(test, y) 58 | cv.Set(row, 255) 59 | cv.SaveImage("_test_original.png", test) 60 | cv.SaveImage("_test_modified.png", undistort(test)) 61 | #""" 62 | 63 | 64 | def preprocess(image, addr, extras): 65 | log = cap.logger(extras, image) 66 | image = cap.doResize(image, factor, cv.CV_INTER_CUBIC) 67 | log.log(image) 68 | image = undistort(image) 69 | log.log(image) 70 | cv.Threshold(image, image, 200, 255, cv.CV_THRESH_BINARY) 71 | log.log(image) 72 | image = cap.repaintCCs(image, doRepaint=lambda comp, col: comp[0] <= 10 and col <= 128) 73 | log.log(image) 74 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_PREPROCESS) 75 | return image -------------------------------------------------------------------------------- /red/recognise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cap 21 | from lconsts import ann_file, charset, segSize 22 | 23 | ann = cap.loadAnn(ann_file) 24 | 25 | def recognise(segments, addr, extras): 26 | return cap.defaultRecognise(segments, addr, extras, ann, segSize, charset, cap.resizeFit) -------------------------------------------------------------------------------- /red/segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from operator import attrgetter 22 | from lconsts import nSegs 23 | 24 | 25 | def segment(image, addr, extras): 26 | log = cap.logger(extras, image) 27 | clone = cv.CloneImage(image) 28 | components = cap.findCCs(image, 0, lambda col: col <= 128, lambda comp: comp[0] < 10) 29 | log.log(cap.drawComponents(clone, components), False) 30 | components = cap.joinCCs(components, cap.rectsIntersectH) 31 | log.log(cap.drawComponents(clone, components), False) 32 | assert(len(components) <= nSegs) 33 | parts = cap.partsFromnSegs5(components) 34 | components = cap.spltCCs(components, parts, projRadius=4, thresh=1) 35 | log.log(cap.drawComponents(clone, components), False) 36 | segments = map(lambda comp: comp[3], components) 37 | log.log(cap.joinImagesH(segments), False) 38 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_SEGMENT) 39 | return segments -------------------------------------------------------------------------------- /red/train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys 21 | from pyfann import libfann 22 | from lconsts import segW, segH, num_input, num_output, charset, train_file, ann_file 23 | 24 | sys.path.append("..") 25 | 26 | from cap import resizeFit as adjustSize, segment_dir 27 | 28 | segments = os.listdir(segment_dir) 29 | 30 | f = open(train_file, "w") 31 | f.write("%d %d %d\n" % (len(segments), num_input, num_output)) 32 | 33 | 34 | for name in segments: 35 | image = cv.LoadImage(os.path.join(segment_dir, name), cv.CV_LOAD_IMAGE_GRAYSCALE) 36 | image = adjustSize(image, (segW, segH)) 37 | for y in range(image.height): 38 | for x in range(image.width): 39 | n = image[y, x] / 159.375 - 0.8 40 | f.write("%f " % n) 41 | f.write("\n") 42 | c = os.path.splitext(name)[0][0] 43 | n = charset.index(c) 44 | f.write("-1 " * n + "1" + " -1" * (num_output - n - 1) + "\n") 45 | 46 | f.close() 47 | 48 | print "Samples: %d" % len(segments) 49 | print "Input: %d" % num_input 50 | print "Output: %d" % num_output 51 | 52 | connection_rate = 1.0 53 | learning_rate = 0.3 54 | num_neurons_hidden = num_input / 3 55 | 56 | desired_error = 0.00001 57 | max_iterations = 10000 58 | iterations_between_reports = 20 59 | 60 | ann = libfann.neural_net() 61 | ann.create_sparse_array(connection_rate, (num_input, num_neurons_hidden, num_output)) 62 | ann.set_learning_rate(learning_rate) 63 | ann.set_activation_function_hidden(libfann.SIGMOID_SYMMETRIC_STEPWISE) 64 | ann.set_activation_function_output(libfann.SIGMOID_SYMMETRIC_STEPWISE) 65 | 66 | ann.train_on_file(train_file, max_iterations, iterations_between_reports, desired_error) 67 | 68 | ann.save(ann_file) -------------------------------------------------------------------------------- /yellow/create_valid_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys 21 | from pyfann import libfann 22 | from lconsts import segW, segH, num_input, num_output, charset, test_file 23 | 24 | sys.path.append("..") 25 | 26 | from cap import resizeFit as adjustSize 27 | 28 | segment_dir = "segments_validset" 29 | segments = os.listdir(segment_dir) 30 | 31 | f = open(test_file, "w") 32 | f.write("%d %d %d\n" % (len(segments), num_input, num_output)) 33 | 34 | 35 | for name in segments: 36 | image = cv.LoadImage(os.path.join(segment_dir, name), cv.CV_LOAD_IMAGE_GRAYSCALE) 37 | image = adjustSize(image, (segW, segH)) 38 | for y in range(image.height): 39 | for x in range(image.width): 40 | n = image[y, x] / 159.375 - 0.8 41 | f.write("%f " % n) 42 | f.write("\n") 43 | c = os.path.splitext(name)[0][0] 44 | n = charset.index(c) 45 | f.write("-1 " * n + "1" + " -1" * (num_output - n - 1) + "\n") 46 | 47 | f.close() 48 | 49 | print "Samples: %d" % len(segments) 50 | print "Input: %d" % num_input 51 | print "Output: %d" % num_output -------------------------------------------------------------------------------- /yellow/lconsts.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | mygray = 153 21 | myblue = 102 22 | mylgrn = 51 23 | mydgrn = 1 24 | myunkn = 128 25 | 26 | mycolors = (mygray, myblue, mylgrn, mydgrn) 27 | 28 | nSegs = 5 29 | 30 | charset = "#123456789abcdefhkmoprt" 31 | 32 | segW = 30 33 | segH = 30 34 | segSize = (segW, segH) 35 | 36 | num_input = segW * segH 37 | num_output = len(charset) 38 | 39 | ann_dir = "anns" 40 | train_file = "ann.train" 41 | ann_file = "ann.net" 42 | test_file = "ann.test" -------------------------------------------------------------------------------- /yellow/preprocess.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import cv, cap 21 | from lconsts import mycolors, mygray, myblue, mylgrn, mydgrn, myunkn 22 | 23 | 24 | # BGR 25 | grays = ((153, 153, 153), (153, 102, 153), (102, 102, 153), (102, 102, 102)) 26 | blues = ((153, 51, 51), (102, 51, 51), (102, 51, 0), (102, 0, 0)) 27 | lgrns = ((102, 102, 51), (102, 153, 51), (51, 102, 51), (51, 102, 0)) 28 | dgrns = ((51, 51, 51), (0, 51, 0), (0, 0, 0)) 29 | white3 = (255, 255, 255) 30 | 31 | white = 255 32 | black = 0 33 | 34 | 35 | def doCopyMakeBorder(image, border, fillval): 36 | result = cv.CreateImage((image.width + border * 2, image.height + border * 2), image.depth, image.nChannels) 37 | cv.CopyMakeBorder(image, result, (border, border), 0, fillval) 38 | return result 39 | 40 | def removeLightColors(image): 41 | b = cv.CreateImage(cv.GetSize(image), image.depth, 1) 42 | g = cv.CreateImage(cv.GetSize(image), image.depth, 1) 43 | r = cv.CreateImage(cv.GetSize(image), image.depth, 1) 44 | cv.Split(image, b, g, r, None) 45 | cv.Threshold(b, b, 154, 255, cv.CV_THRESH_BINARY) 46 | cv.Threshold(g, g, 154, 255, cv.CV_THRESH_BINARY) 47 | cv.Threshold(r, r, 154, 255, cv.CV_THRESH_BINARY) 48 | cv.Or(b, g, b) 49 | cv.Or(b, r, b) 50 | cv.Set(image, cv.ScalarAll(255), b) 51 | return image 52 | 53 | def remapColors(image): 54 | result = cv.CreateImage(cv.GetSize(image), image.depth, 1) 55 | for x in xrange(image.width): 56 | for y in xrange(image.height): 57 | col = image[y, x] 58 | if col in grays: result[y, x] = mygray 59 | elif col in blues: result[y, x] = myblue 60 | elif col in lgrns: result[y, x] = mylgrn 61 | elif col in dgrns: result[y, x] = mydgrn 62 | elif col == white3:result[y, x] = white 63 | else: result[y, x] = myunkn 64 | return result 65 | 66 | def findColor(image, color): 67 | result = cv.CreateImage(cv.GetSize(image), image.depth, 1) 68 | cv.CmpS(image, color, result, cv.CV_CMP_EQ) 69 | return result 70 | 71 | def smoothNoise2(image): 72 | b = 2 73 | temp = cv.CreateImage((image.width + 4, image.height + 4), image.depth, image.nChannels) 74 | result = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 75 | # IPL_BORDER_CONSTANT = 0 76 | # IPL_BORDER_REPLICATE = 1 77 | cv.CopyMakeBorder(image, temp, (b, b), 0, 255) 78 | for x in xrange(b, image.width + b): 79 | for y in xrange(b, image.height + b): 80 | if temp[y + 1, x] == temp[y - 1, x] and \ 81 | temp[y + 2, x] == temp[y - 2, x] and \ 82 | temp[y + 1, x] == temp[y + 2, x] and \ 83 | temp[y, x] != temp[y + 1, x]: 84 | result[y - b, x - b] = temp[y + 1, x] 85 | elif temp[y, x + 1] == temp[y, x - 1] and \ 86 | temp[y, x + 2] == temp[y, x - 2] and \ 87 | temp[y, x + 1] == temp[y, x + 2] and \ 88 | temp[y, x] != temp[y, x + 1]: 89 | result[y - b, x - b] = temp[y, x + 1] 90 | else: 91 | result[y - b, x - b] = temp[y, x] 92 | return result 93 | 94 | def getNoiseMask(image, size, connectivity=8): 95 | mask = cv.CloneImage(image) 96 | for x in xrange(mask.width): 97 | for y in range(mask.height): 98 | col = mask[y, x] 99 | if col == black or col == white or col == 254: 100 | continue 101 | comp = cv.FloodFill(mask, (x, y), black, 0, 0, connectivity, None) 102 | if comp[0] > size: 103 | cv.FloodFill(mask, (x, y), 254, 0, 0, connectivity, None) 104 | cv.Threshold(mask, mask, 253, 255, cv.CV_THRESH_BINARY_INV) 105 | return mask 106 | 107 | def doInpaint(image, mask): 108 | radius = 2 109 | result = doCopyMakeBorder(image, radius, 255) 110 | temp = doCopyMakeBorder(mask, radius, 0) 111 | cv.Inpaint(result, temp, result, radius, cv.CV_INPAINT_NS) 112 | result = cap.getSubImage(result, (radius, radius, image.width, image.height)) 113 | return result 114 | 115 | def makeLUT(): 116 | lut = cv.CreateMat(1, 256, cv.CV_8UC1) 117 | colors = mycolors + (white, ) 118 | for i in xrange(256): 119 | lut[0, i] = colors[cap.argmin(map(lambda col: abs(i - col), colors))] 120 | return lut 121 | 122 | lut = makeLUT() 123 | 124 | def sharpenColors(image): 125 | cv.LUT(image, image, lut) 126 | return image 127 | 128 | 129 | def preprocess(image, addr, extras): 130 | log = cap.logger(extras, image) 131 | image = removeLightColors(image) 132 | log.log(image) 133 | image = remapColors(image) 134 | log.log(image) 135 | image = smoothNoise2(image) 136 | log.log(image) 137 | image = cap.smoothNoise1(image) 138 | log.log(image) 139 | mask = getNoiseMask(image, 15, 4) 140 | cv.Or(mask, findColor(image, myunkn), mask) 141 | log.log(mask) 142 | image = doInpaint(image, mask) 143 | log.log(image) 144 | image = sharpenColors(image) 145 | log.log(image) 146 | image = cap.repaintCCs(image, doRepaint=lambda comp, col: comp[0] <= 5 or comp[2][2] <= 2 or comp[2][3] <= 2) 147 | log.log(image) 148 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_PREPROCESS) 149 | return image -------------------------------------------------------------------------------- /yellow/recognise.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, cap 21 | from operator import itemgetter 22 | from numpy import linspace 23 | from lconsts import ann_dir, ann_file, charset, segSize 24 | from cap import resizeFit as adjustSize 25 | 26 | ann = cap.loadAnn(ann_file) 27 | 28 | def recogniseOne(seg): 29 | resized = adjustSize(seg, segSize) 30 | array = cap.flattenImage(resized) 31 | guesses = ann.run(array) 32 | ichar = cap.argmax(guesses) 33 | guess = guesses[ichar] 34 | return (guess, ichar) 35 | 36 | def findRect(image, left, right): 37 | cols = cv.GetCols(image, left, right) 38 | top = cap.getBound(cols, cap.CAP_BOUND_TOP, colthresh=128) 39 | bottom = cap.getBound(cols, cap.CAP_BOUND_BOTTOM, colthresh=128) 40 | return (left, top, right - left, bottom - top) 41 | 42 | def splitRecogniseOne(image, parts, shiftRadius): 43 | result = "" 44 | splitters = linspace(0, image.width - 1, parts + 1).astype(int) 45 | for index in xrange(parts - 1, 0, -1): 46 | splitter = splitters[index] 47 | results = [] 48 | for x in xrange(splitter - shiftRadius, splitter + shiftRadius + 1): 49 | rect = findRect(image, x, splitters[index + 1]) 50 | seg = cap.getSubImage(image, rect) 51 | guess, ichar = recogniseOne(seg) 52 | results.append((guess, ichar, x, rect)) 53 | best = max(results, key=itemgetter(0)) 54 | #print best[0] 55 | splitters[index] = best[2] 56 | result += charset[best[1]] 57 | firstSeg = cap.getSubImage(image, findRect(image, 0, splitters[1])) 58 | guess, ichar = recogniseOne(firstSeg) 59 | #print guess 60 | result += charset[ichar] 61 | for s in splitters[1:-1]: 62 | cv.Line(image, (s, 0), (s, image.height - 1), 128, 1) 63 | return result[::-1] 64 | 65 | def splitRecogniseAll(segments, allParts, shiftRadius): 66 | result = "" 67 | for index, parts in enumerate(allParts): 68 | assert(parts >= 1) 69 | seg = segments[index] 70 | if parts > 1: result += splitRecogniseOne(seg, parts, shiftRadius) 71 | else: 72 | guess, ichar = recogniseOne(seg) 73 | #print guess 74 | result += charset[ichar] 75 | return result 76 | 77 | def recognise(segments, addr, extras): 78 | allParts = cap.partsFromnSegs5(segments) 79 | result = splitRecogniseAll(segments, allParts, shiftRadius=4) 80 | cap.processExtras([cap.joinImagesH(segments)], addr, extras, cap.CAP_STAGE_RECOGNISE) 81 | return result -------------------------------------------------------------------------------- /yellow/segment.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | from __future__ import division 21 | import cv, cap 22 | from math import radians as rad, sqrt, sin, cos, tan, asin, fsum 23 | from itertools import chain 24 | from lconsts import nSegs, mygray, myblue, mylgrn, mydgrn 25 | 26 | def dist2D((x1, y1), (x2, y2)): 27 | return sqrt((x1 - x2)**2 + (y1 - y2)**2) 28 | 29 | def dist3D((x1, y1, z1), (x2, y2, z2)): 30 | return sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2) 31 | 32 | def distND(v1, v2): 33 | return sum([(c1 - c2)**2 for c1, c2 in zip(v1, v2)]) 34 | 35 | class piston: 36 | def __init__(self, (w, h)): 37 | # For now, include only support for rho=w//2, theta=0 38 | self.w = w 39 | self.h = h 40 | self.rho = w // 2 41 | self.theta = 0 42 | self.pos = float(-(h - 1)) 43 | self.step = 0.05 44 | self.span = h - 1 45 | self.steps = int(self.span / self.step) 46 | self.setAlpha(0.0) 47 | def setAlpha(self, alpha): 48 | self.alpha = alpha 49 | self.ralpha = rad(alpha) 50 | def endPoints(self): 51 | off = self.rho * tan(self.ralpha) 52 | pt1 = (0, -self.pos + off) 53 | pt2 = (self.w - 1, -self.pos - off) 54 | return (pt1, pt2) 55 | def coords(self, image): 56 | original = self.endPoints() 57 | (x1, y1), (x2, y2) = original 58 | try: 59 | clipped = cv.ClipLine((self.w, self.h), (int(x1), int(y1)), (int(x2), int(y2))) 60 | except: 61 | print self.alpha, self.pos 62 | raise 63 | if clipped is None: 64 | return None 65 | (x1c, y1c), (x2c, y2c) = clipped 66 | iter = cv.InitLineIterator(image, *clipped) 67 | clip = tuple(iter) 68 | cliplenpts = len(clip) 69 | cliplen = dist2D(*clipped) 70 | origlen = dist2D(*original) 71 | clipoff = dist2D((x1, y1), (x1c, y1c)) 72 | origpist = origlen / 2.0 73 | clippist = origpist - clipoff 74 | clippistpt = (cliplenpts * clippist) / cliplen 75 | return (int(clippistpt), clip) 76 | def atan(self, dy, dx): 77 | result = cv.FastArctan(dy, dx) 78 | if result >= 180.0: 79 | result -= 180.0 80 | if result >= 90.0: 81 | result -= 180.0 82 | return result 83 | def push(self, image): 84 | crd = self.coords(image) 85 | if crd is None: 86 | self.pos += step 87 | return True 88 | pistpt, line = crd 89 | if line[pistpt] > 0: return False 90 | left, right = 0, 0 91 | for x in xrange(pistpt - 1, -1, -1): 92 | if line[x] > 0: 93 | left = pistpt - x 94 | break 95 | for x in xrange(pistpt + 1, len(line), 1): 96 | if line[x] > 0: 97 | right = x - pistpt 98 | break 99 | if left == 0 and right == 0: 100 | self.pos += self.step 101 | return True 102 | if left != 0 and right != 0: 103 | return False 104 | if self.alpha > 0.0: 105 | alpha = self.ralpha 106 | if left != 0: 107 | dx = left * cos(alpha) 108 | dy = left * sin(alpha) + self.step 109 | newAlpha = self.atan(dy, dx) 110 | else: # right != 0 111 | dx = right * cos(alpha) 112 | dy = right * sin(alpha) - self.step 113 | newAlpha = self.atan(dy, dx) 114 | elif self.alpha < 0.0: 115 | alpha = -self.ralpha 116 | if left != 0: 117 | dx = left * cos(alpha) 118 | dy = left * sin(alpha) - self.step 119 | newAlpha = -self.atan(dy, dx) 120 | else: # right != 0 121 | dx = right * cos(alpha) 122 | dy = right * sin(alpha) + self.step 123 | newAlpha = -self.atan(dy, dx) 124 | else: # self.alpha == 0.0 125 | if left != 0: 126 | newAlpha = asin(self.step / left) 127 | else: # right != 0 128 | newAlpha = -asin(self.step / right) 129 | self.setAlpha(newAlpha) 130 | self.pos += self.step 131 | return True 132 | def approximate(self, image): 133 | resized = cap.doResize(image, 2, cv.CV_INTER_NN) 134 | self.__init__(cv.GetSize(resized)) 135 | for x in xrange(self.steps): 136 | if not self.push(resized): break 137 | forLog = cv.CreateImage(cv.GetSize(resized), cv.IPL_DEPTH_8U, 3) 138 | cv.CvtColor(resized, forLog, cv.CV_GRAY2BGR) 139 | self.draw(forLog) 140 | return self.alpha, forLog 141 | def draw(self, image): 142 | (x1, y1), (x2, y2) = self.endPoints() 143 | try: clipped = cv.ClipLine((self.w, self.h), (int(x1), int(y1)), (int(x2), int(y2))) 144 | except: 145 | print self.alpha, self.pos 146 | raise 147 | if clipped is None: 148 | return 149 | pt1, pt2 = clipped 150 | cv.Line(image, pt1, pt2, (0, 0, 192), 2, cv.CV_AA) 151 | 152 | def split(image): 153 | ch1 = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 154 | ch2 = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 155 | ch3 = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 156 | ch4 = cv.CreateImage(cv.GetSize(image), image.depth, image.nChannels) 157 | cv.CmpS(image, mygray, ch1, cv.CV_CMP_EQ) 158 | cv.CmpS(image, myblue, ch2, cv.CV_CMP_EQ) 159 | cv.CmpS(image, mylgrn, ch3, cv.CV_CMP_EQ) 160 | cv.CmpS(image, mydgrn, ch4, cv.CV_CMP_EQ) 161 | return (ch1, ch2, ch3, ch4) 162 | 163 | def filtCCs(components, (minW, minH), minRectArea, minDensity): 164 | sizefilter = lambda comp: comp[2][2] >= minW and comp[2][3] >= minH 165 | def areafilter(comp): 166 | w, h = cap.minAreaRectImage(comp[3], returnPoints=False)[1] 167 | return w * h >= minRectArea 168 | densityfilter = lambda comp: comp[0] / (comp[2][2] * comp[2][3]) >= minDensity 169 | myfilter = lambda comp: sizefilter(comp) and areafilter(comp) and densityfilter(comp) 170 | components = filter(myfilter, components) 171 | return components 172 | 173 | def segmentChannel(ch, log=None): 174 | clone = cv.CloneImage(ch) 175 | components = cap.findCCs(ch, erasecol=0) 176 | joiner = lambda rect1, rect2: (cap.rectsIntersectH(rect1, rect2) and cap.distV(rect1, rect2) <= 6) or \ 177 | (rect1[2] <= 10 and rect2[2] <= 10 and cap.distH(rect1, rect2) <= 6) or \ 178 | ((rect1[2] <= 6 or rect2[2] <= 6) and cap.distH(rect1, rect2) <= 6) 179 | components = cap.joinCCs(components, joiner) 180 | components = filtCCs(components, (15, 15), 200, 0.2) 181 | if log is not None: 182 | log.log(cap.drawComponents(clone, components)) 183 | return components 184 | 185 | def reorder(components): 186 | return sorted(chain(*components), key=lambda comp: comp[2][0]) 187 | 188 | def addBackground(comp, image, bgcolor=96): 189 | seg = comp[3] 190 | rect = comp[2] 191 | original = cap.getSubImage(image, rect) 192 | for x in xrange(original.width): 193 | for y in xrange(original.height): 194 | if original[y, x] != 255 and seg[y, x] != 255: 195 | seg[y, x] = bgcolor 196 | return comp 197 | 198 | def findComponents(image, log=None): 199 | channels = split(image) 200 | components = map(lambda ch: segmentChannel(ch, log), channels) 201 | components = reorder(components) 202 | return components 203 | 204 | def findAngle(comp, log): 205 | seg = comp[3] 206 | pist = piston(cv.GetSize(seg)) 207 | angle, forLog = pist.approximate(seg) 208 | #log.log(forLog) 209 | return angle 210 | 211 | def removeBadBackground(seg): 212 | threshUp = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) 213 | comparison = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) 214 | visitMask = cv.CreateImage(cv.GetSize(seg), cv.IPL_DEPTH_8U, 1) 215 | ffMask = cv.CreateImage((seg.width + 2, seg.height + 2), cv.IPL_DEPTH_8U, 1) 216 | cv.Threshold(seg, threshUp, 1, 255, cv.CV_THRESH_BINARY) 217 | cv.Zero(visitMask) 218 | cv.Zero(ffMask) 219 | for x in xrange(seg.width): 220 | for y in xrange(seg.height): 221 | if seg[y, x] != 96 or visitMask[y, x] == 255: continue 222 | comp = cv.FloodFill(threshUp, (x, y), 0, 0, 0, 4 + cv.CV_FLOODFILL_MASK_ONLY + (255 << 8), ffMask) 223 | rect = comp[2] 224 | cv.SetImageROI(ffMask, cap.shiftRect(rect, 1, 1)) 225 | cv.OrS(ffMask, 1, ffMask) 226 | cv.SetImageROI(seg, rect) 227 | cv.SetImageROI(comparison, rect) 228 | cv.Cmp(seg, ffMask, comparison, cv.CV_CMP_EQ) # 'comparison' does not need to be zeroed later 229 | intersect = cv.CountNonZero(comparison) 230 | cv.SetImageROI(visitMask, rect) 231 | cv.Or(visitMask, ffMask, visitMask) 232 | cv.ResetImageROI(visitMask) 233 | if intersect == 0: 234 | cv.Set(seg, 0, ffMask) 235 | cv.Zero(ffMask) 236 | cv.ResetImageROI(seg) 237 | cv.ResetImageROI(ffMask) 238 | return seg 239 | 240 | 241 | def segment(image, addr, extras): 242 | log = cap.logger(extras, image) 243 | components = findComponents(image, log) 244 | log.log(cap.drawComponents(image, components)) 245 | angles = map(lambda comp: findAngle(comp, log), components) 246 | angles = filter(lambda angle: angle != 0.0 and abs(angle) <= 27.0, angles) 247 | if len(angles) != 0: 248 | angle = fsum(angles) / len(angles) 249 | image = cap.doRotate(image, -angle, fillval=255, interpolation=cv.CV_INTER_NN) 250 | log.log(image) 251 | components = findComponents(image) 252 | assert(len(components) <= nSegs) 253 | log.log(cap.drawComponents(image, components)) 254 | #components = cap.spltCCs(components, cap.partsFromnSegs5(components), projRadius=5, thresh=2) 255 | #components = filtCCs(components, (15, 15), 200, 0.2) 256 | components = map(lambda comp: addBackground(comp, image, bgcolor=96), components) 257 | segments = map(lambda comp: comp[3], components) 258 | segments = map(removeBadBackground, segments) 259 | log.log(cap.joinImagesH(segments)) 260 | segments = map(lambda seg: cap.smoothNoise1(seg, bgcolor=0), segments) 261 | log.log(cap.joinImagesH(segments)) 262 | cap.processExtras(log.steps, addr, extras, cap.CAP_STAGE_SEGMENT) 263 | return segments -------------------------------------------------------------------------------- /yellow/train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2011 Dmitry Nikulin 3 | 4 | This file is part of Captchure. 5 | 6 | Captchure is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | Captchure is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Captchure. If not, see . 18 | """ 19 | 20 | import os, cv, sys 21 | from random import shuffle, randint, uniform, choice 22 | from pyfann import libfann 23 | from lconsts import segW, segH, num_input, num_output, charset, train_file, ann_file 24 | 25 | test_file = "ann.test" 26 | 27 | sys.path.append("..") 28 | 29 | import cap 30 | from cap import resizeFit as adjustSize, segment_dir 31 | 32 | def addWhiteDots(image): 33 | for i in xrange(randint(10, 20)): 34 | image[randint(0, image.height - 1), randint(0, image.width - 1)] = 255 35 | return image 36 | 37 | def addGrayDots(image): 38 | for i in xrange(randint(10, 20)): 39 | image[randint(0, image.height - 1), randint(0, image.width - 1)] = 96 40 | return image 41 | 42 | def addBlackDots(image): 43 | for i in xrange(randint(10, 20)): 44 | image[randint(0, image.height - 1), randint(0, image.width - 1)] = 0 45 | return image 46 | 47 | def addGrayLines(image): 48 | for i in xrange(randint(1, 3)): 49 | pt1 = (randint(0, image.width - 1), randint(0, image.height - 1)) 50 | pt2 = (randint(0, image.width - 1), randint(0, image.height - 1)) 51 | cv.Line(image, pt1, pt2, 96, 1) 52 | return image 53 | 54 | def addGrayCircles(image): 55 | for i in xrange(randint(1, 4)): 56 | cv.Circle(image, (randint(0, image.width - 1), randint(0, image.height - 1)), randint(2, 4), 96, -1) 57 | return image 58 | 59 | def addGrayRectsBad(image): 60 | for i in xrange(randint(1, 3)): 61 | pt1 = (randint(0, image.width - 2), randint(0, image.height - 2)) 62 | pt2 = (randint(pt1[0] + 1, image.width - 1), randint(pt1[1] + 1, image.height - 1)) 63 | cv.Rectangle(image, pt1, pt2, 128, -1) 64 | return image 65 | 66 | def addGrayRects(image): 67 | for i in xrange(randint(1, 3)): 68 | w = randint(2, 5) 69 | h = randint(2, 5) 70 | pt1 = (randint(0, image.width - w), randint(0, image.height - h)) 71 | pt2 = (pt1[0] + w - 1, pt1[1] + h - 1) 72 | cv.Rectangle(image, pt1, pt2, 96, -1) 73 | return image 74 | 75 | def addRotation(image): 76 | angle = uniform(-15.0, 15.00000001) 77 | image = cap.doRotate(image, angle) 78 | return image 79 | 80 | spoilers = (addWhiteDots, addGrayDots, addBlackDots, addGrayLines, addGrayCircles, addGrayRects, addRotation) 81 | 82 | def spoil(image): 83 | return (choice(spoilers))(image) 84 | 85 | def loadTest(): 86 | global test 87 | test = libfann.training_data() 88 | test.read_train_from_file(test_file) 89 | 90 | def loadSegments(): 91 | global segments 92 | segments = os.listdir(segment_dir) 93 | segments = map(lambda name: (os.path.splitext(name)[0][0], cv.LoadImage(os.path.join(segment_dir, name), cv.CV_LOAD_IMAGE_GRAYSCALE)), segments) 94 | 95 | def printStats(): 96 | print "Samples: %d" % len(segments) 97 | print "Input: %d" % num_input 98 | print "Output: %d" % num_output 99 | 100 | def initNet(): 101 | learning_rate = 0.3 102 | num_neurons_hidden = num_input / 3 103 | 104 | #desired_error = 0.015 105 | #max_iterations = 10000 106 | #iterations_between_reports = 10 107 | 108 | global ann 109 | ann = libfann.neural_net() 110 | ann.create_standard_array((num_input, num_neurons_hidden, num_output)) 111 | ann.set_learning_rate(learning_rate) 112 | ann.set_activation_function_hidden(libfann.SIGMOID_SYMMETRIC_STEPWISE) 113 | ann.set_activation_function_output(libfann.SIGMOID_SYMMETRIC_STEPWISE) 114 | 115 | train = libfann.training_data() 116 | train.read_train_from_file(train_file) 117 | ann.init_weights(train) 118 | train.destroy_train() 119 | 120 | def mainLoop(): 121 | n_iter = 0 122 | last_save = 0 123 | min_test_MSE = 1.0 124 | max_iters_after_save = 50 125 | 126 | try: 127 | while True: 128 | n_iter += 1 129 | print "Iteration: %5d " % (n_iter), 130 | seg_copy = map(lambda (c, seg): (c, cv.CloneImage(seg)), segments) 131 | seg_copy = map(lambda (c, seg): (c, spoil(seg)), seg_copy) 132 | shuffle(seg_copy) 133 | 134 | f = open(train_file, "w") 135 | f.write("%d %d %d\n" % (len(segments), num_input, num_output)) 136 | 137 | for c, image in seg_copy: 138 | image = adjustSize(image, (segW, segH)) 139 | for y in range(image.height): 140 | for x in range(image.width): 141 | n = image[y, x] / 159.375 - 0.8 142 | f.write("%f " % n) 143 | f.write("\n") 144 | n = charset.index(c) 145 | f.write("-1 " * n + "1" + " -1" * (num_output - n - 1) + "\n") 146 | 147 | f.close() 148 | 149 | train = libfann.training_data() 150 | train.read_train_from_file(train_file) 151 | ann.train_epoch(train) 152 | train.destroy_train() 153 | print "Train MSE: %f " % (ann.get_MSE()), 154 | print "Train bit fail: %5d " % (ann.get_bit_fail()), 155 | ann.test_data(test) 156 | mse = ann.get_MSE() 157 | print "Test MSE: %f " % (mse), 158 | print "Test bit fail: %5d " % (ann.get_bit_fail()), 159 | if mse < min_test_MSE: 160 | min_test_MSE = mse 161 | ann.save(ann_file) 162 | last_save = n_iter 163 | print "saved", 164 | if n_iter - last_save > max_iters_after_save: break 165 | print 166 | except KeyboardInterrupt: print "Interrupted by user." 167 | 168 | def cleanup(): 169 | test.destroy_train() 170 | ann.destroy() 171 | 172 | def train(): 173 | loadTest() 174 | loadSegments() 175 | printStats() 176 | initNet() 177 | mainLoop() 178 | cleanup() 179 | 180 | if __name__ == "__main__": 181 | train() --------------------------------------------------------------------------------