├── COPYING ├── COPYING.LESSER ├── README.md ├── libqrencode_ctypes_bindings ├── README.md ├── docs │ ├── Makefile │ └── source │ │ ├── _qrencode.rst │ │ ├── _static │ │ └── qrimage.png │ │ ├── conf.py │ │ ├── index.rst │ │ └── qrencode.rst ├── libqrencode │ ├── __init__.py │ ├── _qrencode.py │ └── qrencode.py └── setup.py └── signal_processing ├── README.md ├── docs ├── Makefile └── source │ ├── conf.py │ ├── filter.rst │ ├── firwin.rst │ ├── gauss.rst │ ├── gold.rst │ ├── imgs │ ├── blur.tif │ ├── building.tif │ ├── building_jpg.tif │ ├── contrast.tif │ ├── einstein.tif │ ├── impulse.tif │ ├── jpg.tif │ └── meanshift.tif │ ├── index.rst │ ├── mls.rst │ ├── multirate.rst │ └── ssim.rst ├── setup.py └── sp ├── __init__.py ├── filter.py ├── firwin.py ├── gauss.py ├── gold.py ├── mls.py ├── multirate.py └── ssim.py /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 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER 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 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | python 2 | ====== 3 | 4 | libqrencode - ctypes python bindings to libqrencode http://mubeta06.github.io/python/libqrencode/ 5 | 6 | Signal Processing Library - various MATLAB-like signal processing math http://mubeta06.github.io/python/sp/ 7 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/README.md: -------------------------------------------------------------------------------- 1 | libqrencode 2 | =========== 3 | 4 | Please refer to documentation here http://mubeta06.github.io/python/libqrencode/ 5 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/libqrencodectypesbindings.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/libqrencodectypesbindings.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/libqrencodectypesbindings" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/libqrencodectypesbindings" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/source/_qrencode.rst: -------------------------------------------------------------------------------- 1 | :mod:`libqrencode._qrencode` 2 | ============================ 3 | 4 | Python ctypes bindings to libqrencode. Note these bindings have been automatically generated by ctypeslib using h2xml and xml2py as follows :: 5 | 6 | $ python -m ctypeslib.h2xml -c -o qrencode.xml /usr/local/include/qrencode.h 7 | 8 | $ python -m ctypeslib.xml2py qrencode.xml -k defst -l /usr/local/lib/libqrencode.so -o _qrencode.py 9 | 10 | This shows how to build the binding automatically under linux. The process is similar under windows with the expception that the .dll path needs to be specified. 11 | 12 | Pre-requisites 13 | -------------- 14 | 15 | Python (http://www.python.org) 16 | 17 | libqrencode (http://fukuchi.org/works/qrencode/index.html.en) 18 | 19 | ctypeslib (http://pypi.python.org/pypi/ctypeslib/) 20 | 21 | gccxml (http://www.gccxml.org) 22 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/source/_static/qrimage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/libqrencode_ctypes_bindings/docs/source/_static/qrimage.png -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # libqrencode ctypes bindings documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Jan 18 20:23:06 2012. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode'] 29 | 30 | # Add any paths that contain templates here, relative to this directory. 31 | templates_path = ['_templates'] 32 | 33 | # The suffix of source filenames. 34 | source_suffix = '.rst' 35 | 36 | # The encoding of source files. 37 | #source_encoding = 'utf-8-sig' 38 | 39 | # The master toctree document. 40 | master_doc = 'index' 41 | 42 | # General information about the project. 43 | project = u'libqrencode ctypes bindings' 44 | copyright = u'2012, Matthew Baker' 45 | 46 | # The version info for the project you're documenting, acts as replacement for 47 | # |version| and |release|, also used in various other places throughout the 48 | # built documents. 49 | # 50 | # The short X.Y version. 51 | version = '1.0' 52 | # The full version, including alpha/beta/rc tags. 53 | release = '1.0' 54 | 55 | # The language for content autogenerated by Sphinx. Refer to documentation 56 | # for a list of supported languages. 57 | #language = None 58 | 59 | # There are two options for replacing |today|: either, you set today to some 60 | # non-false value, then it is used: 61 | #today = '' 62 | # Else, today_fmt is used as the format for a strftime call. 63 | #today_fmt = '%B %d, %Y' 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | exclude_patterns = [] 68 | 69 | # The reST default role (used for this markup: `text`) to use for all documents. 70 | #default_role = None 71 | 72 | # If true, '()' will be appended to :func: etc. cross-reference text. 73 | #add_function_parentheses = True 74 | 75 | # If true, the current module name will be prepended to all description 76 | # unit titles (such as .. function::). 77 | #add_module_names = True 78 | 79 | # If true, sectionauthor and moduleauthor directives will be shown in the 80 | # output. They are ignored by default. 81 | #show_authors = False 82 | 83 | # The name of the Pygments (syntax highlighting) style to use. 84 | pygments_style = 'sphinx' 85 | 86 | # A list of ignored prefixes for module index sorting. 87 | #modindex_common_prefix = [] 88 | 89 | 90 | # -- Options for HTML output --------------------------------------------------- 91 | 92 | # The theme to use for HTML and HTML Help pages. See the documentation for 93 | # a list of builtin themes. 94 | html_theme = 'default' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | #html_theme_options = {} 100 | 101 | # Add any paths that contain custom themes here, relative to this directory. 102 | #html_theme_path = [] 103 | 104 | # The name for this set of Sphinx documents. If None, it defaults to 105 | # " v documentation". 106 | #html_title = None 107 | 108 | # A shorter title for the navigation bar. Default is the same as html_title. 109 | #html_short_title = None 110 | 111 | # The name of an image file (relative to this directory) to place at the top 112 | # of the sidebar. 113 | #html_logo = None 114 | 115 | # The name of an image file (within the static path) to use as favicon of the 116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 117 | # pixels large. 118 | #html_favicon = None 119 | 120 | # Add any paths that contain custom static files (such as style sheets) here, 121 | # relative to this directory. They are copied after the builtin static files, 122 | # so a file named "default.css" will overwrite the builtin "default.css". 123 | html_static_path = ['_static'] 124 | 125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 126 | # using the given strftime format. 127 | #html_last_updated_fmt = '%b %d, %Y' 128 | 129 | # If true, SmartyPants will be used to convert quotes and dashes to 130 | # typographically correct entities. 131 | #html_use_smartypants = True 132 | 133 | # Custom sidebar templates, maps document names to template names. 134 | #html_sidebars = {} 135 | 136 | # Additional templates that should be rendered to pages, maps page names to 137 | # template names. 138 | #html_additional_pages = {} 139 | 140 | # If false, no module index is generated. 141 | #html_domain_indices = True 142 | 143 | # If false, no index is generated. 144 | #html_use_index = True 145 | 146 | # If true, the index is split into individual pages for each letter. 147 | #html_split_index = False 148 | 149 | # If true, links to the reST sources are added to the pages. 150 | #html_show_sourcelink = True 151 | 152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 153 | #html_show_sphinx = True 154 | 155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 156 | #html_show_copyright = True 157 | 158 | # If true, an OpenSearch description file will be output, and all pages will 159 | # contain a tag referring to it. The value of this option must be the 160 | # base URL from which the finished HTML is served. 161 | #html_use_opensearch = '' 162 | 163 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 164 | #html_file_suffix = None 165 | 166 | # Output file base name for HTML help builder. 167 | htmlhelp_basename = 'libqrencodectypesbindingsdoc' 168 | 169 | 170 | # -- Options for LaTeX output -------------------------------------------------- 171 | 172 | # The paper size ('letter' or 'a4'). 173 | #latex_paper_size = 'letter' 174 | 175 | # The font size ('10pt', '11pt' or '12pt'). 176 | #latex_font_size = '10pt' 177 | 178 | # Grouping the document tree into LaTeX files. List of tuples 179 | # (source start file, target name, title, author, documentclass [howto/manual]). 180 | latex_documents = [ 181 | ('index', 'libqrencodectypesbindings.tex', u'libqrencode ctypes bindings Documentation', 182 | u'Matthew Baker', 'manual'), 183 | ] 184 | 185 | # The name of an image file (relative to this directory) to place at the top of 186 | # the title page. 187 | #latex_logo = None 188 | 189 | # For "manual" documents, if this is true, then toplevel headings are parts, 190 | # not chapters. 191 | #latex_use_parts = False 192 | 193 | # If true, show page references after internal links. 194 | #latex_show_pagerefs = False 195 | 196 | # If true, show URL addresses after external links. 197 | #latex_show_urls = False 198 | 199 | # Additional stuff for the LaTeX preamble. 200 | #latex_preamble = '' 201 | 202 | # Documents to append as an appendix to all manuals. 203 | #latex_appendices = [] 204 | 205 | # If false, no module index is generated. 206 | #latex_domain_indices = True 207 | 208 | 209 | # -- Options for manual page output -------------------------------------------- 210 | 211 | # One entry per manual page. List of tuples 212 | # (source start file, name, description, authors, manual section). 213 | man_pages = [ 214 | ('index', 'libqrencodectypesbindings', u'libqrencode ctypes bindings Documentation', 215 | [u'Matthew Baker'], 1) 216 | ] 217 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. libqrencode ctypes bindings documentation master file, created by 2 | sphinx-quickstart on Wed Jan 18 20:23:06 2012. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | :mod:`libqrencode` -- Python Bindings to libqrencode 7 | ==================================================== 8 | 9 | .. |p1| replace:: libqrencode is a C library for encoding data in a QR Code symbol, a kind of 2D symbology that can be scanned by handy terminals such as a mobile phone with CCD (http://fukuchi.org/works/qrencode/index.html.en). libqrencode is a stand-alone library not requiring any additional files at run time and demonstrates fast symbol encoding with automatic optimization of input data. libqrencode supports QR Code model 2, described in JIS (Japanese Industrial Standards) X0510:2004 or ISO/IEC 18004. 10 | 11 | .. |p2| replace:: This documentation describes python bindings written to interface with the libqrencode API. The bindings have been constructed using ctypes (http://docs.python.org/library/ctypes.html) which provides functionality to dynamically load shared libraries / DLLs, and hence, allows construction of bindings in pure python. This binding only uses built-in python modules with the exception of PIL for image IO but only when the bindings are run in scripted fashion, thereby, making the binding highly portable. Given the binding is pure python it is also somewhat python version agnostic. Futhermore, since the binding loads up the shared library dynamically the binding more comprehensively exposes the API for future enhancements in contrast to other interpretter extension binding approaches. 12 | 13 | .. |p3| replace:: Any questions or comments regarding the bindings please feel free to get in touch with me, mu.beta.06@gmail.com 14 | 15 | .. |qrimage| image:: /_static/qrimage.png 16 | :scale: 200 % 17 | 18 | +-----------------+-----------+ 19 | | |p1| | | 20 | | | | 21 | | |p2| | |qrimage| | 22 | | | | 23 | | |p3| | | 24 | +-----------------+-----------+ 25 | 26 | Contents: 27 | 28 | .. toctree:: 29 | :maxdepth: 2 30 | 31 | qrencode 32 | _qrencode 33 | 34 | Indices and tables 35 | ================== 36 | 37 | * :ref:`genindex` 38 | * :ref:`modindex` 39 | * :ref:`search` 40 | 41 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/docs/source/qrencode.rst: -------------------------------------------------------------------------------- 1 | :mod:`libqrencode.qrencode` -- QR Encoding 2 | ========================================== 3 | 4 | .. automodule:: libqrencode.qrencode 5 | 6 | 7 | Installation 8 | ------------ 9 | 10 | 1. Install libqrencode. 11 | 12 | 2. Unpack archive onto local machine. 13 | 14 | 3. Run :: 15 | 16 | $ python setup.py install 17 | 18 | 4. Test :: 19 | 20 | $ python -m libqrencode.qrencode 'Hello World' 21 | XXXXXXXXXXXXXX XX XXXX XXXXXXXXXXXXXX 22 | XX XX XXXXXX XX XX 23 | XX XXXXXX XX XXXX XXXX XX XXXXXX XX 24 | XX XXXXXX XX XX XX XX XXXXXX XX 25 | XX XXXXXX XX XX XX XX XXXXXX XX 26 | XX XX XX XX XX 27 | XXXXXXXXXXXXXX XX XX XX XXXXXXXXXXXXXX 28 | XXXX XXXX 29 | XXXXXX XXXXXXXXXXXXXXXX XXXX XX 30 | XXXX XXXX XXXXXX XXXXXX XXXX 31 | XX XX XX XX XX XX XXXX XXXXXXXXXXXX 32 | XX XXXXXX XX XX 33 | XXXX XX XXXX XX XXXX XXXX 34 | XX XXXX XX XXXX 35 | XXXXXXXXXXXXXX XX XXXX XXXX XXXXXX 36 | XX XX XXXX XXXX XX XX 37 | XX XXXXXX XX XX XX XX 38 | XX XXXXXX XX XXXXXX XXXXXX XXXX 39 | XX XXXXXX XX XX XX XX XX XX XX XX 40 | XX XX XX XX XX XX 41 | XXXXXXXXXXXXXX XX XXXXXX XX XXXX 42 | 43 | Usage 44 | ----- 45 | 46 | Scripted Usage 47 | ^^^^^^^^^^^^^^ 48 | 49 | 1. Run the following for usage :: 50 | 51 | $ python -m libqrencode.qrencode -h 52 | Usage: qrencode [OPTION]... [STRING] 53 | 54 | libqrencode ctypes python binding version 1.0, libqrencode version 3.2.1 55 | 56 | Options: 57 | -h, --help show this help message and exit 58 | -o FILENAME, --filename=FILENAME 59 | Encoded image filename (.png, .pdf, .jpg, .tif...) 60 | -s SIZE, --size=SIZE Specify module size in dots (pixels). (default=3) 61 | -l LEVEL, --level=LEVEL 62 | specify error correction level from L (lowest) to H 63 | (highest). (default=L) 64 | -v SYMVERSION, --symversion=SYMVERSION 65 | specify the version of the symbol. (default=auto) 66 | -m MARGIN, --margin=MARGIN 67 | specify the width of the margins. (default=4) 68 | (2 for Micro))) 69 | -d DPI, --dpi=DPI specify the DPI of the generated PNG. (default=72) 70 | -S, --structured make structured symbols. Version must be 71 | specified. 72 | -k, --kanji assume that the input text contains kanji 73 | (shift-jis). 74 | -c, --casesensitive encode lower-case alphabet characters in 8-bit mode. 75 | (default) 76 | -8, --eightbit encode entire data in 8-bit mode. -k and -c will be 77 | ignored. 78 | -M, --micro encode in a Micro QR Code. (experimental). 79 | 80 | 81 | Module Usage 82 | ^^^^^^^^^^^^ 83 | 84 | 1. Import libqrencode bindings:: 85 | 86 | >>> from libqrencode import qrencode 87 | 88 | 2. Create a :class:`qrencode.QREncoder` instantiation:: 89 | 90 | >>> encoder = qrencode.QREncoder() 91 | 92 | 3. Encode a string using the aforementioned instantiation:: 93 | 94 | >>> encoder.encode('Hello World') 95 | 96 | 4. Select encoded output format from one of the following output formats: 97 | 98 | 1. ASCII:: 99 | 100 | >>> encoder.asciipreview() 101 | XXXXXXXXXXXXXX XX XXXX XXXXXXXXXXXXXX 102 | XX XX XXXXXX XX XX 103 | XX XXXXXX XX XXXX XXXX XX XXXXXX XX 104 | XX XXXXXX XX XX XX XX XXXXXX XX 105 | XX XXXXXX XX XX XX XX XXXXXX XX 106 | XX XX XX XX XX 107 | XXXXXXXXXXXXXX XX XX XX XXXXXXXXXXXXXX 108 | XXXX XXXX 109 | XXXXXX XXXXXXXXXXXXXXXX XXXX XX 110 | XXXX XXXX XXXXXX XXXXXX XXXX 111 | XX XX XX XX XX XX XXXX XXXXXXXXXXXX 112 | XX XXXXXX XX XX 113 | XXXX XX XXXX XX XXXX XXXX 114 | XX XXXX XX XXXX 115 | XXXXXXXXXXXXXX XX XXXX XXXX XXXXXX 116 | XX XX XXXX XXXX XX XX 117 | XX XXXXXX XX XX XX XX 118 | XX XXXXXX XX XXXXXX XXXXXX XXXX 119 | XX XXXXXX XX XX XX XX XX XX XX XX 120 | XX XX XX XX XX XX 121 | XXXXXXXXXXXXXX XX XXXXXX XX XXXX 122 | 123 | 2. Boolean list of lists:: 124 | 125 | >>> qr_list = encoder.as2dlist() 126 | 127 | 3. Postscript string:: 128 | 129 | >>> qr_ps = encoder.asps() 130 | 131 | See the individual classes, methods, attributes and functions below for further details. 132 | 133 | Classes 134 | ------- 135 | 136 | .. autoclass:: QREncode 137 | :members: 138 | 139 | .. autoclass:: QRcode 140 | :members: 141 | 142 | .. autoclass:: QRcode_List 143 | :members: 144 | 145 | .. autoclass:: QREncoder 146 | :members: 147 | 148 | .. autoclass:: StructuredQREncoder 149 | :members: 150 | 151 | Functions 152 | --------- 153 | 154 | .. autofunction:: call 155 | 156 | .. autofunction:: main 157 | 158 | Exceptions 159 | ---------- 160 | 161 | .. autoexception:: Error 162 | 163 | Pre-requisites 164 | -------------- 165 | 166 | Python (http://www.python.org) 167 | 168 | libqrencode (http://fukuchi.org/works/qrencode/index.html.en) 169 | 170 | Python Imaging Library (PIL, http://www.pythonware.com/products/pil/) (optional) 171 | 172 | Known Issues 173 | ---------------------- 174 | 175 | 1. For the moment the bindings have only be constructed for use under linux. I could be tempted to support windows if required. 176 | 177 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/libqrencode/__init__.py: -------------------------------------------------------------------------------- 1 | """This file is part of libqrencode python ctypes bindings. 2 | 3 | Copyright (C) 2012 Matthew Baker 4 | 5 | This is free software: you can redistribute it and/or modify 6 | it under the terms of the LGNU Lesser General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This software is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the LGNU Lesser General Public License 16 | along with this software. If not, see .""" 17 | 18 | author = 'Matthew Baker' 19 | version = '1.1' 20 | 21 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/libqrencode/_qrencode.py: -------------------------------------------------------------------------------- 1 | """This file is part of libqrencode python ctypes bindings. 2 | 3 | Copyright (C) 2012 Matthew Baker 4 | 5 | This is free software: you can redistribute it and/or modify 6 | it under the terms of the LGNU Lesser General Public License as published by 7 | the Free Software Foundation, either version 3 of the License, or 8 | (at your option) any later version. 9 | 10 | This software is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the LGNU Lesser General Public License 16 | along with this software. If not, see .""" 17 | 18 | 19 | from ctypes import * 20 | 21 | _libraries = {} 22 | _libraries['/usr/local/lib/libqrencode.so'] = CDLL('/usr/local/lib/libqrencode.so') 23 | STRING = c_char_p 24 | 25 | 26 | QR_ECLEVEL_H = 3 27 | QR_MODE_FNC1FIRST = 6 28 | QR_MODE_KANJI = 3 29 | QR_ECLEVEL_Q = 2 30 | QR_MODE_NUM = 0 31 | QR_MODE_ECI = 5 32 | QR_MODE_8 = 2 33 | QR_MODE_AN = 1 34 | QR_ECLEVEL_L = 0 35 | QR_MODE_FNC1SECOND = 7 36 | QR_ECLEVEL_M = 1 37 | QR_MODE_STRUCTURE = 4 38 | QR_MODE_NUL = -1 39 | 40 | # values for enumeration 'QRencodeMode' 41 | QRencodeMode = c_int # enum 42 | 43 | # values for enumeration 'QRecLevel' 44 | QRecLevel = c_int # enum 45 | class _QRinput(Structure): 46 | pass 47 | QRinput = _QRinput 48 | _QRinput._fields_ = [ 49 | ] 50 | QRinput_new = _libraries['/usr/local/lib/libqrencode.so'].QRinput_new 51 | QRinput_new.restype = POINTER(QRinput) 52 | QRinput_new.argtypes = [] 53 | QRinput_new2 = _libraries['/usr/local/lib/libqrencode.so'].QRinput_new2 54 | QRinput_new2.restype = POINTER(QRinput) 55 | QRinput_new2.argtypes = [c_int, QRecLevel] 56 | QRinput_newMQR = _libraries['/usr/local/lib/libqrencode.so'].QRinput_newMQR 57 | QRinput_newMQR.restype = POINTER(QRinput) 58 | QRinput_newMQR.argtypes = [c_int, QRecLevel] 59 | QRinput_append = _libraries['/usr/local/lib/libqrencode.so'].QRinput_append 60 | QRinput_append.restype = c_int 61 | QRinput_append.argtypes = [POINTER(QRinput), QRencodeMode, c_int, POINTER(c_ubyte)] 62 | QRinput_appendECIheader = _libraries['/usr/local/lib/libqrencode.so'].QRinput_appendECIheader 63 | QRinput_appendECIheader.restype = c_int 64 | QRinput_appendECIheader.argtypes = [POINTER(QRinput), c_uint] 65 | QRinput_getVersion = _libraries['/usr/local/lib/libqrencode.so'].QRinput_getVersion 66 | QRinput_getVersion.restype = c_int 67 | QRinput_getVersion.argtypes = [POINTER(QRinput)] 68 | QRinput_setVersion = _libraries['/usr/local/lib/libqrencode.so'].QRinput_setVersion 69 | QRinput_setVersion.restype = c_int 70 | QRinput_setVersion.argtypes = [POINTER(QRinput), c_int] 71 | QRinput_getErrorCorrectionLevel = _libraries['/usr/local/lib/libqrencode.so'].QRinput_getErrorCorrectionLevel 72 | QRinput_getErrorCorrectionLevel.restype = QRecLevel 73 | QRinput_getErrorCorrectionLevel.argtypes = [POINTER(QRinput)] 74 | QRinput_setErrorCorrectionLevel = _libraries['/usr/local/lib/libqrencode.so'].QRinput_setErrorCorrectionLevel 75 | QRinput_setErrorCorrectionLevel.restype = c_int 76 | QRinput_setErrorCorrectionLevel.argtypes = [POINTER(QRinput), QRecLevel] 77 | QRinput_setVersionAndErrorCorrectionLevel = _libraries['/usr/local/lib/libqrencode.so'].QRinput_setVersionAndErrorCorrectionLevel 78 | QRinput_setVersionAndErrorCorrectionLevel.restype = c_int 79 | QRinput_setVersionAndErrorCorrectionLevel.argtypes = [POINTER(QRinput), c_int, QRecLevel] 80 | QRinput_free = _libraries['/usr/local/lib/libqrencode.so'].QRinput_free 81 | QRinput_free.restype = None 82 | QRinput_free.argtypes = [POINTER(QRinput)] 83 | QRinput_check = _libraries['/usr/local/lib/libqrencode.so'].QRinput_check 84 | QRinput_check.restype = c_int 85 | QRinput_check.argtypes = [QRencodeMode, c_int, POINTER(c_ubyte)] 86 | class _QRinput_Struct(Structure): 87 | pass 88 | QRinput_Struct = _QRinput_Struct 89 | _QRinput_Struct._fields_ = [ 90 | ] 91 | QRinput_Struct_new = _libraries['/usr/local/lib/libqrencode.so'].QRinput_Struct_new 92 | QRinput_Struct_new.restype = POINTER(QRinput_Struct) 93 | QRinput_Struct_new.argtypes = [] 94 | QRinput_Struct_setParity = _libraries['/usr/local/lib/libqrencode.so'].QRinput_Struct_setParity 95 | QRinput_Struct_setParity.restype = None 96 | QRinput_Struct_setParity.argtypes = [POINTER(QRinput_Struct), c_ubyte] 97 | QRinput_Struct_appendInput = _libraries['/usr/local/lib/libqrencode.so'].QRinput_Struct_appendInput 98 | QRinput_Struct_appendInput.restype = c_int 99 | QRinput_Struct_appendInput.argtypes = [POINTER(QRinput_Struct), POINTER(QRinput)] 100 | QRinput_Struct_free = _libraries['/usr/local/lib/libqrencode.so'].QRinput_Struct_free 101 | QRinput_Struct_free.restype = None 102 | QRinput_Struct_free.argtypes = [POINTER(QRinput_Struct)] 103 | QRinput_splitQRinputToStruct = _libraries['/usr/local/lib/libqrencode.so'].QRinput_splitQRinputToStruct 104 | QRinput_splitQRinputToStruct.restype = POINTER(QRinput_Struct) 105 | QRinput_splitQRinputToStruct.argtypes = [POINTER(QRinput)] 106 | QRinput_Struct_insertStructuredAppendHeaders = _libraries['/usr/local/lib/libqrencode.so'].QRinput_Struct_insertStructuredAppendHeaders 107 | QRinput_Struct_insertStructuredAppendHeaders.restype = c_int 108 | QRinput_Struct_insertStructuredAppendHeaders.argtypes = [POINTER(QRinput_Struct)] 109 | QRinput_setFNC1First = _libraries['/usr/local/lib/libqrencode.so'].QRinput_setFNC1First 110 | QRinput_setFNC1First.restype = c_int 111 | QRinput_setFNC1First.argtypes = [POINTER(QRinput)] 112 | QRinput_setFNC1Second = _libraries['/usr/local/lib/libqrencode.so'].QRinput_setFNC1Second 113 | QRinput_setFNC1Second.restype = c_int 114 | QRinput_setFNC1Second.argtypes = [POINTER(QRinput), c_ubyte] 115 | class QRcode(Structure): 116 | pass 117 | QRcode._fields_ = [ 118 | ('version', c_int), 119 | ('width', c_int), 120 | ('data', POINTER(c_ubyte)), 121 | ] 122 | class _QRcode_List(Structure): 123 | pass 124 | QRcode_List = _QRcode_List 125 | _QRcode_List._fields_ = [ 126 | ('code', POINTER(QRcode)), 127 | ('next', POINTER(QRcode_List)), 128 | ] 129 | QRcode_encodeInput = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeInput 130 | QRcode_encodeInput.restype = POINTER(QRcode) 131 | QRcode_encodeInput.argtypes = [POINTER(QRinput)] 132 | QRcode_encodeString = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeString 133 | QRcode_encodeString.restype = POINTER(QRcode) 134 | QRcode_encodeString.argtypes = [STRING, c_int, QRecLevel, QRencodeMode, c_int] 135 | QRcode_encodeString8bit = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeString8bit 136 | QRcode_encodeString8bit.restype = POINTER(QRcode) 137 | QRcode_encodeString8bit.argtypes = [STRING, c_int, QRecLevel] 138 | QRcode_encodeStringMQR = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeStringMQR 139 | QRcode_encodeStringMQR.restype = POINTER(QRcode) 140 | QRcode_encodeStringMQR.argtypes = [STRING, c_int, QRecLevel, QRencodeMode, c_int] 141 | QRcode_encodeString8bitMQR = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeString8bitMQR 142 | QRcode_encodeString8bitMQR.restype = POINTER(QRcode) 143 | QRcode_encodeString8bitMQR.argtypes = [STRING, c_int, QRecLevel] 144 | QRcode_encodeData = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeData 145 | QRcode_encodeData.restype = POINTER(QRcode) 146 | QRcode_encodeData.argtypes = [c_int, POINTER(c_ubyte), c_int, QRecLevel] 147 | QRcode_encodeDataMQR = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeDataMQR 148 | QRcode_encodeDataMQR.restype = POINTER(QRcode) 149 | QRcode_encodeDataMQR.argtypes = [c_int, POINTER(c_ubyte), c_int, QRecLevel] 150 | QRcode_free = _libraries['/usr/local/lib/libqrencode.so'].QRcode_free 151 | QRcode_free.restype = None 152 | QRcode_free.argtypes = [POINTER(QRcode)] 153 | QRcode_encodeInputStructured = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeInputStructured 154 | QRcode_encodeInputStructured.restype = POINTER(QRcode_List) 155 | QRcode_encodeInputStructured.argtypes = [POINTER(QRinput_Struct)] 156 | QRcode_encodeStringStructured = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeStringStructured 157 | QRcode_encodeStringStructured.restype = POINTER(QRcode_List) 158 | QRcode_encodeStringStructured.argtypes = [STRING, c_int, QRecLevel, QRencodeMode, c_int] 159 | QRcode_encodeString8bitStructured = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeString8bitStructured 160 | QRcode_encodeString8bitStructured.restype = POINTER(QRcode_List) 161 | QRcode_encodeString8bitStructured.argtypes = [STRING, c_int, QRecLevel] 162 | QRcode_encodeDataStructured = _libraries['/usr/local/lib/libqrencode.so'].QRcode_encodeDataStructured 163 | QRcode_encodeDataStructured.restype = POINTER(QRcode_List) 164 | QRcode_encodeDataStructured.argtypes = [c_int, POINTER(c_ubyte), c_int, QRecLevel] 165 | QRcode_List_size = _libraries['/usr/local/lib/libqrencode.so'].QRcode_List_size 166 | QRcode_List_size.restype = c_int 167 | QRcode_List_size.argtypes = [POINTER(QRcode_List)] 168 | QRcode_List_free = _libraries['/usr/local/lib/libqrencode.so'].QRcode_List_free 169 | QRcode_List_free.restype = None 170 | QRcode_List_free.argtypes = [POINTER(QRcode_List)] 171 | QRcode_APIVersion = _libraries['/usr/local/lib/libqrencode.so'].QRcode_APIVersion 172 | QRcode_APIVersion.restype = None 173 | QRcode_APIVersion.argtypes = [POINTER(c_int), POINTER(c_int), POINTER(c_int)] 174 | QRcode_APIVersionString = _libraries['/usr/local/lib/libqrencode.so'].QRcode_APIVersionString 175 | QRcode_APIVersionString.restype = STRING 176 | QRcode_APIVersionString.argtypes = [] 177 | QRcode_clearCache = _libraries['/usr/local/lib/libqrencode.so'].QRcode_clearCache 178 | QRcode_clearCache.restype = None 179 | QRcode_clearCache.argtypes = [] 180 | MQRSPEC_VERSION_MAX = 4 # Variable c_int '4' 181 | QRSPEC_VERSION_MAX = 40 # Variable c_int '40' 182 | __all__ = ['QRcode_clearCache', 'QRinput_setFNC1Second', 183 | 'QRcode_List_size', 'QRinput_append', 'QRcode_List', 184 | 'QR_MODE_8', 'QR_MODE_KANJI', 'QRcode_encodeStringMQR', 185 | 'QR_MODE_FNC1FIRST', '_QRcode_List', 186 | 'QRcode_encodeString8bit', 'QRcode', 'QRcode_encodeString', 187 | 'QR_MODE_ECI', 'QRcode_encodeString8bitMQR', 'QR_MODE_NUL', 188 | 'QR_MODE_NUM', 'QRcode_encodeString8bitStructured', 189 | 'QR_ECLEVEL_Q', 'QRcode_encodeInputStructured', 190 | 'QRinput_splitQRinputToStruct', 'QRinput_Struct', 191 | 'QRinput_getVersion', 'QRcode_List_free', 192 | 'QRcode_encodeDataMQR', 'QRinput_Struct_setParity', 193 | 'QRinput_setVersion', 'QRinput_setErrorCorrectionLevel', 194 | 'QRcode_encodeStringStructured', 'QRinput_check', 195 | 'QRinput_Struct_free', 'QRinput_Struct_new', 196 | 'QR_ECLEVEL_M', 'QR_ECLEVEL_L', 'QRcode_APIVersion', 197 | 'QR_MODE_STRUCTURE', 'QRinput_appendECIheader', 198 | 'QR_MODE_FNC1SECOND', 199 | 'QRinput_Struct_insertStructuredAppendHeaders', 200 | 'QRcode_encodeData', 'QRinput', 'QRinput_new2', 201 | 'QRSPEC_VERSION_MAX', 'QRecLevel', '_QRinput', 202 | 'QRcode_encodeInput', 'QRinput_getErrorCorrectionLevel', 203 | 'QRcode_encodeDataStructured', 'QRencodeMode', 204 | 'MQRSPEC_VERSION_MAX', '_QRinput_Struct', 'QRinput_free', 205 | 'QRinput_setVersionAndErrorCorrectionLevel', 206 | 'QRinput_Struct_appendInput', 'QR_MODE_AN', 207 | 'QRcode_APIVersionString', 'QRinput_newMQR', 'QRinput_new', 208 | 'QRcode_free', 'QR_ECLEVEL_H', 'QRinput_setFNC1First'] 209 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/libqrencode/qrencode.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Python ctypes binding to libqrencode. 3 | 4 | This module when ran as a script attempts to mimic the c sample program 5 | qrenc.c otherwise known as qrencode 6 | 7 | 8 | This file is part of libqrencode python ctypes bindings. 9 | 10 | Copyright (C) 2012 Matthew Baker 11 | 12 | This is free software: you can redistribute it and/or modify 13 | it under the terms of the LGNU Lesser General Public License as published by 14 | the Free Software Foundation, either version 3 of the License, or 15 | (at your option) any later version. 16 | 17 | This software is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | GNU General Public License for more details. 21 | 22 | You should have received a copy of the LGNU Lesser General Public License 23 | along with this software. If not, see .""" 24 | 25 | import ctypes 26 | import errno 27 | import optparse 28 | import os 29 | import sys 30 | 31 | from _qrencode import * 32 | 33 | 34 | class Error(Exception): 35 | 36 | """This is a user-defined exception for errors raised by this module.""" 37 | 38 | pass 39 | 40 | 41 | def call(func, *args): 42 | """Convenience routine to call function func, check for NULL pointer and 43 | subsequently check errno to report useful error message.""" 44 | p = func(*args) 45 | if p: 46 | return p 47 | else: 48 | raise Error('NULL pointer returned when calling %s, errno %s' % 49 | (str(func), errno.errorcode[ctypes.get_errno()])) 50 | 51 | 52 | class QREncode(object): 53 | 54 | """Base class for representing QREncode c structures. Allows for struct 55 | member read access as class attributes.""" 56 | 57 | def __init__(self, p): 58 | """Initialise an DmtxStructure object with pointer p.""" 59 | self._p = p 60 | 61 | def __getattribute__(self, name): 62 | """Overloaded method so each field of c structure can be assessed as 63 | read only attributes.""" 64 | try: 65 | return object.__getattribute__(self, name) 66 | except AttributeError: 67 | p = object.__getattribute__(self, '_p') 68 | return getattr(p.contents, name) 69 | 70 | 71 | class QRcode(QREncode): 72 | 73 | """Python representation of QRcode c structure""" 74 | 75 | def __init__(self, p, cleanup=True): 76 | if p: 77 | super(QRcode, self).__init__(p) 78 | self.cleanup = cleanup #boolean to perform QRcode cleanup or not 79 | else: 80 | raise ValueError('Invalid pointer to QRcode c structure required') 81 | 82 | def __del__(self): 83 | """Clean up QRcode c structure.""" 84 | if self._p and self.cleanup: 85 | QRcode_free(self._p) 86 | 87 | 88 | class QRcode_List(QREncode, list): 89 | 90 | """Python representation of QRcode_List c structure.""" 91 | 92 | def __init__(self, p): 93 | if p: 94 | super(QRcode_List, self).__init__(p) 95 | while p: 96 | self.append(QRcode(p.contents.code, cleanup=False)) 97 | p = p.contents.next 98 | else: 99 | raise ValueError('Invalid pointer to QRcode_List c structure') 100 | 101 | def __del__(self): 102 | """Clean up QRcode_List c structure.""" 103 | if self._p: 104 | QRcode_List_free(self._p) 105 | 106 | 107 | class QREncoder(object): 108 | 109 | """Base class for representing QREncoder. 110 | 111 | Largely used to maintain the state that the globals in qrenc.c represent. 112 | """ 113 | 114 | def __init__(self): 115 | """Initialise object.""" 116 | self._casesensitive = True 117 | self._code = None #Represents encoded result i.e. a QRcode c structure 118 | self._eightbit = False 119 | self._hint = QR_MODE_8 120 | self._level = QR_ECLEVEL_L 121 | self._micro = False 122 | self._version = 0 123 | 124 | def encode(self, data): 125 | """Encode input string represented by data""" 126 | cdata = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte 127 | if self.eightbit else ctypes.c_char)) 128 | length = len(data) 129 | if self.micro: 130 | if self.version == 0: 131 | e = 'Version must be specified to encode a Micro QR Code symbol' 132 | raise Error(e) 133 | elif self.version > MQRSPEC_VERSION_MAX: 134 | e = 'Version should be less or equal to %d.' 135 | raise Error(e % MQRSPEC_VERSION_MAX) 136 | elif self.eightbit: 137 | self.code = call(QRcode_encodeDataMQR, length, cdata, 138 | self.version, self.level) 139 | else: 140 | self.code = call(QRcode_encodeStringMQR, cdata, self.version, 141 | self.level, self.hint, self.casesensitive) 142 | else: 143 | if self.eightbit: 144 | self.code = call(QRcode_encodeData, length, cdata, self.version, 145 | self.level) 146 | else: 147 | self.code = call(QRcode_encodeString, cdata, self.version, 148 | self.level, self.hint, self.casesensitive) 149 | 150 | def as2dlist(self): 151 | """Return a list of lists describing the encoded data.""" 152 | l = list() 153 | offset = 0 154 | for y in range(self.code.width): 155 | row = list() 156 | for x in range(self.code.width): 157 | row.append(bool(self.code.data[offset] & 1)) 158 | offset += 1 159 | l.append(row) 160 | return l 161 | 162 | def asciipreview(self): 163 | """Print an ascii representation of the Encoder output to stdout""" 164 | for row in self.as2dlist(): 165 | for col in row: 166 | sys.stdout.write('XX' if col else ' ') 167 | sys.stdout.write('\n') 168 | 169 | def asps(self): 170 | """Return a PostScript representation of the encoded QRCode. 171 | 172 | Paints the "black" symbol in the current colour on the assumption 173 | that the background has already been painted and appropriate colour. 174 | Symbols are assumed to be 1 user coordinate square. 175 | 176 | """ 177 | ps = """ 178 | %QR Code postscript output 179 | %Generated by qrencodes.py 180 | 181 | """ 182 | # Get the datamatrix symbols in bottom-to-top & left-to-right order. 183 | rows = self.as2dlist() 184 | nrow = len(rows) 185 | ps += '%d array\n' % nrow 186 | for i in range(nrow): 187 | ps += 'dup %d [' % (nrow - 1 - i) 188 | for sym in rows[i]: 189 | ps += '1 ' if sym else '0 ' 190 | ps += '] put\n' 191 | ps += """ 192 | gsave 2 dict begin 193 | /x 0 def 194 | /y 0 def 195 | { 196 | { 197 | 1 eq {x y 1 1 rectfill} if 198 | /x x 1 add store 199 | } forall 200 | /y y 1 add store 201 | /x 0 store 202 | } forall 203 | end grestore 204 | """ 205 | return ps 206 | 207 | def _get_casesensitive(self): 208 | """Return the QREncoder's casesensitive property.""" 209 | return int(self._casesensitive) 210 | 211 | def _set_casesensitive(self, casesensitive): 212 | if isinstance(casesensitive, (bool)): 213 | self._casesensitive = casesensitive 214 | else: 215 | raise ValueError('boolean required') 216 | 217 | def _get_code(self): 218 | """Return the QREncode object""" 219 | return self._code 220 | 221 | def _set_code(self, code): 222 | self._code = QRcode(code) 223 | 224 | def _get_eightbit(self): 225 | """Return the QREncoder's eightbit property.""" 226 | return self._eightbit 227 | 228 | def _set_eightbit(self, eightbit): 229 | if isinstance(eightbit, (bool)): 230 | self._eightbit = eightbit 231 | else: 232 | raise ValueError('boolean required') 233 | 234 | def _get_hint(self): 235 | """Return the QREncoder's hint.""" 236 | return self._hint 237 | 238 | def _set_hint(self, hint): 239 | if hint in [QR_MODE_8, QR_MODE_KANJI]: 240 | self._hint = hint 241 | else: 242 | raise ValueError('invalid hint %s' % str(hint)) 243 | 244 | def _get_level(self): 245 | """Return the QREncoder's level.""" 246 | return self._level 247 | 248 | def _set_level(self, level): 249 | if level in [QR_ECLEVEL_L, QR_ECLEVEL_M, QR_ECLEVEL_Q, QR_ECLEVEL_H]: 250 | self._level = level 251 | else: 252 | raise ValueError('invalid level %s' % str(level)) 253 | 254 | def _get_micro(self): 255 | """Return the QREncoder's micro property.""" 256 | return self._micro 257 | 258 | def _set_micro(self, micro): 259 | if isinstance(micro, (bool)): 260 | self._micro = micro 261 | else: 262 | raise ValueError('boolean required') 263 | 264 | def _get_version(self): 265 | """Return the QREncoder's symbol version property.""" 266 | return self._version 267 | 268 | def _set_version(self, version): 269 | if isinstance(version, (int)) and 0<= version <= QRSPEC_VERSION_MAX: 270 | self._version = version 271 | else: 272 | raise ValueError('version must be 0<=int<=%d' % QRSPEC_VERSION_MAX) 273 | 274 | #properties 275 | casesensitive = property(_get_casesensitive, _set_casesensitive, None) 276 | code = property(_get_code, _set_code, None) 277 | eightbit = property(_get_eightbit, _set_eightbit, None) 278 | hint = property(_get_hint, _set_hint, None) 279 | level = property(_get_level, _set_level, None) 280 | micro = property(_get_micro, _set_micro, None) 281 | version = property(_get_version, _set_version, None) 282 | 283 | 284 | class StructuredQREncoder(QREncoder): 285 | 286 | """Subclassing of QREncoder for structured QR encoding.""" 287 | 288 | def __init__(self): 289 | """Initialise object.""" 290 | super(StructuredQREncoder, self).__init__() 291 | self._code_list = [] # encoded result i.e. a QRcode_List c structure 292 | 293 | def encode(self, data): 294 | """Encode input string represented by data""" 295 | if self.version == 0: 296 | e = 'Version must be specified to encode structured symbols.' 297 | raise Error(e) 298 | elif self.micro: 299 | e = 'Micro QR Code does not support structured symbols.' 300 | raise Error(e) 301 | else: 302 | cdata = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte 303 | if self.eightbit else ctypes.c_char)) 304 | length = len(data) 305 | if self.eightbit: 306 | self.code_list = call(QRcode_encodeDataStructured, length, 307 | cdata, self.version, self.level) 308 | else: 309 | self.code_list = call(QRcode_encodeStringStructured, cdata, 310 | self.version, self.level, self.hint, 311 | self.casesensitive) 312 | def as2dlists(self): 313 | """Return a list of list of lists describing the encoded data.""" 314 | l = list() 315 | for code in self.code_list: 316 | self._code = code 317 | l.append(super(StructuredQREncoder, self).as2dlist()) 318 | return l 319 | 320 | def asciipreview(self): 321 | """Print an ascii representation of the Encoder output to stdout""" 322 | for code in self.code_list: 323 | self._code = code 324 | super(StructuredQREncoder, self).asciipreview() 325 | sys.stdout.write('\n') 326 | 327 | def asps(self): 328 | """Return a list of PostScript strings representing the encoded 329 | QRCode's of the StructuredQREncoder.""" 330 | l = list() 331 | for code in self.code_list: 332 | self._code = code 333 | l.append(super(StructuredQREncoder, self).asps()) 334 | return l 335 | 336 | def _get_code_list(self): 337 | """Return StructuredQREncoder's code_list.""" 338 | return self._code_list 339 | 340 | def _set_code_list(self, code_list): 341 | self._code_list = QRcode_List(code_list) 342 | 343 | code_list = property(_get_code_list, _set_code_list, None) 344 | 345 | 346 | def main(argv): 347 | import libqrencode 348 | version = libqrencode.version 349 | desc = """libqrencode ctypes python binding version %s, """ % version 350 | desc += """libqrencode version %s""" % QRcode_APIVersionString() 351 | usage = 'Usage: qrencode [OPTION]... [STRING]' 352 | p = optparse.OptionParser(description=desc, usage=usage) 353 | p.add_option('-o', '--filename', default=None, type='string', 354 | action='store', 355 | help='Encoded image filename (.png, .pdf, .jpg, .tif...)') 356 | p.add_option('-s', '--size', default=3, type='int', action='store', 357 | help='Specify module size in dots (pixels). (default=3)') 358 | p.add_option('-l', '--level', default='L', type='choice', action='store', 359 | choices=['L', 'M', 'Q', 'H'], 360 | help="""specify error correction level from L (lowest) to H 361 | (highest). (default=L)""") 362 | p.add_option('-v', '--symversion', default=0, type='int', action='store', 363 | help='specify the version of the symbol. (default=auto)') 364 | p.add_option('-m', '--margin', default=None, type='int', action='store', 365 | help="""specify the width of the margins. (default=4) 366 | (2 for Micro)))""") 367 | p.add_option('-d', '--dpi', default=72, type='int', action='store', 368 | help='specify the DPI of the generated PNG. (default=72)') 369 | p.add_option('-S', '--structured', default=False, action='store_true', 370 | help="""make structured symbols. Version must be 371 | specified.""") 372 | p.add_option('-k', '--kanji', default=False, action='store_true', 373 | help="""assume that the input text contains kanji 374 | (shift-jis).""") 375 | p.add_option('-c', '--casesensitive', default=True, action='store_false', 376 | help="""encode lower-case alphabet characters in 8-bit mode. 377 | (default)""") 378 | p.add_option('-8', '--eightbit', default=False, action='store_true', 379 | help="""encode entire data in 8-bit mode. -k and -c will be 380 | ignored.""") 381 | p.add_option('-M', '--micro', default=False, action='store_true', 382 | help="""encode in a Micro QR Code. (experimental).""") 383 | options, args = p.parse_args(argv[1:]) 384 | 385 | #set defaults and do error checking 386 | if options.margin is None: 387 | if options.micro: 388 | options.margin = 2 389 | else: 390 | options.margin = 4 391 | elif options.margin < 0: 392 | raise Error('Invalid margin: %d' % options.margin) 393 | if options.size <= 0: 394 | raise Error('Invalid size: %d' % options.size) 395 | if options.symversion < 0: 396 | raise Error('Invalid version: %d' % options.symversion) 397 | if options.level == 'L': 398 | options.level = QR_ECLEVEL_L 399 | elif options.level == 'M': 400 | options.level = QR_ECLEVEL_M 401 | elif options.level == 'Q': 402 | options.level = QR_ECLEVEL_Q 403 | elif options.level == 'H': 404 | options.level = QR_ECLEVEL_H 405 | if options.dpi < 0: 406 | raise Error('Invalid dpi: %d' % options.dpi) 407 | if options.kanji: 408 | options.kanji = QR_MODE_KANJI 409 | else: 410 | options.kanji = QR_MODE_8 411 | 412 | if args == []: 413 | string = sys.stdin.read() #read from stdin into string 414 | else: 415 | string = args[0] 416 | 417 | if not options.structured: 418 | encoder = QREncoder() 419 | else: 420 | encoder = StructuredQREncoder() 421 | 422 | #set properties of encoder 423 | encoder.casesensitive = options.casesensitive 424 | encoder.eightbit = options.eightbit 425 | encoder.hint = options.kanji 426 | encoder.level = options.level 427 | encoder.micro = options.micro 428 | encoder.version = options.symversion 429 | 430 | #encode 431 | encoder.encode(string) 432 | 433 | #next write output if required. 434 | if options.filename is None: 435 | encoder.asciipreview() #output to stdout 436 | else: 437 | try: 438 | from PIL import Image 439 | except Exception, e: 440 | e = 'Cannot write image %s, %s' % (options.filename, str(e)) 441 | print >> sys.stderr, e 442 | def saveimage(filename, qr): 443 | qrim = Image.new('1', (len(qr),)*2) 444 | qrim.putdata([0 if symbol else 1 for row in qr for symbol in row]) 445 | qrim = qrim.resize((len(qr)*options.size,)*2, Image.NEAREST) 446 | im = Image.new('1', tuple(s + 2*options.margin for s in qrim.size), 447 | color=1) 448 | im.paste(qrim, (options.margin,)*2) 449 | im = im.convert('RGB') 450 | im.save(filename, dpi=(options.dpi,)*2) 451 | if isinstance(encoder, (StructuredQREncoder)): 452 | i = 1 453 | for qr in encoder.as2dlists(): 454 | basename, ext = os.path.splitext(options.filename) 455 | saveimage(basename + str(i) + ext, qr) 456 | i += 1 457 | else: 458 | qr = encoder.as2dlist() 459 | saveimage(options.filename, qr) 460 | 461 | 462 | if __name__ == '__main__': 463 | main(sys.argv) 464 | -------------------------------------------------------------------------------- /libqrencode_ctypes_bindings/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | import libqrencode 3 | setup( 4 | name='libqrencode', 5 | description='Python ctypes libqrencode wrapper', 6 | provides=['qrencode'], 7 | requires=[], 8 | long_description= 9 | """ 10 | This package is a python ctypes wrapper for the libqrencode api 11 | http://fukuchi.org/works/qrencode/index.html.en 12 | """, 13 | version=libqrencode.version, 14 | packages=['libqrencode'], 15 | package_dir={'libqrencode': './libqrencode'}, 16 | url='http://matbaker.net', 17 | author='Matthew Baker', 18 | author_email='mu.beta.06@gmail.com', 19 | platforms='Linux', 20 | license='GNU Library or Lesser General Public License (LGPL)' 21 | ) 22 | -------------------------------------------------------------------------------- /signal_processing/README.md: -------------------------------------------------------------------------------- 1 | Signal Processing 2 | ================= 3 | 4 | Please refer to documentation here http://mubeta06.github.io/python/sp/ 5 | -------------------------------------------------------------------------------- /signal_processing/docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/SignalProcessingLibrary.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/SignalProcessingLibrary.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/SignalProcessingLibrary" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/SignalProcessingLibrary" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /signal_processing/docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Signal Processing Library documentation build configuration file, created by 4 | # sphinx-quickstart on Mon Jul 29 18:21:02 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | sys.path.insert(0, os.path.abspath('../../')) 20 | 21 | # -- General configuration ----------------------------------------------------- 22 | 23 | # If your documentation needs a minimal Sphinx version, state it here. 24 | #needs_sphinx = '1.0' 25 | 26 | # Add any Sphinx extension module names here, as strings. They can be extensions 27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 28 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode', 29 | 'matplotlib.sphinxext.mathmpl', 30 | 'matplotlib.sphinxext.only_directives', 31 | 'matplotlib.sphinxext.plot_directive'] 32 | 33 | # Add any paths that contain templates here, relative to this directory. 34 | templates_path = ['_templates'] 35 | 36 | # The suffix of source filenames. 37 | source_suffix = '.rst' 38 | 39 | # The encoding of source files. 40 | #source_encoding = 'utf-8-sig' 41 | 42 | # The master toctree document. 43 | master_doc = 'index' 44 | 45 | # General information about the project. 46 | project = u'Signal Processing Library' 47 | copyright = u'2013, Matthew Baker' 48 | 49 | # The version info for the project you're documenting, acts as replacement for 50 | # |version| and |release|, also used in various other places throughout the 51 | # built documents. 52 | # 53 | # The short X.Y version. 54 | version = '1.0' 55 | # The full version, including alpha/beta/rc tags. 56 | release = '1.0' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | #language = None 61 | 62 | # There are two options for replacing |today|: either, you set today to some 63 | # non-false value, then it is used: 64 | #today = '' 65 | # Else, today_fmt is used as the format for a strftime call. 66 | #today_fmt = '%B %d, %Y' 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | exclude_patterns = [] 71 | 72 | # The reST default role (used for this markup: `text`) to use for all documents. 73 | #default_role = None 74 | 75 | # If true, '()' will be appended to :func: etc. cross-reference text. 76 | #add_function_parentheses = True 77 | 78 | # If true, the current module name will be prepended to all description 79 | # unit titles (such as .. function::). 80 | #add_module_names = True 81 | 82 | # If true, sectionauthor and moduleauthor directives will be shown in the 83 | # output. They are ignored by default. 84 | #show_authors = False 85 | 86 | # The name of the Pygments (syntax highlighting) style to use. 87 | pygments_style = 'sphinx' 88 | 89 | # A list of ignored prefixes for module index sorting. 90 | #modindex_common_prefix = [] 91 | 92 | 93 | # -- Options for HTML output --------------------------------------------------- 94 | 95 | # The theme to use for HTML and HTML Help pages. See the documentation for 96 | # a list of builtin themes. 97 | html_theme = 'default' 98 | 99 | # Theme options are theme-specific and customize the look and feel of a theme 100 | # further. For a list of options available for each theme, see the 101 | # documentation. 102 | #html_theme_options = {} 103 | 104 | # Add any paths that contain custom themes here, relative to this directory. 105 | #html_theme_path = [] 106 | 107 | # The name for this set of Sphinx documents. If None, it defaults to 108 | # " v documentation". 109 | #html_title = None 110 | 111 | # A shorter title for the navigation bar. Default is the same as html_title. 112 | #html_short_title = None 113 | 114 | # The name of an image file (relative to this directory) to place at the top 115 | # of the sidebar. 116 | #html_logo = None 117 | 118 | # The name of an image file (within the static path) to use as favicon of the 119 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 120 | # pixels large. 121 | #html_favicon = None 122 | 123 | # Add any paths that contain custom static files (such as style sheets) here, 124 | # relative to this directory. They are copied after the builtin static files, 125 | # so a file named "default.css" will overwrite the builtin "default.css". 126 | html_static_path = ['_static'] 127 | 128 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 129 | # using the given strftime format. 130 | #html_last_updated_fmt = '%b %d, %Y' 131 | 132 | # If true, SmartyPants will be used to convert quotes and dashes to 133 | # typographically correct entities. 134 | #html_use_smartypants = True 135 | 136 | # Custom sidebar templates, maps document names to template names. 137 | #html_sidebars = {} 138 | 139 | # Additional templates that should be rendered to pages, maps page names to 140 | # template names. 141 | #html_additional_pages = {} 142 | 143 | # If false, no module index is generated. 144 | #html_domain_indices = True 145 | 146 | # If false, no index is generated. 147 | #html_use_index = True 148 | 149 | # If true, the index is split into individual pages for each letter. 150 | #html_split_index = False 151 | 152 | # If true, links to the reST sources are added to the pages. 153 | #html_show_sourcelink = True 154 | 155 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 156 | #html_show_sphinx = True 157 | 158 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 159 | #html_show_copyright = True 160 | 161 | # If true, an OpenSearch description file will be output, and all pages will 162 | # contain a tag referring to it. The value of this option must be the 163 | # base URL from which the finished HTML is served. 164 | #html_use_opensearch = '' 165 | 166 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 167 | #html_file_suffix = None 168 | 169 | # Output file base name for HTML help builder. 170 | htmlhelp_basename = 'SignalProcessingLibrarydoc' 171 | 172 | 173 | # -- Options for LaTeX output -------------------------------------------------- 174 | 175 | latex_elements = { 176 | # The paper size ('letterpaper' or 'a4paper'). 177 | #'papersize': 'letterpaper', 178 | 179 | # The font size ('10pt', '11pt' or '12pt'). 180 | #'pointsize': '10pt', 181 | 182 | # Additional stuff for the LaTeX preamble. 183 | #'preamble': '', 184 | } 185 | 186 | # Grouping the document tree into LaTeX files. List of tuples 187 | # (source start file, target name, title, author, documentclass [howto/manual]). 188 | latex_documents = [ 189 | ('index', 'SignalProcessingLibrary.tex', u'Signal Processing Library Documentation', 190 | u'Matthew Baker', 'manual'), 191 | ] 192 | 193 | # The name of an image file (relative to this directory) to place at the top of 194 | # the title page. 195 | #latex_logo = None 196 | 197 | # For "manual" documents, if this is true, then toplevel headings are parts, 198 | # not chapters. 199 | #latex_use_parts = False 200 | 201 | # If true, show page references after internal links. 202 | #latex_show_pagerefs = False 203 | 204 | # If true, show URL addresses after external links. 205 | #latex_show_urls = False 206 | 207 | # Documents to append as an appendix to all manuals. 208 | #latex_appendices = [] 209 | 210 | # If false, no module index is generated. 211 | #latex_domain_indices = True 212 | 213 | 214 | # -- Options for manual page output -------------------------------------------- 215 | 216 | # One entry per manual page. List of tuples 217 | # (source start file, name, description, authors, manual section). 218 | man_pages = [ 219 | ('index', 'signalprocessinglibrary', u'Signal Processing Library Documentation', 220 | [u'Matthew Baker'], 1) 221 | ] 222 | 223 | # If true, show URL addresses after external links. 224 | #man_show_urls = False 225 | 226 | 227 | # -- Options for Texinfo output ------------------------------------------------ 228 | 229 | # Grouping the document tree into Texinfo files. List of tuples 230 | # (source start file, target name, title, author, 231 | # dir menu entry, description, category) 232 | texinfo_documents = [ 233 | ('index', 'SignalProcessingLibrary', u'Signal Processing Library Documentation', 234 | u'Matthew Baker', 'SignalProcessingLibrary', 'One line description of project.', 235 | 'Miscellaneous'), 236 | ] 237 | 238 | # Documents to append as an appendix to all manuals. 239 | #texinfo_appendices = [] 240 | 241 | # If false, no module index is generated. 242 | #texinfo_domain_indices = True 243 | 244 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 245 | #texinfo_show_urls = 'footnote' 246 | -------------------------------------------------------------------------------- /signal_processing/docs/source/filter.rst: -------------------------------------------------------------------------------- 1 | 2 | sp.filter 3 | ========= 4 | 5 | .. automodule:: sp.filter 6 | 7 | Example Usage 8 | ^^^^^^^^^^^^^ 9 | :: 10 | 11 | TBD 12 | 13 | See the individual methods below for further details. 14 | 15 | Functions 16 | ^^^^^^^^^ 17 | 18 | .. autofunction:: sp.filter.cconv 19 | 20 | .. autofunction:: sp.filter.ccorr 21 | -------------------------------------------------------------------------------- /signal_processing/docs/source/firwin.rst: -------------------------------------------------------------------------------- 1 | 2 | sp.firwin 3 | ========= 4 | 5 | .. automodule:: sp.firwin 6 | 7 | Example Usage 8 | ^^^^^^^^^^^^^ 9 | 10 | Building a Lowpass Filter 11 | _________________________ 12 | 13 | :: 14 | 15 | import numpy 16 | import pylab 17 | 18 | from sp import firwin 19 | 20 | f0 = 20 #20Hz 21 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 22 | x = numpy.arange(-10, 10, ts) 23 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 24 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 25 | 26 | #build filter 27 | #Low pass 28 | M = 100 #number of taps in filter 29 | fc = 0.25 #i.e. normalised cutoff frequency 1/4 of sampling rate i.e. 25Hz 30 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 31 | 32 | #filter the signal 33 | filtered = numpy.convolve(signal, lp) 34 | 35 | #plotting 36 | pylab.figure() 37 | pylab.subplot(3,1,1) 38 | pylab.title('Original Spectrum') 39 | pylab.xlabel('Normalised Frequency') 40 | firwin.plot_fft(signal) 41 | pylab.subplot(3,1,2) 42 | pylab.title('Filter Frequency Response') 43 | pylab.xlabel('Normalised Frequency') 44 | firwin.plot_fft(lp) 45 | #window and fft 46 | pylab.subplot(3,1,3) 47 | pylab.title('Filtered Spectrum') 48 | pylab.xlabel('Normalised Frequency') 49 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 50 | pylab.subplots_adjust(hspace = 0.6) 51 | pylab.show() 52 | 53 | .. plot:: 54 | 55 | import numpy 56 | import pylab 57 | 58 | from sp import firwin 59 | 60 | f0 = 20 #20Hz 61 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 62 | x = numpy.arange(-10, 10, ts) 63 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 64 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 65 | 66 | #build filter 67 | #Low pass 68 | M = 100 #number of taps in filter 69 | fc = 0.25 #i.e. normalised cutoff frequency 1/4 of sampling rate i.e. 25Hz 70 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 71 | 72 | #filter the signal 73 | filtered = numpy.convolve(signal, lp) 74 | 75 | #plotting 76 | pylab.figure() 77 | pylab.subplot(3,1,1) 78 | pylab.title('Original Spectrum') 79 | pylab.xlabel('Normalised Frequency') 80 | firwin.plot_fft(signal) 81 | pylab.subplot(3,1,2) 82 | pylab.title('Filter Frequency Response') 83 | pylab.xlabel('Normalised Frequency') 84 | firwin.plot_fft(lp) 85 | #window and fft 86 | pylab.subplot(3,1,3) 87 | pylab.title('Filtered Spectrum') 88 | pylab.xlabel('Normalised Frequency') 89 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 90 | pylab.subplots_adjust(hspace = 0.6) 91 | pylab.show() 92 | 93 | Building a Highpass Filter 94 | __________________________ 95 | 96 | :: 97 | 98 | import numpy 99 | import pylab 100 | 101 | from sp import firwin 102 | 103 | f0 = 20 #20Hz 104 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 105 | x = numpy.arange(-10, 10, ts) 106 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 107 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 108 | 109 | #build filter 110 | #First build a Lowpass filter 111 | M = 100 #number of taps in filter 112 | fc = 0.25 #i.e. normalised cutoff frequency 1/4 of sampling rate i.e. 25Hz 113 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 114 | #next build Highpass filter by shifting frequency domain 115 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 116 | hp = lp*shift 117 | 118 | #filter the signal 119 | filtered = numpy.convolve(signal, hp) 120 | 121 | #plotting 122 | pylab.figure() 123 | pylab.subplot(3,1,1) 124 | pylab.title('Original Spectrum') 125 | pylab.xlabel('Normalised Frequency') 126 | firwin.plot_fft(signal) 127 | pylab.subplot(3,1,2) 128 | pylab.title('Filter Frequency Response') 129 | pylab.xlabel('Normalised Frequency') 130 | firwin.plot_fft(hp) 131 | #window and fft 132 | pylab.subplot(3,1,3) 133 | pylab.title('Filtered Spectrum') 134 | pylab.xlabel('Normalised Frequency') 135 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 136 | pylab.subplots_adjust(hspace = 0.6) 137 | pylab.show() 138 | 139 | .. plot:: 140 | 141 | import numpy 142 | import pylab 143 | 144 | from sp import firwin 145 | 146 | f0 = 20 #20Hz 147 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 148 | x = numpy.arange(-10, 10, ts) 149 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 150 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 151 | 152 | #build filter 153 | #First build a Lowpass filter 154 | M = 100 #number of taps in filter 155 | fc = 0.25 #i.e. normalised cutoff frequency 1/4 of sampling rate i.e. 25Hz 156 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 157 | #next build Highpass filter by shifting frequency domain 158 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 159 | hp = lp*shift 160 | 161 | #filter the signal 162 | filtered = numpy.convolve(signal, hp) 163 | 164 | #plotting 165 | pylab.figure() 166 | pylab.subplot(3,1,1) 167 | pylab.title('Original Spectrum') 168 | pylab.xlabel('Normalised Frequency') 169 | firwin.plot_fft(signal) 170 | pylab.subplot(3,1,2) 171 | pylab.title('Filter Frequency Response') 172 | pylab.xlabel('Normalised Frequency') 173 | firwin.plot_fft(hp) 174 | #window and fft 175 | pylab.subplot(3,1,3) 176 | pylab.title('Filtered Spectrum') 177 | pylab.xlabel('Normalised Frequency') 178 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 179 | pylab.subplots_adjust(hspace = 0.6) 180 | pylab.show() 181 | 182 | Building a Bandpass Filter 183 | __________________________ 184 | 185 | :: 186 | 187 | import numpy 188 | import pylab 189 | 190 | from sp import firwin 191 | 192 | f0 = 20 #20Hz 193 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 194 | x = numpy.arange(-10, 10, ts) 195 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 196 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 197 | 198 | #build filter 199 | #first need a low-pass with fc 0.35 200 | M = 100 #number of taps in filter 201 | fc = 0.35 202 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 203 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 204 | hp = lp*shift 205 | #now we can create the bandpass filter by convolution 206 | bp = numpy.convolve(lp, hp) 207 | 208 | #filter the signal 209 | filtered = numpy.convolve(signal, bp) 210 | 211 | #plotting 212 | pylab.figure() 213 | pylab.subplot(3,1,1) 214 | pylab.title('Original Spectrum') 215 | pylab.xlabel('Normalised Frequency') 216 | firwin.plot_fft(signal) 217 | pylab.subplot(3,1,2) 218 | pylab.title('Filter Frequency Response') 219 | pylab.xlabel('Normalised Frequency') 220 | firwin.plot_fft(bp) 221 | #window and fft 222 | pylab.subplot(3,1,3) 223 | pylab.title('Filtered Spectrum') 224 | pylab.xlabel('Normalised Frequency') 225 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 226 | pylab.subplots_adjust(hspace = 0.6) 227 | pylab.show() 228 | 229 | .. plot:: 230 | 231 | import numpy 232 | import pylab 233 | 234 | from sp import firwin 235 | 236 | f0 = 20 #20Hz 237 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 238 | x = numpy.arange(-10, 10, ts) 239 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 240 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 241 | 242 | #build filter 243 | #first need a low-pass with fc 0.35 244 | M = 100 #number of taps in filter 245 | fc = 0.35 246 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 247 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 248 | hp = lp*shift 249 | #now we can create the bandpass filter by convolution 250 | bp = numpy.convolve(lp, hp) 251 | 252 | #filter the signal 253 | filtered = numpy.convolve(signal, bp) 254 | 255 | #plotting 256 | pylab.figure() 257 | pylab.subplot(3,1,1) 258 | pylab.title('Original Spectrum') 259 | pylab.xlabel('Normalised Frequency') 260 | firwin.plot_fft(signal) 261 | pylab.subplot(3,1,2) 262 | pylab.title('Filter Frequency Response') 263 | pylab.xlabel('Normalised Frequency') 264 | firwin.plot_fft(bp) 265 | #window and fft 266 | pylab.subplot(3,1,3) 267 | pylab.title('Filtered Spectrum') 268 | pylab.xlabel('Normalised Frequency') 269 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 270 | pylab.subplots_adjust(hspace = 0.6) 271 | pylab.show() 272 | 273 | Building a Bandstop Filter 274 | __________________________ 275 | 276 | :: 277 | 278 | import numpy 279 | import pylab 280 | 281 | from sp import firwin 282 | 283 | f0 = 20 #20Hz 284 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 285 | x = numpy.arange(-10, 10, ts) 286 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 287 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 288 | 289 | #build filter 290 | #first need a low-pass with fc 0.15 291 | M = 100 #number of taps in filter 292 | fc = 0.15 293 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 294 | #next need a high-pass 295 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 296 | hp = lp*shift 297 | #now we can create the bandstop filter by adding the two impulse responses 298 | bs = lp + hp 299 | 300 | #filter the signal 301 | filtered = numpy.convolve(signal, bs) 302 | 303 | #plotting 304 | pylab.figure() 305 | pylab.subplot(3,1,1) 306 | pylab.title('Original Spectrum') 307 | pylab.xlabel('Normalised Frequency') 308 | firwin.plot_fft(signal) 309 | pylab.subplot(3,1,2) 310 | pylab.title('Filter Frequency Response') 311 | pylab.xlabel('Normalised Frequency') 312 | firwin.plot_fft(bs) 313 | #window and fft 314 | pylab.subplot(3,1,3) 315 | pylab.title('Filtered Spectrum') 316 | pylab.xlabel('Normalised Frequency') 317 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 318 | pylab.subplots_adjust(hspace = 0.6) 319 | pylab.show() 320 | 321 | .. plot:: 322 | 323 | import numpy 324 | import pylab 325 | 326 | from sp import firwin 327 | 328 | f0 = 20 #20Hz 329 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 330 | x = numpy.arange(-10, 10, ts) 331 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 332 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 333 | 334 | #build filter 335 | #first need a low-pass with fc 0.15 336 | M = 100 #number of taps in filter 337 | fc = 0.15 338 | lp = firwin.build_filter(M, fc, window=firwin.blackman) 339 | #next need a high-pass 340 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 341 | hp = lp*shift 342 | #now we can create the bandstop filter by adding the two impulse responses 343 | bs = lp + hp 344 | 345 | #filter the signal 346 | filtered = numpy.convolve(signal, bs) 347 | 348 | #plotting 349 | pylab.figure() 350 | pylab.subplot(3,1,1) 351 | pylab.title('Original Spectrum') 352 | pylab.xlabel('Normalised Frequency') 353 | firwin.plot_fft(signal) 354 | pylab.subplot(3,1,2) 355 | pylab.title('Filter Frequency Response') 356 | pylab.xlabel('Normalised Frequency') 357 | firwin.plot_fft(bs) 358 | #window and fft 359 | pylab.subplot(3,1,3) 360 | pylab.title('Filtered Spectrum') 361 | pylab.xlabel('Normalised Frequency') 362 | firwin.plot_fft(firwin.hamming(len(filtered))[:-1]*(filtered)) 363 | pylab.subplots_adjust(hspace = 0.6) 364 | pylab.show() 365 | 366 | See the individual methods below for further details. 367 | 368 | Functions 369 | ^^^^^^^^^ 370 | 371 | .. autofunction:: sp.firwin.blackman 372 | 373 | .. autofunction:: sp.firwin.build_filter 374 | 375 | .. autofunction:: sp.firwin.hamming 376 | 377 | .. autofunction:: sp.firwin.plot_fft 378 | 379 | .. autofunction:: sp.firwin.sinc_filter 380 | -------------------------------------------------------------------------------- /signal_processing/docs/source/gauss.rst: -------------------------------------------------------------------------------- 1 | sp.gauss 2 | ======== 3 | 4 | .. automodule:: sp.gauss 5 | 6 | Example Usage 7 | ^^^^^^^^^^^^^ 8 | 9 | fspecial_gauss / gaussian2 10 | __________________________ 11 | :: 12 | 13 | from mpl_toolkits.mplot3d.axes3d import Axes3D 14 | import pylab 15 | import numpy 16 | from sp import gauss 17 | size = 11 18 | sigma = 1.5 19 | x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 20 | 21 | fig = pylab.figure() 22 | fig.suptitle('Some 2-D Gauss Functions') 23 | ax = fig.add_subplot(2, 1, 1, projection='3d') 24 | ax.plot_surface(x, y, gauss.fspecial_gauss(size, sigma), rstride=1, 25 | cstride=1, linewidth=0, antialiased=False, cmap=pylab.jet()) 26 | ax = fig.add_subplot(2, 1, 2, projection='3d') 27 | ax.plot_surface(x, y, gauss.gaussian2(size, sigma), rstride=1, cstride=1, 28 | linewidth=0, antialiased=False, cmap=pylab.jet()) 29 | pylab.show() 30 | 31 | .. plot:: 32 | 33 | from mpl_toolkits.mplot3d.axes3d import Axes3D 34 | import pylab 35 | import numpy 36 | from sp import gauss 37 | size = 11 38 | sigma = 1.5 39 | x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 40 | 41 | fig = pylab.figure() 42 | fig.suptitle('Some 2-D Gauss Functions') 43 | ax = fig.add_subplot(2, 1, 1, projection='3d') 44 | ax.plot_surface(x, y, gauss.fspecial_gauss(size, sigma), rstride=1, 45 | cstride=1, linewidth=0, antialiased=False, cmap=pylab.jet()) 46 | ax = fig.add_subplot(2, 1, 2, projection='3d') 47 | ax.plot_surface(x, y, gauss.gaussian2(size, sigma), rstride=1, cstride=1, 48 | linewidth=0, antialiased=False, cmap=pylab.jet()) 49 | pylab.show() 50 | 51 | See the individual methods below for further details. 52 | 53 | Functions 54 | ^^^^^^^^^ 55 | 56 | .. autofunction:: sp.gauss.gaussian2 57 | 58 | .. autofunction:: sp.gauss.fspecial_gauss 59 | -------------------------------------------------------------------------------- /signal_processing/docs/source/gold.rst: -------------------------------------------------------------------------------- 1 | 2 | sp.gold 3 | ======= 4 | 5 | .. automodule:: sp.gold 6 | 7 | Example Usage 8 | ^^^^^^^^^^^^^ 9 | 10 | gold 11 | ____ 12 | 13 | :: 14 | 15 | import numpy 16 | import pylab 17 | from sp import mls 18 | from sp import filter 19 | nbits = 9 20 | m = mls.mls(nbits) 21 | pylab.figure() 22 | pylab.title('%d bit M-Sequence Periodic Autocorrelation' % nbits) 23 | m = numpy.where(m, 1.0, -1.0) 24 | pylab.plot((numpy.roll(filter.ccorr(m, m).real, 2**nbits/2 - 1))) 25 | pylab.xlim(0, len(m)) 26 | pylab.show() 27 | 28 | .. plot:: 29 | 30 | import numpy 31 | import pylab 32 | from sp import mls 33 | from sp import filter 34 | nbits = 9 35 | m = mls.mls(nbits) 36 | pylab.figure() 37 | pylab.title('%d bit M-Sequence Periodic Autocorrelation' % nbits) 38 | m = numpy.where(m, 1.0, -1.0) 39 | pylab.plot((numpy.roll(filter.ccorr(m, m).real, 2**nbits/2 - 1))) 40 | pylab.xlim(0, len(m)) 41 | pylab.show() 42 | 43 | See the individual methods below for further details. 44 | 45 | Functions 46 | ^^^^^^^^^ 47 | 48 | .. autofunction:: sp.gold.gold 49 | 50 | .. autofunction:: sp.gold.gen_gold 51 | 52 | -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/blur.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/blur.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/building.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/building.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/building_jpg.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/building_jpg.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/contrast.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/contrast.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/einstein.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/einstein.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/impulse.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/impulse.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/jpg.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/jpg.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/imgs/meanshift.tif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mubeta06/python/17438ce4914f09ca076aa89167f95ea775b411dd/signal_processing/docs/source/imgs/meanshift.tif -------------------------------------------------------------------------------- /signal_processing/docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. Signal Processing Library documentation master file, created by 2 | sphinx-quickstart on Mon Jul 29 18:21:02 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Signal Processing Library's documentation! 7 | ===================================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | filter 15 | firwin 16 | gauss 17 | gold 18 | mls 19 | multirate 20 | ssim 21 | 22 | Indices and tables 23 | ================== 24 | 25 | * :ref:`genindex` 26 | * :ref:`modindex` 27 | * :ref:`search` 28 | 29 | -------------------------------------------------------------------------------- /signal_processing/docs/source/mls.rst: -------------------------------------------------------------------------------- 1 | 2 | sp.mls 3 | ====== 4 | 5 | .. automodule:: sp.mls 6 | 7 | Example Usage 8 | ^^^^^^^^^^^^^ 9 | 10 | mls 11 | ___ 12 | 13 | :: 14 | 15 | import numpy 16 | import pylab 17 | from sp import mls 18 | from sp import filter 19 | nbits = 9 20 | m = mls.mls(nbits) 21 | pylab.figure() 22 | pylab.title('%d bit M-Sequence Periodic Autocorrelation' % nbits) 23 | m = numpy.where(m, 1.0, -1.0) 24 | pylab.plot((numpy.roll(filter.ccorr(m, m).real, 2**nbits/2 - 1))) 25 | pylab.xlim(0, len(m)) 26 | pylab.show() 27 | 28 | .. plot:: 29 | 30 | import numpy 31 | import pylab 32 | from sp import mls 33 | from sp import filter 34 | nbits = 9 35 | m = mls.mls(nbits) 36 | pylab.figure() 37 | pylab.title('%d bit M-Sequence Periodic Autocorrelation' % nbits) 38 | m = numpy.where(m, 1.0, -1.0) 39 | pylab.plot((numpy.roll(filter.ccorr(m, m).real, 2**nbits/2 - 1))) 40 | pylab.xlim(0, len(m)) 41 | pylab.show() 42 | 43 | See the individual methods below for further details. 44 | 45 | Functions 46 | ^^^^^^^^^ 47 | 48 | .. autofunction:: sp.mls.mls 49 | 50 | .. autofunction:: sp.mls.lfsr 51 | -------------------------------------------------------------------------------- /signal_processing/docs/source/multirate.rst: -------------------------------------------------------------------------------- 1 | sp.multirate 2 | ============ 3 | 4 | .. automodule:: sp.multirate 5 | 6 | Example Usage 7 | ^^^^^^^^^^^^^ 8 | 9 | downsample 10 | __________ 11 | 12 | >>> import numpy 13 | >>> from sp import multirate 14 | >>> x = numpy.arange(1, 11) 15 | >>> multirate.downsample(x, 3) 16 | array([ 1, 4, 7, 10]) 17 | >>> multirate.downsample(x, 3, phase=2) 18 | array([3, 6, 9]) 19 | 20 | upsample 21 | ________ 22 | 23 | >>> import numpy 24 | >>> from sp import multirate 25 | >>> x = numpy.arange(1, 5) 26 | >>> multirate.upsample(x, 3) 27 | array([ 1., 0., 0., 2., 0., 0., 3., 0., 0., 4., 0., 0.]) 28 | >>> multirate.upsample(x, 3, 2) 29 | array([ 0., 0., 1., 0., 0., 2., 0., 0., 3., 0., 0., 4.]) 30 | 31 | decimate 32 | ________ 33 | :: 34 | 35 | import numpy 36 | import pylab 37 | from sp import multirate 38 | t = numpy.arange(0, 1, 0.00025) 39 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 40 | y = multirate.decimate(x,4) 41 | pylab.figure() 42 | pylab.subplot(2, 1, 1) 43 | pylab.title('Original Signal') 44 | pylab.stem(numpy.arange(len(x[0:120])), x[0:120]) 45 | pylab.subplot(2, 1, 2) 46 | pylab.title('Decimated Signal') 47 | pylab.stem(numpy.arange(len(y[0:30])), y[0:30]) 48 | pylab.show() 49 | 50 | .. plot:: 51 | 52 | import numpy 53 | import pylab 54 | from sp import multirate 55 | t = numpy.arange(0, 1, 0.00025) 56 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 57 | y = multirate.decimate(x,4) 58 | pylab.figure() 59 | pylab.subplot(2, 1, 1) 60 | pylab.title('Original Signal') 61 | pylab.stem(numpy.arange(len(x[0:120])), x[0:120]) 62 | pylab.subplot(2, 1, 2) 63 | pylab.title('Decimated Signal') 64 | pylab.stem(numpy.arange(len(y[0:30])), y[0:30]) 65 | pylab.show() 66 | 67 | interp 68 | ________ 69 | :: 70 | 71 | import numpy 72 | import pylab 73 | from sp import multirate 74 | t = numpy.arange(0, 1, 0.001) 75 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 76 | y = interp(x,4) 77 | pylab.figure() 78 | pylab.subplot(2, 1, 1) 79 | pylab.title('Original Signal') 80 | pylab.stem(numpy.arange(len(x[0:30])), x[0:30]) 81 | pylab.subplot(2, 1, 2) 82 | pylab.title('Interpolated Signal') 83 | pylab.stem(numpy.arange(len(y[0:120])), y[0:120]) 84 | pylab.show() 85 | 86 | .. plot:: 87 | 88 | import numpy 89 | import pylab 90 | from sp import multirate 91 | t = numpy.arange(0, 1, 0.001) 92 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 93 | y = multirate.interp(x,4) 94 | pylab.figure() 95 | pylab.subplot(2, 1, 1) 96 | pylab.title('Original Signal') 97 | pylab.stem(numpy.arange(len(x[0:30])), x[0:30]) 98 | pylab.subplot(2, 1, 2) 99 | pylab.title('Interpolated Signal') 100 | pylab.stem(numpy.arange(len(y[0:120])), y[0:120]) 101 | pylab.show() 102 | 103 | upfirdn 104 | ________ 105 | :: 106 | 107 | import numpy 108 | import pylab 109 | from sp import multirate 110 | L = 147.0 111 | M = 160.0 112 | N = 24.0*L 113 | h = signal.firwin(N-1, 1/M, window=('kaiser', 7.8562)) 114 | h = L*h 115 | Fs = 48000.0 116 | n = numpy.arange(0, 10239) 117 | x = numpy.sin(2*numpy.pi*1000/Fs*n) 118 | y = multirate.upfirdn(x, h, L, M) 119 | pylab.figure() 120 | pylab.stem(n[1:49]/Fs, x[1:49]) 121 | pylab.stem(n[1:45]/(Fs*L/M), y[13:57], 'r', markerfmt='ro',) 122 | pylab.xlabel('Time (sec)') 123 | pylab.ylabel('Signal value') 124 | pylab.show() 125 | 126 | .. plot:: 127 | 128 | import numpy 129 | import pylab 130 | from scipy import signal 131 | from sp import multirate 132 | L = 147.0 133 | M = 160.0 134 | N = 24.0*L 135 | h = signal.firwin(N-1, 1/M, window=('kaiser', 7.8562)) 136 | h = L*h 137 | Fs = 48000.0 138 | n = numpy.arange(0, 10239) 139 | x = numpy.sin(2*numpy.pi*1000/Fs*n) 140 | y = multirate.upfirdn(x, h, L, M) 141 | pylab.figure() 142 | pylab.stem(n[1:49]/Fs, x[1:49]) 143 | pylab.stem(n[1:45]/(Fs*L/M), y[13:57], 'r', markerfmt='ro',) 144 | pylab.xlabel('Time (sec)') 145 | pylab.ylabel('Signal value') 146 | pylab.show() 147 | 148 | resample 149 | ________ 150 | :: 151 | 152 | import numpy 153 | import pylab 154 | from sp import multirate 155 | fs1 = 10.0 156 | t1 = numpy.arange(0, 1 + 1.0/fs1, 1.0/fs1) 157 | x = t1 158 | y = multirate.resample(x, 3, 2) 159 | t2 = numpy.arange(0,(len(y)))*2.0/(3.0*fs1) 160 | pylab.figure() 161 | pylab.plot(t1, x, '*') 162 | pylab.plot(t2, y, 'o') 163 | pylab.plot(numpy.arange(-0.5,1.5, 0.01), numpy.arange(-0.5,1.5, 0.01), ':') 164 | pylab.legend(('original','resampled'), numpoints=1) 165 | pylab.xlabel('Time') 166 | pylab.show() 167 | 168 | .. plot:: 169 | 170 | import numpy 171 | import pylab 172 | from sp import multirate 173 | fs1 = 10.0 174 | t1 = numpy.arange(0, 1 + 1.0/fs1, 1.0/fs1) 175 | x = t1 176 | y = multirate.resample(x, 3, 2) 177 | t2 = numpy.arange(0,(len(y)))*2.0/(3.0*fs1) 178 | pylab.figure() 179 | pylab.plot(t1, x, '*') 180 | pylab.plot(t2, y, 'o') 181 | pylab.plot(numpy.arange(-0.5,1.5, 0.01), numpy.arange(-0.5,1.5, 0.01), ':') 182 | pylab.legend(('original','resampled'), numpoints=1) 183 | pylab.xlabel('Time') 184 | pylab.show() 185 | 186 | :: 187 | 188 | import numpy 189 | import pylab 190 | from sp import multirate 191 | x = numpy.hstack([numpy.arange(1,11), numpy.arange(9,0,-1)]) 192 | y = multirate.resample(x,3,2) 193 | pylab.figure() 194 | pylab.subplot(2, 1, 1) 195 | pylab.title('Edge Effects Not Noticeable') 196 | pylab.plot(numpy.arange(19)+1, x, '*') 197 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 198 | pylab.legend(('original', 'resampled'), numpoints=1) 199 | x = numpy.hstack([numpy.arange(10, 0, -1), numpy.arange(2,11)]) 200 | y = multirate.resample(x,3,2) 201 | pylab.subplot(2, 1, 2) 202 | pylab.plot(numpy.arange(19)+1, x, '*') 203 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 204 | pylab.title('Edge Effects Very Noticeable') 205 | pylab.legend(('original', 'resampled'), numpoints=1) 206 | pylab.show() 207 | 208 | .. plot:: 209 | 210 | import numpy 211 | import pylab 212 | from sp import multirate 213 | x = numpy.hstack([numpy.arange(1,11), numpy.arange(9,0,-1)]) 214 | y = multirate.resample(x,3,2) 215 | pylab.figure() 216 | pylab.subplot(2, 1, 1) 217 | pylab.title('Edge Effects Not Noticeable') 218 | pylab.plot(numpy.arange(19)+1, x, '*') 219 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 220 | pylab.legend(('original', 'resampled'), numpoints=1) 221 | x = numpy.hstack([numpy.arange(10, 0, -1), numpy.arange(2,11)]) 222 | y = multirate.resample(x,3,2) 223 | pylab.subplot(2, 1, 2) 224 | pylab.plot(numpy.arange(19)+1, x, '*') 225 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 226 | pylab.title('Edge Effects Very Noticeable') 227 | pylab.legend(('original', 'resampled'), numpoints=1) 228 | pylab.show() 229 | 230 | See the individual methods below for further details. 231 | 232 | Functions 233 | ^^^^^^^^^ 234 | 235 | .. autofunction:: sp.multirate.downsample 236 | 237 | .. autofunction:: sp.multirate.upsample 238 | 239 | .. autofunction:: sp.multirate.decimate 240 | 241 | .. autofunction:: sp.multirate.interp 242 | 243 | .. autofunction:: sp.multirate.upfirdn 244 | 245 | .. autofunction:: sp.multirate.resample 246 | -------------------------------------------------------------------------------- /signal_processing/docs/source/ssim.rst: -------------------------------------------------------------------------------- 1 | 2 | sp.ssim 3 | ======= 4 | 5 | .. automodule:: sp.ssim 6 | 7 | Example Usage 8 | ^^^^^^^^^^^^^ 9 | 10 | ssim 11 | ____ 12 | 13 | :: 14 | 15 | import pylab 16 | import numpy 17 | from sp import ssim 18 | from PIL import Image 19 | einstein = numpy.asarray(Image.open('./imgs/einstein.tif')) 20 | meanshift = numpy.asarray(Image.open('./imgs/meanshift.tif')) 21 | contrast = numpy.asarray(Image.open('./imgs/contrast.tif')) 22 | impulse = numpy.asarray(Image.open('./imgs/impulse.tif')) 23 | blur = numpy.asarray(Image.open('./imgs/blur.tif')) 24 | jpg = numpy.asarray(Image.open('./imgs/jpg.tif')) 25 | einstein_ssim = ssim.ssim(einstein, einstein) 26 | meanshift_ssim = ssim.ssim(einstein, meanshift) 27 | contrast_ssim = ssim.ssim(einstein, contrast) 28 | impulse_ssim = ssim.ssim(einstein, impulse) 29 | blur_ssim = ssim.ssim(einstein, blur) 30 | jpg_ssim = ssim.ssim(einstein, jpg) 31 | pylab.figure() 32 | pylab.subplot(2, 3, 1) 33 | pylab.title('Original\n SSIM %.3f' % einstein_ssim.mean()) 34 | pylab.imshow(einstein, cmap=pylab.gray()) 35 | pylab.subplot(2, 3, 2) 36 | pylab.title('Mean-Shifted\n SSIM %.3f' % meanshift_ssim.mean()) 37 | pylab.imshow(meanshift, cmap=pylab.gray()) 38 | pylab.subplot(2, 3, 3) 39 | pylab.title('Contrast-Adjusted\n SSIM %.3f' % contrast_ssim.mean()) 40 | pylab.imshow(contrast, cmap=pylab.gray()) 41 | pylab.subplot(2, 3, 4) 42 | pylab.title('Impulse-Noise\n SSIM %.3f' % impulse_ssim.mean()) 43 | pylab.imshow(impulse, cmap=pylab.gray()) 44 | pylab.subplot(2, 3, 5) 45 | pylab.title('Blur\n SSIM %.3f' % blur_ssim.mean()) 46 | pylab.imshow(blur, cmap=pylab.gray()) 47 | pylab.subplot(2, 3, 6) 48 | pylab.title('JPG\n SSIM %.3f' % jpg_ssim.mean()) 49 | pylab.imshow(jpg, cmap=pylab.gray()) 50 | pylab.show() 51 | 52 | .. plot:: 53 | 54 | import pylab 55 | import numpy 56 | from sp import ssim 57 | from PIL import Image 58 | einstein = numpy.asarray(Image.open('./imgs/einstein.tif')) 59 | meanshift = numpy.asarray(Image.open('./imgs/meanshift.tif')) 60 | contrast = numpy.asarray(Image.open('./imgs/contrast.tif')) 61 | impulse = numpy.asarray(Image.open('./imgs/impulse.tif')) 62 | blur = numpy.asarray(Image.open('./imgs/blur.tif')) 63 | jpg = numpy.asarray(Image.open('./imgs/jpg.tif')) 64 | einstein_ssim = ssim.ssim(einstein, einstein) 65 | meanshift_ssim = ssim.ssim(einstein, meanshift) 66 | contrast_ssim = ssim.ssim(einstein, contrast) 67 | impulse_ssim = ssim.ssim(einstein, impulse) 68 | blur_ssim = ssim.ssim(einstein, blur) 69 | jpg_ssim = ssim.ssim(einstein, jpg) 70 | pylab.figure() 71 | pylab.subplot(2, 3, 1) 72 | pylab.title('Original\n SSIM %.3f' % einstein_ssim.mean()) 73 | pylab.imshow(einstein, cmap=pylab.gray()) 74 | pylab.subplot(2, 3, 2) 75 | pylab.title('Mean-Shifted\n SSIM %.3f' % meanshift_ssim.mean()) 76 | pylab.imshow(meanshift, cmap=pylab.gray()) 77 | pylab.subplot(2, 3, 3) 78 | pylab.title('Contrast-Adjusted\n SSIM %.3f' % contrast_ssim.mean()) 79 | pylab.imshow(contrast, cmap=pylab.gray()) 80 | pylab.subplot(2, 3, 4) 81 | pylab.title('Impulse-Noise\n SSIM %.3f' % impulse_ssim.mean()) 82 | pylab.imshow(impulse, cmap=pylab.gray()) 83 | pylab.subplot(2, 3, 5) 84 | pylab.title('Blur\n SSIM %.3f' % blur_ssim.mean()) 85 | pylab.imshow(blur, cmap=pylab.gray()) 86 | pylab.subplot(2, 3, 6) 87 | pylab.title('JPG\n SSIM %.3f' % jpg_ssim.mean()) 88 | pylab.imshow(jpg, cmap=pylab.gray()) 89 | pylab.show() 90 | 91 | :: 92 | 93 | import numpy 94 | import pylab 95 | from sp import ssim 96 | from PIL import Image 97 | original = numpy.asarray(Image.open('./imgs/building.tif')) 98 | jpg = numpy.asarray(Image.open('./imgs/building_jpg.tif')) 99 | ssim_map = ssim.ssim(original, jpg) 100 | abs_map = numpy.abs(original.astype('float64')-jpg.astype('float64')) 101 | pylab.figure() 102 | pylab.subplot(2, 2, 1) 103 | pylab.title('Original') 104 | pylab.imshow(original, cmap=pylab.gray()) 105 | pylab.subplot(2, 2, 2) 106 | pylab.title('JPEG compressed') 107 | pylab.imshow(jpg, cmap=pylab.gray()) 108 | pylab.subplot(2, 2, 3) 109 | pylab.title('Absolute error map') 110 | pylab.imshow(abs_map.astype('uint8'), cmap=pylab.gray()) 111 | pylab.subplot(2, 2, 4) 112 | pylab.title('SSIM index map') 113 | pylab.imshow(ssim_map, cmap=pylab.gray()) 114 | pylab.show() 115 | 116 | .. plot:: 117 | 118 | import numpy 119 | import pylab 120 | from sp import ssim 121 | from PIL import Image 122 | original = numpy.asarray(Image.open('./imgs/building.tif')) 123 | jpg = numpy.asarray(Image.open('./imgs/building_jpg.tif')) 124 | ssim_map = ssim.ssim(original, jpg) 125 | abs_map = numpy.abs(original.astype('float64')-jpg.astype('float64')) 126 | pylab.figure() 127 | pylab.subplot(2, 2, 1) 128 | pylab.title('Original') 129 | pylab.imshow(original, cmap=pylab.gray()) 130 | pylab.subplot(2, 2, 2) 131 | pylab.title('JPEG compressed') 132 | pylab.imshow(jpg, cmap=pylab.gray()) 133 | pylab.subplot(2, 2, 3) 134 | pylab.title('Absolute error map') 135 | pylab.imshow(abs_map.astype('uint8'), cmap=pylab.gray()) 136 | pylab.subplot(2, 2, 4) 137 | pylab.title('SSIM index map') 138 | pylab.imshow(ssim_map, cmap=pylab.gray()) 139 | pylab.show() 140 | 141 | msssim 142 | ______ 143 | 144 | :: 145 | 146 | import numpy 147 | import pylab 148 | from sp import ssim 149 | from PIL import Image 150 | einstein = numpy.asarray(Image.open('./imgs/einstein.tif')) 151 | impulse = numpy.asarray(Image.open('./imgs/impulse.tif')) 152 | ms_ssim = ssim.msssim(original, impulse) 153 | pylab.figure() 154 | pylab.subplot(1, 2, 1) 155 | pylab.title('Original') 156 | pylab.imshow(original, cmap=pylab.gray()) 157 | pylab.subplot(1, 2, 2) 158 | pylab.title('Impulse-Noise\n %.3f' % ms_ssim) 159 | pylab.imshow(impulse, cmap=pylab.gray()) 160 | pylab.show() 161 | 162 | .. plot:: 163 | 164 | import numpy 165 | import pylab 166 | from sp import ssim 167 | from PIL import Image 168 | einstein = numpy.asarray(Image.open('./imgs/einstein.tif')) 169 | impulse = numpy.asarray(Image.open('./imgs/impulse.tif')) 170 | ms_ssim = ssim.msssim(einstein, impulse) 171 | pylab.figure() 172 | pylab.subplot(1, 2, 1) 173 | pylab.title('Original') 174 | pylab.imshow(einstein, cmap=pylab.gray()) 175 | pylab.subplot(1, 2, 2) 176 | pylab.title('Impulse-Noise\n MSSSIM %.3f' % ms_ssim) 177 | pylab.imshow(impulse, cmap=pylab.gray()) 178 | pylab.show() 179 | 180 | See the individual methods below for further details. 181 | 182 | Functions 183 | ^^^^^^^^^ 184 | 185 | .. autofunction:: sp.ssim.ssim 186 | 187 | .. autofunction:: sp.ssim.msssim 188 | -------------------------------------------------------------------------------- /signal_processing/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | import sp 3 | setup( 4 | name='sp', 5 | description='Python Signal Processing Library', 6 | provides=[], 7 | requires=[], 8 | long_description= 9 | """ 10 | This package contains various Signal Processing modules. 11 | """, 12 | version=sp.version, 13 | packages=['sp'], 14 | package_dir={'sp': './sp'}, 15 | url='http://matbaker.net', 16 | author='Matthew Baker', 17 | author_email='mu.beta.06@gmail.com', 18 | platforms='Linux', 19 | license='GNU Library or Lesser General Public License (LGPL)' 20 | ) 21 | -------------------------------------------------------------------------------- /signal_processing/sp/__init__.py: -------------------------------------------------------------------------------- 1 | version = 1.0 2 | 3 | 4 | def iterchannels(img): 5 | """Convenience routine to allow iteration through the channels of a numpy 6 | ndarray that represents an image. 7 | """ 8 | return [img] if img.ndim == 2 else img.transpose(2, 0 , 1) 9 | 10 | 11 | def channels(img): 12 | """Convenience routine to return a list of the channels of an numpy ndarray 13 | that represents an image. 14 | """ 15 | return [c for c in iterchannels(img)] 16 | -------------------------------------------------------------------------------- /signal_processing/sp/filter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module to provide filter functions for data, etc. 3 | 4 | """ 5 | 6 | from numpy import fft 7 | 8 | def cconv(x, y): 9 | """Calculate the circular convolution of 1-D input numpy arrays using DFT 10 | """ 11 | return fft.ifft(fft.fft(x)*fft.fft(y)) 12 | 13 | def ccorr(x, y): 14 | """Calculate the circular correlation of 1-D input numpy arrays using DFT 15 | """ 16 | return fft.ifft(fft.fft(x)*fft.fft(y).conj()) 17 | 18 | -------------------------------------------------------------------------------- /signal_processing/sp/firwin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module to design window based fir filter and analyse the frequency response 3 | of fir filters. 4 | 5 | This implementation is largely based on Chapter 16 of The Scientist and 6 | Engineer's Guide to Digital Signal Processing Second Edition. 7 | 8 | """ 9 | 10 | import pylab 11 | import numpy 12 | 13 | def hamming(M): 14 | """Return an M + 1 point symmetric hamming window.""" 15 | if M%2: 16 | raise Exception('M must be even') 17 | return 0.54 - 0.46*numpy.cos(2*numpy.pi*numpy.arange(M + 1)/M) 18 | 19 | def blackman(M): 20 | """Return an M + 1 point symmetric point hamming window.""" 21 | if M%2: 22 | raise Exception('M must be even') 23 | return (0.42 - 0.5*numpy.cos(2*numpy.pi*numpy.arange(M + 1)/M) + 24 | 0.08*numpy.cos(4*numpy.pi*numpy.arange(M + 1)/M)) 25 | 26 | def sinc_filter(M, fc): 27 | """Return an M + 1 point symmetric point sinc kernel with normalised cut-off 28 | frequency fc 0->0.5.""" 29 | if M%2: 30 | raise Exception('M must be even') 31 | return numpy.sinc(2*fc*(numpy.arange(M + 1) - M/2)) 32 | 33 | def plot_fft(x, style='b'): 34 | """Convenience routine for plotting fft's of signal with normalised 35 | frequency axis.""" 36 | pylab.plot(numpy.arange(len(x))/float(len(x)), numpy.abs(numpy.fft.fft(x)) 37 | , style) 38 | 39 | def build_filter(M, fc, window=None): 40 | """Construct filter using the windowing method for filter parameters M 41 | number of taps, cut-off frequency fc and window. Window defaults to None 42 | i.e. a rectangular window.""" 43 | if window is None: 44 | h = sinc_filter(M, fc) 45 | else: 46 | h = sinc_filter(M, fc)*window(M) 47 | return h/h.sum() 48 | 49 | def main(): 50 | f0 = 20 #20Hz 51 | ts = 0.01 # i.e. sampling frequency is 1/ts = 100Hz 52 | x = numpy.arange(-10, 10, ts) 53 | signal = (numpy.cos(2*numpy.pi*f0*x) + numpy.sin(2*numpy.pi*2*f0*x) + 54 | numpy.cos(2*numpy.pi*0.5*f0*x) + numpy.cos(2*numpy.pi*1.5*f0*x)) 55 | 56 | #build up some filters 57 | #Low pass 58 | M = 100 #number of taps in filter 59 | fc = 0.25 #i.e. normalised cutoff frequency 1/4 of sampling rate i.e. 25Hz 60 | ham_lp = build_filter(M, fc, window=hamming) 61 | black_lp = build_filter(M, fc, window=blackman) 62 | rect_lp = build_filter(M, fc) 63 | 64 | #filter the signals 65 | f_ham = numpy.convolve(signal, ham_lp) 66 | f_black = numpy.convolve(signal, black_lp) 67 | f_rect = numpy.convolve(signal, rect_lp) 68 | 69 | #plotting 70 | pylab.figure() 71 | pylab.subplot(3,1,1) 72 | pylab.title('Original Spectrum') 73 | pylab.xlabel('Normalised Frequency') 74 | plot_fft(signal) 75 | pylab.subplot(3,1,2) 76 | pylab.title('Lowpass Filter Frequency Response') 77 | pylab.xlabel('Normalised Frequency') 78 | plot_fft(ham_lp) 79 | plot_fft(black_lp, style='k') 80 | plot_fft(rect_lp, style='r') 81 | pylab.legend(('Hamming', 'Blackman', 'Rectangular')) 82 | #window and fft 83 | pylab.subplot(3,1,3) 84 | pylab.title('Filtered Spectrum') 85 | pylab.xlabel('Normalised Frequency') 86 | plot_fft(hamming(len(f_ham))[:-1]*(f_ham)) 87 | plot_fft(hamming(len(f_black))[:-1]*(f_black), 'k') 88 | plot_fft(hamming(len(f_rect))[:-1]*(f_rect), 'r') 89 | pylab.subplots_adjust(hspace = 0.6) 90 | 91 | #High Pass 92 | shift = numpy.cos(2*numpy.pi*0.5*numpy.arange(M + 1)) 93 | ham_hp = ham_lp*shift 94 | black_hp = black_lp*shift 95 | rect_hp = rect_lp*shift 96 | 97 | #filter the signals 98 | f_ham = numpy.convolve(signal, ham_hp) 99 | f_black = numpy.convolve(signal, black_hp) 100 | f_rect = numpy.convolve(signal, rect_hp) 101 | 102 | #plotting 103 | pylab.figure() 104 | pylab.subplot(3,1,1) 105 | pylab.title('Original Spectrum') 106 | pylab.xlabel('Normalised Frequency') 107 | plot_fft(signal) 108 | pylab.subplot(3,1,2) 109 | pylab.title('Highpass Filter Frequency Response') 110 | pylab.xlabel('Normalised Frequency') 111 | plot_fft(ham_hp) 112 | plot_fft(black_hp, style='k') 113 | plot_fft(rect_hp, style='r') 114 | pylab.legend(('Hamming', 'Blackman', 'Rectangular')) 115 | #window and fft 116 | pylab.subplot(3,1,3) 117 | pylab.title('Filtered Spectrum') 118 | pylab.xlabel('Normalised Frequency') 119 | plot_fft(hamming(len(f_ham))[:-1]*(f_ham)) 120 | plot_fft(hamming(len(f_black))[:-1]*(f_black), 'k') 121 | plot_fft(hamming(len(f_rect))[:-1]*(f_rect), 'r') 122 | pylab.subplots_adjust(hspace = 0.6) 123 | 124 | #Bandpass 125 | #first need a low-pass with fc 0.35 126 | fc = 0.35 127 | ham_lp = build_filter(M, fc, window=hamming) 128 | black_lp = build_filter(M, fc, window=blackman) 129 | rect_lp = build_filter(M, fc) 130 | ham_hp = ham_lp*shift 131 | black_hp = black_lp*shift 132 | rect_hp = rect_lp*shift 133 | #now we can create the bandpass filter 134 | ham_bp = numpy.convolve(ham_lp, ham_hp) 135 | black_bp = numpy.convolve(black_lp, black_hp) 136 | rect_bp = numpy.convolve(rect_lp, rect_hp) 137 | 138 | #filter the signals 139 | f_ham = numpy.convolve(signal, ham_bp) 140 | f_black = numpy.convolve(signal, black_bp) 141 | f_rect = numpy.convolve(signal, rect_bp) 142 | 143 | #plotting 144 | pylab.figure() 145 | pylab.subplot(3,1,1) 146 | pylab.title('Original Spectrum') 147 | pylab.xlabel('Normalised Frequency') 148 | plot_fft(signal) 149 | pylab.subplot(3,1,2) 150 | pylab.title('Bandpass Filter Frequency Response') 151 | pylab.xlabel('Normalised Frequency') 152 | plot_fft(ham_bp) 153 | plot_fft(black_bp, style='k') 154 | plot_fft(rect_bp, style='r') 155 | pylab.legend(('Hamming', 'Blackman', 'Rectangular')) 156 | #window and fft 157 | pylab.subplot(3,1,3) 158 | pylab.title('Filtered Spectrum') 159 | pylab.xlabel('Normalised Frequency') 160 | plot_fft(hamming(len(f_ham))[:-1]*(f_ham)) 161 | plot_fft(hamming(len(f_black))[:-1]*(f_black), 'k') 162 | plot_fft(hamming(len(f_rect))[:-1]*(f_rect), 'r') 163 | pylab.subplots_adjust(hspace = 0.6) 164 | 165 | #Bandstop 166 | #first need a low-pass with fc 0.15 167 | fc = 0.15 168 | ham_lp = build_filter(M, fc, window=hamming) 169 | black_lp = build_filter(M, fc, window=blackman) 170 | rect_lp = build_filter(M, fc) 171 | #next need a high-pass 172 | ham_hp = ham_lp*shift 173 | black_hp = black_lp*shift 174 | rect_hp = rect_lp*shift 175 | #now we can create the bandstop filter 176 | ham_bs = ham_lp + ham_hp 177 | black_bs = black_lp + black_hp 178 | rect_bs = rect_lp + rect_hp 179 | 180 | #filter the signals 181 | f_ham = numpy.convolve(signal, ham_bs) 182 | f_black = numpy.convolve(signal, black_bs) 183 | f_rect = numpy.convolve(signal, rect_bs) 184 | 185 | #plotting 186 | pylab.figure() 187 | pylab.subplot(3,1,1) 188 | pylab.title('Original Spectrum') 189 | pylab.xlabel('Normalised Frequency') 190 | plot_fft(signal) 191 | pylab.subplot(3,1,2) 192 | pylab.title('Bandstop Filter Frequency Response') 193 | pylab.xlabel('Normalised Frequency') 194 | plot_fft(ham_bs) 195 | plot_fft(black_bs, style='k') 196 | plot_fft(rect_bs, style='r') 197 | pylab.legend(('Hamming', 'Blackman', 'Rectangular')) 198 | #window and fft 199 | pylab.subplot(3,1,3) 200 | pylab.title('Filtered Spectrum') 201 | pylab.xlabel('Normalised Frequency') 202 | plot_fft(hamming(len(f_ham))[:-1]*(f_ham)) 203 | plot_fft(hamming(len(f_black))[:-1]*(f_black), 'k') 204 | plot_fft(hamming(len(f_rect))[:-1]*(f_rect), 'r') 205 | pylab.subplots_adjust(hspace = 0.6) 206 | 207 | pylab.show() 208 | 209 | if __name__ == '__main__': 210 | main() -------------------------------------------------------------------------------- /signal_processing/sp/gauss.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module providing functionality surrounding gaussian function. 3 | """ 4 | SVN_REVISION = '$LastChangedRevision: 16541 $' 5 | 6 | import sys 7 | import numpy 8 | 9 | def gaussian2(size, sigma): 10 | """Returns a normalized circularly symmetric 2D gauss kernel array 11 | 12 | f(x,y) = A.e^{-(x^2/2*sigma^2 + y^2/2*sigma^2)} where 13 | 14 | A = 1/(2*pi*sigma^2) 15 | 16 | as define by Wolfram Mathworld 17 | http://mathworld.wolfram.com/GaussianFunction.html 18 | """ 19 | A = 1/(2.0*numpy.pi*sigma**2) 20 | x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 21 | g = A*numpy.exp(-((x**2/(2.0*sigma**2))+(y**2/(2.0*sigma**2)))) 22 | return g 23 | 24 | def fspecial_gauss(size, sigma): 25 | """Function to mimic the 'fspecial' gaussian MATLAB function 26 | """ 27 | x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 28 | g = numpy.exp(-((x**2 + y**2)/(2.0*sigma**2))) 29 | return g/g.sum() 30 | 31 | def main(): 32 | """Show simple use cases for functionality provided by this module.""" 33 | from mpl_toolkits.mplot3d.axes3d import Axes3D 34 | import pylab 35 | argv = sys.argv 36 | if len(argv) != 3: 37 | print >>sys.stderr, 'usage: python -m pim.sp.gauss size sigma' 38 | sys.exit(2) 39 | size = int(argv[1]) 40 | sigma = float(argv[2]) 41 | x, y = numpy.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] 42 | 43 | fig = pylab.figure() 44 | fig.suptitle('Some 2-D Gauss Functions') 45 | ax = fig.add_subplot(2, 1, 1, projection='3d') 46 | ax.plot_surface(x, y, fspecial_gauss(size, sigma), rstride=1, cstride=1, 47 | linewidth=0, antialiased=False, cmap=pylab.jet()) 48 | ax = fig.add_subplot(2, 1, 2, projection='3d') 49 | ax.plot_surface(x, y, gaussian2(size, sigma), rstride=1, cstride=1, 50 | linewidth=0, antialiased=False, cmap=pylab.jet()) 51 | pylab.show() 52 | return 0 53 | 54 | if __name__ == '__main__': 55 | sys.exit(main()) -------------------------------------------------------------------------------- /signal_processing/sp/gold.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Module providing the functionality to generate Gold Codes / Sequences 4 | """ 5 | 6 | import numpy 7 | import pylab 8 | 9 | import filter 10 | import mls 11 | 12 | 13 | preferred_pairs = {5:[[2],[1,2,3]], 6:[[5],[1,4,5]], 7:[[4],[4,5,6]], 14 | 8:[[1,2,3,6,7],[1,2,7]], 9:[[5],[3,5,6]], 15 | 10:[[2,5,9],[3,4,6,8,9]], 11:[[9],[3,6,9]]} 16 | 17 | 18 | def gen_gold(seq1, seq2): 19 | """Function to produce a gold sequence based on two input preferred pair 20 | Maximal Length Sequences 21 | """ 22 | gold = [seq1, seq2] 23 | for shift in range(len(seq1)): 24 | gold.append(numpy.logical_xor(seq1, numpy.roll(seq2, -shift))) 25 | return gold 26 | 27 | 28 | def gold(n): 29 | """Generate a set of 2^n +1 Gold Codes 30 | """ 31 | n = int(n) 32 | if not n in preferred_pairs: 33 | raise ss.Error('preferred pairs for %s bits unknown' % str(n)) 34 | seed = list(numpy.ones(n)) 35 | seq1 = mls.lfsr(preferred_pairs[n][0], seed) 36 | seq2 = mls.lfsr(preferred_pairs[n][1], seed) 37 | return gen_gold(seq1, seq2) 38 | 39 | 40 | def paper_eg(): 41 | """Gold code set example base on paper by E. H. Dinan and B. Jabbari 42 | Spreading Codes for Direct Sequence CDMA and Wideband CDMA Cellular 43 | Networks""" 44 | seq1 = mls.lfsr([2],[1, 1, 1, 1, 1]) 45 | print 'Sequence 1:', numpy.where(seq1, 1, 0) 46 | seq2 = mls.lfsr([1, 2, 3], [1, 1, 1, 1, 1]) 47 | print 'Sequence 2:', numpy.where(seq2, 1, 0) 48 | gold = gen_gold(seq1, seq2) 49 | print 'Gold 0 shift combination:', numpy.where(gold[0], 1, 0) 50 | print 'Gold 1 shift combination:', numpy.where(gold[1], 1, 0) 51 | print 'Gold 30 shift combination:', numpy.where(gold[-1], 1, 0) 52 | 53 | pylab.figure() 54 | pylab.subplot(2,2,1) 55 | pylab.title('Autocorrelation gold[0]') 56 | g0 = numpy.where(gold[0], 1.0, -1.0) 57 | pylab.plot((numpy.roll(filter.ccorr(g0, g0).real, len(g0)/2-1))) 58 | pylab.subplot(2,2,2) 59 | pylab.title('Autocorrelation gold[30]') 60 | g30 = numpy.where(gold[30], 1.0, -1.0) 61 | pylab.plot((numpy.roll(filter.ccorr(g30, g30).real, len(g30)/2-1))) 62 | pylab.subplot(2,2,3) 63 | pylab.title('Crosscorrelation gold[0] gold[1]') 64 | g1 = numpy.where(gold[1], 1.0, -1.0) 65 | pylab.plot((numpy.roll(filter.ccorr(g0, g1).real, len(g0)/2-1))) 66 | pylab.subplot(2,2,4) 67 | pylab.title('Crosscorrelation gold[0] gold[30]') 68 | pylab.plot((numpy.roll(filter.ccorr(g0, g30).real, len(g0)/2-1))) 69 | pylab.show() 70 | 71 | 72 | def web_eg(): 73 | """Example of producing Gold Codes from the net 74 | (http://paginas.fe.up.pt/~hmiranda/cm/Pseudo_Noise_Sequences.pdf)""" 75 | seq1 = mls.lfsr([1],[1,0,0]) 76 | print 'Sequence 1:', numpy.where(seq1, 1, 0) 77 | seq2 = mls.lfsr([2], [1,0,0]) 78 | print 'Sequence 2:', numpy.where(seq2, 1, 0) 79 | for gold in gen_gold(seq1, seq2): 80 | print 'Gold Code:', numpy.where(gold, 1, 0) 81 | 82 | 83 | def main(nbits): 84 | """Main Program""" 85 | print nbits 86 | if nbits != None: 87 | g = gold(nbits) 88 | #plotting 89 | pylab.figure() 90 | pylab.subplot(2,2,1) 91 | pylab.title('Autocorrelation g[0]') 92 | g0 = numpy.where(g[0], 1.0, -1.0) 93 | pylab.plot((numpy.roll(filter.ccorr(g0, g0).real, len(g0)/2-1))) 94 | pylab.xlim(0, len(g0)) 95 | pylab.subplot(2,2,2) 96 | pylab.title('Autocorrelation g[-1]') 97 | gm1 = numpy.where(g[-1], 1.0, -1.0) 98 | pylab.plot((numpy.roll(filter.ccorr(gm1, gm1).real, len(gm1)/2-1))) 99 | pylab.xlim(0, len(gm1)) 100 | pylab.subplot(2,2,3) 101 | pylab.title('Crosscorrelation g[0] g[1]') 102 | g1 = numpy.where(g[1], 1.0, -1.0) 103 | pylab.plot((numpy.roll(filter.ccorr(g0, g1).real, len(g0)/2-1))) 104 | pylab.xlim(0, len(g0)) 105 | pylab.subplot(2,2,4) 106 | pylab.title('Crosscorrelation g[0] g[-1]') 107 | pylab.plot((numpy.roll(filter.ccorr(g0, gm1).real, len(g0)/2-1))) 108 | pylab.xlim(0, len(g0)) 109 | pylab.show() 110 | else: 111 | print 'Paper Example:' 112 | paper_eg() 113 | print 'Web Example:' 114 | web_eg() 115 | 116 | 117 | if __name__ == '__main__': 118 | import sys 119 | main(sys.argv[1] if len(sys.argv) > 1 else None) 120 | -------------------------------------------------------------------------------- /signal_processing/sp/mls.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module providing the functionality to generate Maximal Length Sequences. 3 | Based on wiki's description and polynomial representation. 4 | http://en.wikipedia.org/wiki/Maximum_length_sequence 5 | """ 6 | 7 | import numpy 8 | 9 | bittaps = {2:[1], 3:[2], 4:[3], 5:[2], 6:[5], 7:[6], 8:[4,5,6], 9:[5], 10 | 10:[7], 11:[9]} 11 | 12 | 13 | class Error(Exception): 14 | 15 | """This is a user-defined exception for errors raised by this module.""" 16 | 17 | pass 18 | 19 | 20 | def lfsr(taps, buf): 21 | """Function implements a linear feedback shift register 22 | taps: List of Polynomial exponents for non-zero terms other than 1 and n 23 | buf: List of buffer initialisation values as 1's and 0's or booleans 24 | """ 25 | nbits = len(buf) 26 | sr = numpy.array(buf, dtype='bool') 27 | out = [] 28 | for i in range((2**nbits)-1): 29 | feedback = sr[0] 30 | out.append(feedback) 31 | for t in taps: 32 | feedback ^= sr[t] 33 | sr = numpy.roll(sr, -1) 34 | sr[-1] = feedback 35 | return out 36 | 37 | def mls(n, seed=None): 38 | """Generate a Maximal Length Sequence 2^n - 1 bits long 39 | """ 40 | if n in bittaps: 41 | taps = bittaps[n] 42 | else: 43 | raise Error('taps for %s bits unknown' % str(n)) 44 | if seed is None: 45 | seed = list(numpy.ones(n)) 46 | elif len(seed) != n: 47 | raise Error('length of seed must equal n') 48 | return lfsr(taps, seed) 49 | 50 | def main(nbits): 51 | """Main Program""" 52 | import pylab 53 | import filter 54 | nbits = int(nbits) 55 | m = mls(nbits) 56 | pylab.figure() 57 | pylab.title('%d bit M-Sequence Periodic Autocorrelation' % nbits) 58 | m = numpy.where(m, 1.0, -1.0) 59 | pylab.plot((numpy.roll(filter.ccorr(m, m).real, 2**nbits/2 - 1))) 60 | pylab.xlim(0, len(m)) 61 | pylab.show() 62 | 63 | if __name__ == '__main__': 64 | import sys 65 | main(sys.argv[1]) 66 | -------------------------------------------------------------------------------- /signal_processing/sp/multirate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module providing Multirate signal processing functionality. 3 | Largely based on MATLAB's Multirate signal processing toolbox with consultation 4 | of Octave m-file source code. 5 | """ 6 | 7 | import sys 8 | import fractions 9 | import numpy 10 | from scipy import signal 11 | 12 | 13 | def downsample(s, n, phase=0): 14 | """Decrease sampling rate by integer factor n with included offset phase. 15 | """ 16 | return s[phase::n] 17 | 18 | 19 | def upsample(s, n, phase=0): 20 | """Increase sampling rate by integer factor n with included offset phase. 21 | """ 22 | return numpy.roll(numpy.kron(s, numpy.r_[1, numpy.zeros(n-1)]), phase) 23 | 24 | 25 | def decimate(s, r, n=None, fir=False): 26 | """Decimation - decrease sampling rate by r. The decimation process filters 27 | the input data s with an order n lowpass filter and then resamples the 28 | resulting smoothed signal at a lower rate. By default, decimate employs an 29 | eighth-order lowpass Chebyshev Type I filter with a cutoff frequency of 30 | 0.8/r. It filters the input sequence in both the forward and reverse 31 | directions to remove all phase distortion, effectively doubling the filter 32 | order. If 'fir' is set to True decimate uses an order 30 FIR filter (by 33 | default otherwise n), instead of the Chebyshev IIR filter. Here decimate 34 | filters the input sequence in only one direction. This technique conserves 35 | memory and is useful for working with long sequences. 36 | """ 37 | if fir: 38 | if n is None: 39 | n = 30 40 | b = signal.firwin(n, 1.0/r) 41 | a = 1 42 | f = signal.lfilter(b, a, s) 43 | else: #iir 44 | if n is None: 45 | n = 8 46 | b, a = signal.cheby1(n, 0.05, 0.8/r) 47 | f = signal.filtfilt(b, a, s) 48 | return downsample(f, r) 49 | 50 | 51 | def interp(s, r, l=4, alpha=0.5): 52 | """Interpolation - increase sampling rate by integer factor r. Interpolation 53 | increases the original sampling rate for a sequence to a higher rate. interp 54 | performs lowpass interpolation by inserting zeros into the original sequence 55 | and then applying a special lowpass filter. l specifies the filter length 56 | and alpha the cut-off frequency. The length of the FIR lowpass interpolating 57 | filter is 2*l*r+1. The number of original sample values used for 58 | interpolation is 2*l. Ordinarily, l should be less than or equal to 10. The 59 | original signal is assumed to be band limited with normalized cutoff 60 | frequency 0=alpha=1, where 1 is half the original sampling frequency (the 61 | Nyquist frequency). The default value for l is 4 and the default value for 62 | alpha is 0.5. 63 | """ 64 | b = signal.firwin(2*l*r+1, alpha/r); 65 | a = 1 66 | return r*signal.lfilter(b, a, upsample(s, r))[r*l+1:-1] 67 | 68 | 69 | def resample(s, p, q, h=None): 70 | """Change sampling rate by rational factor. This implementation is based on 71 | the Octave implementation of the resample function. It designs the 72 | anti-aliasing filter using the window approach applying a Kaiser window with 73 | the beta term calculated as specified by [2]. 74 | 75 | Ref [1] J. G. Proakis and D. G. Manolakis, 76 | Digital Signal Processing: Principles, Algorithms, and Applications, 77 | 4th ed., Prentice Hall, 2007. Chap. 6 78 | 79 | Ref [2] A. V. Oppenheim, R. W. Schafer and J. R. Buck, 80 | Discrete-time signal processing, Signal processing series, 81 | Prentice-Hall, 1999 82 | """ 83 | gcd = fractions.gcd(p,q) 84 | if gcd>1: 85 | p=p/gcd 86 | q=q/gcd 87 | 88 | if h is None: #design filter 89 | #properties of the antialiasing filter 90 | log10_rejection = -3.0 91 | stopband_cutoff_f = 1.0/(2.0 * max(p,q)) 92 | roll_off_width = stopband_cutoff_f / 10.0 93 | 94 | #determine filter length 95 | #use empirical formula from [2] Chap 7, Eq. (7.63) p 476 96 | rejection_db = -20.0*log10_rejection; 97 | l = numpy.ceil((rejection_db-8.0) / (28.714 * roll_off_width)) 98 | 99 | #ideal sinc filter 100 | t = numpy.arange(-l, l + 1) 101 | ideal_filter=2*p*stopband_cutoff_f*numpy.sinc(2*stopband_cutoff_f*t) 102 | 103 | #determine parameter of Kaiser window 104 | #use empirical formula from [2] Chap 7, Eq. (7.62) p 474 105 | beta = signal.kaiser_beta(rejection_db) 106 | 107 | #apodize ideal filter response 108 | h = numpy.kaiser(2*l+1, beta)*ideal_filter 109 | 110 | ls = len(s) 111 | lh = len(h) 112 | 113 | l = (lh - 1)/2.0 114 | ly = numpy.ceil(ls*p/float(q)) 115 | 116 | #pre and postpad filter response 117 | nz_pre = numpy.floor(q - numpy.mod(l,q)) 118 | hpad = h[-lh+nz_pre:] 119 | 120 | offset = numpy.floor((l+nz_pre)/q) 121 | nz_post = 0; 122 | while numpy.ceil(((ls-1)*p + nz_pre + lh + nz_post )/q ) - offset < ly: 123 | nz_post += 1 124 | hpad = hpad[:lh + nz_pre + nz_post] 125 | 126 | #filtering 127 | xfilt = upfirdn(s, hpad, p, q) 128 | 129 | return xfilt[offset-1:offset-1+ly] 130 | 131 | 132 | def upfirdn(s, h, p, q): 133 | """Upsample signal s by p, apply FIR filter as specified by h, and 134 | downsample by q. Using fftconvolve as opposed to lfilter as it does not seem 135 | to do a full convolution operation (and its much faster than convolve). 136 | """ 137 | return downsample(signal.fftconvolve(h, upsample(s, p)), q) 138 | 139 | def main(): 140 | """Show simple use cases for functionality provided by this module. Each 141 | example below attempts to mimic the examples provided by mathworks MATLAB 142 | documentation, http://www.mathworks.com/help/toolbox/signal/ 143 | """ 144 | import pylab 145 | argv = sys.argv 146 | if len(argv) != 1: 147 | print >>sys.stderr, 'usage: python -m pim.sp.multirate' 148 | sys.exit(2) 149 | 150 | #Downsample 151 | x = numpy.arange(1, 11) 152 | print 'Down Sampling %s by 3' % x 153 | print downsample(x, 3) 154 | print 'Down Sampling %s by 3 with phase offset 2' % x 155 | print downsample(x, 3, phase=2) 156 | 157 | #Upsample 158 | x = numpy.arange(1, 5) 159 | print 'Up Sampling %s by 3' % x 160 | print upsample(x, 3) 161 | print 'Up Sampling %s by 3 with phase offset 2' % x 162 | print upsample(x, 3, 2) 163 | 164 | #Decimate 165 | t = numpy.arange(0, 1, 0.00025) 166 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 167 | y = decimate(x,4) 168 | pylab.figure() 169 | pylab.subplot(2, 1, 1) 170 | pylab.title('Original Signal') 171 | pylab.stem(numpy.arange(len(x[0:120])), x[0:120]) 172 | pylab.subplot(2, 1, 2) 173 | pylab.title('Decimated Signal') 174 | pylab.stem(numpy.arange(len(y[0:30])), y[0:30]) 175 | 176 | #Interp 177 | t = numpy.arange(0, 1, 0.001) 178 | x = numpy.sin(2*numpy.pi*30*t) + numpy.sin(2*numpy.pi*60*t) 179 | y = interp(x,4) 180 | pylab.figure() 181 | pylab.subplot(2, 1, 1) 182 | pylab.title('Original Signal') 183 | pylab.stem(numpy.arange(len(x[0:30])), x[0:30]) 184 | pylab.subplot(2, 1, 2) 185 | pylab.title('Interpolated Signal') 186 | pylab.stem(numpy.arange(len(y[0:120])), y[0:120]) 187 | 188 | #upfirdn 189 | L = 147.0 190 | M = 160.0 191 | N = 24.0*L 192 | h = signal.firwin(N-1, 1/M, window=('kaiser', 7.8562)) 193 | h = L*h 194 | Fs = 48000.0 195 | n = numpy.arange(0, 10239) 196 | x = numpy.sin(2*numpy.pi*1000/Fs*n) 197 | y = upfirdn(x, h, L, M) 198 | pylab.figure() 199 | pylab.stem(n[1:49]/Fs, x[1:49]) 200 | pylab.stem(n[1:45]/(Fs*L/M), y[13:57], 'r', markerfmt='ro',) 201 | pylab.xlabel('Time (sec)') 202 | pylab.ylabel('Signal value') 203 | 204 | #resample 205 | fs1 = 10.0 206 | t1 = numpy.arange(0, 1 + 1.0/fs1, 1.0/fs1) 207 | x = t1 208 | y = resample(x, 3, 2) 209 | t2 = numpy.arange(0,(len(y)))*2.0/(3.0*fs1) 210 | pylab.figure() 211 | pylab.plot(t1, x, '*') 212 | pylab.plot(t2, y, 'o') 213 | pylab.plot(numpy.arange(-0.5,1.5, 0.01), numpy.arange(-0.5,1.5, 0.01), ':') 214 | pylab.legend(('original','resampled')) 215 | pylab.xlabel('Time') 216 | 217 | x = numpy.hstack([numpy.arange(1,11), numpy.arange(9,0,-1)]) 218 | y = resample(x,3,2) 219 | pylab.figure() 220 | pylab.subplot(2, 1, 1) 221 | pylab.title('Edge Effects Not Noticeable') 222 | pylab.plot(numpy.arange(19)+1, x, '*') 223 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 224 | pylab.legend(('original', 'resampled')) 225 | x = numpy.hstack([numpy.arange(10, 0, -1), numpy.arange(2,11)]) 226 | y = resample(x,3,2) 227 | pylab.subplot(2, 1, 2) 228 | pylab.plot(numpy.arange(19)+1, x, '*') 229 | pylab.plot(numpy.arange(29)*2/3.0 + 1, y, 'o') 230 | pylab.title('Edge Effects Very Noticeable') 231 | pylab.legend(('original', 'resampled')) 232 | 233 | pylab.show() 234 | return 0 235 | 236 | if __name__ == '__main__': 237 | sys.exit(main()) 238 | -------------------------------------------------------------------------------- /signal_processing/sp/ssim.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Module providing functionality to implement Structural Similarity Image 3 | Quality Assessment. Based on original paper by Z. Whang 4 | "Image Quality Assessment: From Error Visibility to Structural Similarity" IEEE 5 | Transactions on Image Processing Vol. 13. No. 4. April 2004. 6 | """ 7 | 8 | import sys 9 | import numpy 10 | from scipy import signal 11 | from scipy import ndimage 12 | 13 | import gauss 14 | 15 | 16 | def ssim(img1, img2, cs_map=False): 17 | """Return the Structural Similarity Map corresponding to input images img1 18 | and img2 (images are assumed to be uint8) 19 | 20 | This function attempts to mimic precisely the functionality of ssim.m a 21 | MATLAB provided by the author's of SSIM 22 | https://ece.uwaterloo.ca/~z70wang/research/ssim/ssim_index.m 23 | """ 24 | img1 = img1.astype(numpy.float64) 25 | img2 = img2.astype(numpy.float64) 26 | size = 11 27 | sigma = 1.5 28 | window = gauss.fspecial_gauss(size, sigma) 29 | K1 = 0.01 30 | K2 = 0.03 31 | L = 255 #bitdepth of image 32 | C1 = (K1*L)**2 33 | C2 = (K2*L)**2 34 | mu1 = signal.fftconvolve(window, img1, mode='valid') 35 | mu2 = signal.fftconvolve(window, img2, mode='valid') 36 | mu1_sq = mu1*mu1 37 | mu2_sq = mu2*mu2 38 | mu1_mu2 = mu1*mu2 39 | sigma1_sq = signal.fftconvolve(window, img1*img1, mode='valid') - mu1_sq 40 | sigma2_sq = signal.fftconvolve(window, img2*img2, mode='valid') - mu2_sq 41 | sigma12 = signal.fftconvolve(window, img1*img2, mode='valid') - mu1_mu2 42 | if cs_map: 43 | return (((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)* 44 | (sigma1_sq + sigma2_sq + C2)), 45 | (2.0*sigma12 + C2)/(sigma1_sq + sigma2_sq + C2)) 46 | else: 47 | return ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)* 48 | (sigma1_sq + sigma2_sq + C2)) 49 | 50 | def msssim(img1, img2): 51 | """This function implements Multi-Scale Structural Similarity (MSSSIM) Image 52 | Quality Assessment according to Z. Wang's "Multi-scale structural similarity 53 | for image quality assessment" Invited Paper, IEEE Asilomar Conference on 54 | Signals, Systems and Computers, Nov. 2003 55 | 56 | Author's MATLAB implementation:- 57 | http://www.cns.nyu.edu/~lcv/ssim/msssim.zip 58 | """ 59 | level = 5 60 | weight = numpy.array([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]) 61 | downsample_filter = numpy.ones((2, 2))/4.0 62 | im1 = img1.astype(numpy.float64) 63 | im2 = img2.astype(numpy.float64) 64 | mssim = numpy.array([]) 65 | mcs = numpy.array([]) 66 | for l in range(level): 67 | ssim_map, cs_map = ssim(im1, im2, cs_map=True) 68 | mssim = numpy.append(mssim, ssim_map.mean()) 69 | mcs = numpy.append(mcs, cs_map.mean()) 70 | filtered_im1 = ndimage.filters.convolve(im1, downsample_filter, 71 | mode='reflect') 72 | filtered_im2 = ndimage.filters.convolve(im2, downsample_filter, 73 | mode='reflect') 74 | im1 = filtered_im1[::2, ::2] 75 | im2 = filtered_im2[::2, ::2] 76 | return (numpy.prod(mcs[0:level-1]**weight[0:level-1])* 77 | (mssim[level-1]**weight[level-1])) 78 | 79 | def main(): 80 | """Compute the SSIM index on two input images specified on the cmd line.""" 81 | import pylab 82 | argv = sys.argv 83 | if len(argv) != 3: 84 | print >>sys.stderr, 'usage: python -m sp.ssim image1.tif image2.tif' 85 | sys.exit(2) 86 | 87 | try: 88 | from PIL import Image 89 | img1 = numpy.asarray(Image.open(argv[1])) 90 | img2 = numpy.asarray(Image.open(argv[2])) 91 | except Exception, e: 92 | e = 'Cannot load images' + str(e) 93 | print >> sys.stderr, e 94 | 95 | ssim_map = ssim(img1, img2) 96 | ms_ssim = msssim(img1, img2) 97 | 98 | pylab.figure() 99 | pylab.subplot(131) 100 | pylab.title('Image1') 101 | pylab.imshow(img1, interpolation='nearest', cmap=pylab.gray()) 102 | pylab.subplot(132) 103 | pylab.title('Image2') 104 | pylab.imshow(img2, interpolation='nearest', cmap=pylab.gray()) 105 | pylab.subplot(133) 106 | pylab.title('SSIM Map\n SSIM: %f\n MSSSIM: %f' % (ssim_map.mean(), ms_ssim)) 107 | pylab.imshow(ssim_map, interpolation='nearest', cmap=pylab.gray()) 108 | pylab.show() 109 | 110 | return 0 111 | 112 | if __name__ == '__main__': 113 | sys.exit(main()) 114 | --------------------------------------------------------------------------------