├── .gitignore ├── LICENSE ├── README.md ├── images ├── PipelineOverview.png ├── VidPipe-Guide.png └── VidPipe.png ├── requirements.txt ├── resources └── PipelineOverview.xml ├── tools ├── playvideo.py ├── showbox.py ├── showlive.py └── vidcap.py └── vidpipe ├── ActivityFilter.py ├── BackgroundRemove.py ├── BlockNumber.py ├── BlurFilter.py ├── CameraDevice.py ├── CameraWidget.py ├── EdgeDetector.py ├── FilterListOrderMapper.py ├── FrameProcessor.py ├── Histogram.py ├── OpenCVQImage.py ├── SampleFilter.py ├── SimpleMotionDetection.py ├── dialog_main_auto.py ├── gui ├── Makefile ├── dialog_main.ui └── dialog_main_auto.py ├── helpers.py └── main.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vidpipe 2 | 3 | Video data processing pipeline using OpenCV 4 | 5 | A video processing toolset that allows the user to interactively modify the data in the video stream to 6 | see the immediate effect. 7 | 8 | ![VidPipe GUI](./images/VidPipe.png) 9 | 10 | ## To run 11 | 12 | python3 main.py 13 | 14 | ## Overview 15 | 16 | The processing flow is a pipeline that uses filters to transform the data in discrete steps along the dataflow path. 17 | 18 | A *filter* is an object made from a simple python file that that has processing functions called from the main app. The main processing function is passed a single video frame data buffer. That data can be examined and/or modified. The new data can then be passed back to the main app. (See [SampleFilter.py](https://github.com/jchrisweaver/vidpipe/blob/master/vidpipe/SampleFilter.py) for a simple example.) 19 | 20 | Filters are arranged and called in a specific order to create a data flow. The order of the filters matches the order in which they appear in the right-hand side of the dialog box in the scroll window. Each filter can enabled or disabled. The order of the filters can be changed by dragging and dropping the filter into a differnt position in the processing order. Each filters effects can be immediately visible in the processed video feed and compared to the preview video feed. 21 | 22 | Settings for each individual filter can be changed in the dialog box for the filter. Changes take effect immediately. 23 | 24 | ![Pipeline Overview](./images/PipelineOverview.png) 25 | 26 | Each filter takes a single action. For example, the Blur Filter takes an incoming video frame, applies a blur action to the frame data and then passes the new frame data to the next filter in the path. 27 | 28 | ![GUI Guide](./images/VidPipe-Guide.png) 29 | 30 | ## The Currently Implemented Filters 31 | 32 | * Blur filter - uses OpenCV [GaussianBlur](https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html?highlight=gaussianblur#gaussianblur) function 33 | * Simple motion detector 34 | * Edge detector - uses OpenCV [Canny](https://docs.opencv.org/2.4/modules/imgproc/doc/feature_detection.html?highlight=canny#canny) and [findCountours](https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontoures#findcontours) functions 35 | * Activity detector 36 | 37 | ## Steps to Create New filters 38 | 39 | *TODO: Add steps here!* 40 | 41 | The GUI is designed with QT for simplicity, which must be installed manually (https://www.qt.io/download) 42 | 43 | ## Future Filters 44 | 45 | * Color filter - pick out a specific color in the video 46 | * YOLO - implement the YOLO algorithm 47 | * Object track - track objects on linear path 48 | 49 | ## Why I Wrote This 50 | 51 | I took the [PyImageSearch Gurus](https://www.pyimagesearch.com/pyimagesearch-gurus/) course to learn more about computer vision. Many of 52 | the steps required to process an image have several discrete stages of manipulation or analyis of the image data to arrive at a result. 53 | 54 | I wanted to better understand how each discrete step affected the image data and how rearranging the order of each step affected the data. This tool made it extremelty easy to visualize each step. I've continued to add additional fun filters as time and interest permit. 55 | 56 | If you use and enjoy this tool, please let me know @jchrisweaver on twitter. 57 | 58 | And by all means, please submit PRs if you'd like to add features, fix bugs, etc. 59 | 60 | ## NOTE: Selecting the camera for the video feed 61 | 62 | The camera feed is selected in the KnobTurner class in the main.py file as _cameraId. For OS X, it's unclear how the camera ID is determined. I've found it to be 0 on my Mac, but it may not be the same on other systems. 63 | 64 | Further, OS X has implemented an enhanced permissions model that requires the user to give the app permission to use the camera. I don't have more information at this point on how to work with that model, other than to give the app permission when requested. 65 | -------------------------------------------------------------------------------- /images/PipelineOverview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchrisweaver/vidpipe/1d00143ca3696164af107e5fa407f7aac190bb06/images/PipelineOverview.png -------------------------------------------------------------------------------- /images/VidPipe-Guide.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchrisweaver/vidpipe/1d00143ca3696164af107e5fa407f7aac190bb06/images/VidPipe-Guide.png -------------------------------------------------------------------------------- /images/VidPipe.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jchrisweaver/vidpipe/1d00143ca3696164af107e5fa407f7aac190bb06/images/VidPipe.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | install==1.3.5 2 | numpy==1.26.4 3 | opencv-python==4.9.0.80 4 | PyQt5==5.15.10 5 | PyQt5-Qt5==5.15.12 6 | PyQt5-sip==12.13.0 7 | -------------------------------------------------------------------------------- /resources/PipelineOverview.xml: -------------------------------------------------------------------------------- 1 | 7ZrLcuI4FIafhmUoW7INLAMdZhZzSVWqZjqrKcUWRtWy5TIikHn6ObIl32QIoU2TqYZFsI5kXc7/6XbCCC+S/S85yda/i4jyEXKi/Qh/GSHkOhjBl7K8GcvELy1xziJtqw1P7F9qCmrrlkV00yooheCSZW1jKNKUhrJlI3kudu1iK8HbrWYkppbhKSTctv7NIrkurRg7Tp3xK2XxWjcNWbMy54WE3+JcbFPd4AjhVfEpsxNiKtM1bdYkEruGCT+M8CIXQpZPyX5BufKu8Vv53vJAbtXxnKbylBdw+cIr4Vtqelz0S74ZZ0AXM/XIksJr87VMOCRdeHyluWTgtnvO4hRsUmQN62/khfJHsWGSCZX7IqQUCRTgKmNeeWohuMiLtoyv8Lxo7H6Tleo6YCEmsWJ7GpkikF5LqbC4V4NEyzBK0ZgBGCuWRjQfh9AiWkZEEvhS9g18rziRd1t2V6TvkHeX7cGKPPjzCuQJZXLRdJylMTS0kbn4VoGgxr1inDd6/TD/snxQ9jgnEQPPm7xUpMpjK5HKJUkYV/NhIbY5ozn4+A+605l6BrieTjfqdoqPGr/2Macr8MJc6waupvuD2rsVUTBXqUiozN+giH4h0AzqWVqldzXy4ITStm7QXhmJnmZxVXVNGjxo2PrB8yzwlozLwi/uQQSzXIR0A63Od2sm6VNGQmXewTLUBrOehn9uJWcp1fZ3pVwWnwtLKaDfTKoasN9QNoTmoLZBtEXerC3uzOsR17HFNRB8j7b+YW0PLy83bU/V1jMOvoa2wWFt8U3bAdZk53raTixtn8X2oKjbhN+HUjlpkB2//yzRYEOURCyqM5/zafbmA2AMt1VPcRsL3IMFvhAVU4uKx3I6wykMOX+p85LFSKGyOqUVkrwz6X+ayT2ZXnFyz94/6dM0ule3JzVsTjYbFvYJ1XBeAJ9CmLaEaChN6J7Jr7px9fysZv1YyQMez9++6kWgSNR55bhoZN3xOjrB2KFfoS6ldy9J8pjKxhnVVrOhlt8jlrHlFG4Z7LXdiT4FdQuPgkH3aljarPizDgNl3/VLzRtep54KKFOR16moHLFVUcFTNeqTEDPX9xtjBxjzbMb8azKGJ157W5lOxv55mHUPpT1VDQiaewPtKGi+DVpwTdCQO23T4XnnYYaC2fGKBoQM3SA7CllgQza9JmS+31mC8JmQBa5zvKIBITshAPv5IDuCkgGwTj3rbp4HWc+xzL3qucxF7T3TM+vEhynz25R5/mmUAQvkrVEsUwU2H+iwbqeGtqzxbITtUO5jTl8ZIIUCri7AL4BYEKun223xA6GgTnzeMzr+iNuia8dwLdns1aUpk44SJftY/ZNwvOJiF65JLsckTYUkKkL0D7KDJdcQM9f9AfPMGShGG6CWeGaReGeN8mZ4AO3sGK2O2LA0Bvsjy2gRW+0KCsOVx7YW4/OGRNpk8d+N5iUsilQzvbO7nv/OUJIOIWHn4uyaG3hz/vUF3boX7LM0tGOx338uwDCdML784XOovf9TxV/8M+Mv2OncWLqBnAEPk3ao9ueD5roBFbcjdnDmFcSb+j+MmktEhv9v1Fw1OuLN/GGo6R4ZL0gNukSs9+LUVBfXOiTyrI8dp3Pzee6iuBuoOPefBBN0HjgfvYseameouyiyA8PwNgFL+Quw24H3yIEXm2CLEWeiq2jAPOuBGQ1w3u35zRBX8wIsvSGDm3JN5Vy/rZyH7VDBxZSzb5s3yU6QrLvnO4ElmTeMZJCsf1BcLqr177bxw38= -------------------------------------------------------------------------------- /tools/playvideo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | 6 | video = "drop.avi" 7 | 8 | video_capture = cv2.VideoCapture(video) 9 | video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) 10 | 11 | count = 0 12 | while(True): 13 | # Capture frame-by-frame 14 | ret, frame = video_capture.read() 15 | if not ret: 16 | break 17 | 18 | count += 1 19 | 20 | print( video_length, count ) 21 | # When everything done, release the capture 22 | video_capture.release() 23 | cv2.destroyAllWindows() 24 | 25 | -------------------------------------------------------------------------------- /tools/showbox.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | img = cv2.imread('/Users/chris/code/bounder/vidpipe/images/VidPipe.png',0) 5 | cv2.imshow('image',img) 6 | k = cv2.waitKey(1) & 0xFF 7 | 8 | if k == 27: # wait for ESC key to exit 9 | cv2.destroyAllWindows() 10 | elif k == ord('s'): # wait for 's' key to save and exit 11 | cv2.destroyAllWindows() 12 | 13 | -------------------------------------------------------------------------------- /tools/showlive.py: -------------------------------------------------------------------------------- 1 | # from https://www.learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/ 2 | import cv2 3 | import numpy as np 4 | 5 | save_video = False 6 | 7 | # Create a VideoCapture object 8 | cap = cv2.VideoCapture(0) 9 | 10 | # Check if camera opened successfully 11 | if (cap.isOpened() == False): 12 | print("Unable to read camera feed") 13 | 14 | # Default resolutions of the frame are obtained.The default resolutions are system dependent. 15 | # We convert the resolutions from float to integer. 16 | frame_width = int(cap.get(3)) 17 | frame_height = int(cap.get(4)) 18 | 19 | # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file. 20 | if save_video: 21 | out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height)) 22 | else: 23 | out = None 24 | 25 | while(True): 26 | ret, frame = cap.read() 27 | 28 | if ret == True: 29 | 30 | # Write the frame into the file 'output.avi' 31 | if out: 32 | out.write(frame) 33 | 34 | # Display the resulting frame 35 | cv2.imshow('frame',frame) 36 | 37 | # Press Q on keyboard to stop recording 38 | if cv2.waitKey(1) & 0xFF == ord('q'): 39 | break 40 | 41 | # Break the loop 42 | else: 43 | break 44 | 45 | # When everything done, release the video capture and video write objects 46 | cap.release() 47 | if out: 48 | out.release() 49 | 50 | # Closes all the frames 51 | cv2.destroyAllWindows() 52 | 53 | -------------------------------------------------------------------------------- /tools/vidcap.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | 6 | ''' 7 | Capture live video and save it to a file 8 | ''' 9 | 10 | cap = cv2.VideoCapture(0) 11 | 12 | # Define the codec and create VideoWriter object 13 | fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v') # note the lower case 14 | out = cv2.VideoWriter('fan.avi', fourcc, 15.0, (640,480)) 15 | 16 | while(cap.isOpened()): 17 | ret, frame = cap.read() 18 | if ret==True: 19 | 20 | # write the flipped frame 21 | out.write(frame) 22 | 23 | cv2.imshow('frame',frame) 24 | if cv2.waitKey(1) & 0xFF == ord('q'): 25 | break 26 | else: 27 | break 28 | 29 | # Release everything if job is finished 30 | cap.release() 31 | out.release() 32 | cv2.destroyAllWindows() 33 | -------------------------------------------------------------------------------- /vidpipe/ActivityFilter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import random 6 | 7 | import cv2 8 | import numpy as np 9 | from FrameProcessor import FrameProcessor 10 | from helpers import draw_rect, draw_str 11 | 12 | ''' 13 | Activity Filter tries to detect periodic activity in each block and then remove that 14 | window of video so it's not passed forward. 15 | 16 | Use case: Ignoring a fan in the background when processing video. 17 | ''' 18 | 19 | class ActivityFilter( FrameProcessor ): 20 | 21 | # color of the filter and outlines 22 | _color = ( 200, 180, 255 ) 23 | 24 | # 10 x 10 grid 25 | _X = 10 # 64 pixels 26 | _Y = 10 # 48 pixels 27 | _threshold = 0.05 # 5% value change - LOWER is more sensitive 28 | 29 | _threshold2 = 0.10 # 10% value change - HIGHER is more sensitive 30 | _timeSpan2 = 10 * 10 # 10 seconds, 30 frames 31 | _frameCount = 0 # always running frame count 32 | 33 | _countMovAvg = 0 34 | _lastAccum = 0 35 | 36 | # debug flags to add one square with generated noise 37 | # TODO: make this configurable in the GUI? 38 | _percentNoise = 1 # percentage of screen to cover with generated noise 39 | _debugRandomNoise = False 40 | _debugSteadyNoise = True 41 | _noiseBlock_x = 3 42 | _noiseBlock_y = 7 43 | 44 | def __init__( self ): 45 | super( ActivityFilter, self ).__init__() 46 | self._name = "Activity Filter" 47 | 48 | self._prev_frame_sum_of_values = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 4.2 bill 49 | self._histAccum = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 4.2 bill 50 | self._devAccum = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 4.2 bill 51 | self._mask = np.zeros( ( self._Y, self._X ), np.bool_ ) 52 | 53 | random.seed( 1231 ) 54 | 55 | self._enabled = False 56 | 57 | # frame that's processed but is hijacked to show a histogram instead of video 58 | # useful for debugging values and buffers 59 | self._watchFrame_enabled = True 60 | self._watchFrame = ( 0, 8 ) # Set the watch frame at cel x=8, y=0 NOTE: Order is Y, X 61 | 62 | self._graph_ringbuf_MovingAverage = np.zeros( 200, np.float32 ) 63 | self._graph_ringbuf = np.zeros( 200, np.uint8 ) 64 | self._maxhistAccum = 1 # use 1 to avoid divide by zero later 65 | 66 | def prop_ChangeThresh_set( self, thresh ): 67 | self._threshold = thresh / 1000 68 | 69 | def prop_ChangeThresh_get( self): 70 | return self._threshold * 1000 71 | 72 | def type_ChangeThresh( self ): 73 | return int 74 | 75 | def prop_Watch_set( self, val ): 76 | # TODO: error check 77 | self._watchFrame = tuple( val )[ :: -1 ] 78 | self._graph_ringbuf_MovingAverage = np.zeros( 200, np.float32 ) 79 | self._graph_ringbuf = np.zeros( 200, np.uint8 ) 80 | self._maxhistAccum = 1 81 | 82 | def prop_Watch_get( self): 83 | return self._watchFrame[ :: -1 ] 84 | 85 | def type_Watch( self ): 86 | return tuple 87 | 88 | def processFrame( self, frame_in ): 89 | # frame_in is BGR 90 | # frame_in.shape = ( 480, 640, 3 ) 91 | self._frameCount += 1 92 | 93 | # get the size of the frame 94 | h, w, _ = frame_in.shape 95 | 96 | # divide the frame into X x Y grid 97 | yjump = int( w / self._Y ) 98 | xjump = int( h / self._X ) 99 | 100 | # brute force a background 101 | #draw_rect( frame_in, 0, 0, 640, 480, ( 0, 0, 0 ) ) 102 | 103 | # inject random noise 104 | if self._debugRandomNoise == True: 105 | r = random.randint( 0, 255 ) 106 | g = random.randint( 0, 255 ) 107 | b = random.randint( 0, 255 ) 108 | draw_rect( frame_in, ( self._noiseBlock_x * xjump ), ( self._noiseBlock_y * yjump ), 109 | ( ( self._noiseBlock_x + 1 ) * xjump - ( ( 1 - self._percentNoise ) * xjump ) - 1 ), 110 | ( ( self._noiseBlock_y + 1 ) * yjump - ( ( 1 - self._percentNoise ) * yjump ) - 1 ), 111 | ( r, g, b ) ) 112 | 113 | # inject noise that follows a steady pattern 114 | if self._debugSteadyNoise == True: 115 | color = ( 255, 255, 0 ) 116 | if self._frameCount % 9 == 0: 117 | color = ( 128, 255, 255 ) 118 | elif self._frameCount % 8 == 0: 119 | color = ( 0, 128, 255 ) 120 | elif self._frameCount % 7 == 0: 121 | color = ( 128, 255, 128 ) 122 | elif self._frameCount % 6 == 0: 123 | color = ( 0, 0, 255 ) 124 | elif self._frameCount % 5 == 0: 125 | color = ( 33, 255, 255 ) 126 | elif self._frameCount % 4 == 0: 127 | color = ( 0, 33, 255 ) 128 | elif self._frameCount % 3 == 0: 129 | color = ( 0, 0, 33 ) 130 | elif self._frameCount % 2 == 0: 131 | color = ( 50, 50, 255 ) 132 | draw_rect( frame_in, ( self._noiseBlock_x * xjump ), ( self._noiseBlock_y * yjump ), 133 | ( ( self._noiseBlock_x + 1 ) * xjump - ( ( 1 - self._percentNoise ) * xjump ) - 1 ), 134 | ( ( self._noiseBlock_y + 1 ) * yjump - ( ( 1 - self._percentNoise ) * yjump ) - 1 ), 135 | color ) 136 | 137 | for y in range( 0, self._Y ): 138 | for x in range( 0, self._X ): 139 | 140 | # sum for each portion of the grid 141 | # TODO: change to count the number of pixels change to monitor a % of area changed 142 | # sum is mixing both degree of change AND area changed 143 | sum_of_values = int( frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ].sum() ) 144 | 145 | # calc a delta for each portion after Z # of frames - 1st derivitate, change over time 146 | dev_from_hist = abs( sum_of_values - self._prev_frame_sum_of_values[ y ][ x ] ) 147 | 148 | if self._mask[ y ][ x ] == True: 149 | frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] = 128 150 | 151 | #if the | delta | < Threshold then blank out that sector 152 | nomotion = False 153 | if dev_from_hist < self._threshold * self._prev_frame_sum_of_values[ y ][ x ]: 154 | nomotion = True 155 | 156 | # if not already masked for some reason 157 | #if self._mask[ y ][ x ] != True: 158 | # frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] = 0 159 | 160 | # 2nd derivative - change of change over time 161 | self._devAccum[ y ][ x ] += dev_from_hist 162 | 163 | if self._watchFrame_enabled and self._watchFrame == ( y, x ): 164 | 165 | self._graph_ringbuf = np.roll( self._graph_ringbuf, 1 ) 166 | self._graph_ringbuf[ 0 ] = yjump * dev_from_hist / 100000 167 | 168 | # start with a clear image 169 | #frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] = 0 170 | vis = frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] 171 | 172 | # plot the values 173 | for xx in range( 1, xjump ): 174 | cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf[ xx ] ) ), ( 255, 255, 0 ), 1 ) 175 | #cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf_MovingAverage[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf_MovingAverage[ xx ] ) ), ( 0, 25, 255 ), 2 ) 176 | 177 | if self._mask[ y ][ x ] == True: 178 | cv2.circle( vis, ( xjump - 6, 4 ), 3, ( 0, 25, 255 ), -1 ) 179 | 180 | # show midway mark for refrence 181 | cv2.line( vis, ( 0, yjump - int( yjump / 2 ) ), ( xjump - 1, yjump - int( yjump / 2 ) ), ( 128, 128, 128 ), 1 ) 182 | 183 | # plot the moving average 184 | scaledMovingAvg = int( yjump * self._graph_ringbuf_MovingAverage[ 0 ] / self._maxhistAccum ) 185 | cv2.line( vis, ( 0, yjump - scaledMovingAvg ), ( xjump - 1, yjump - scaledMovingAvg ), ( 0, 25, 255 ), 2 ) 186 | 187 | scaledLastAccum = int( yjump * self._lastAccum / 1000000 ) 188 | cv2.line( vis, ( 0, yjump - scaledLastAccum ), ( xjump - 1, yjump - scaledLastAccum ), ( 255, 25, 0 ), 2 ) 189 | 190 | #if self._watchFrame == ( y, x ): 191 | # print( "%d\t%d\t%d\t%d" % ( sum_of_values, self._prev_frame_sum_of_values[ y ][ x ], dev_from_hist, self._devAccum[ y ][ x ] ) ) 192 | 193 | # calculuate change over time 194 | if self._frameCount % self._timeSpan2 == 0: 195 | if self._histAccum[ y ][ x ] > self._devAccum[ y ][ x ]: 196 | accum = self._histAccum[ y ][ x ] - self._devAccum[ y ][ x ] 197 | else: 198 | accum = self._devAccum[ y ][ x ] - self._histAccum[ y ][ x ] 199 | 200 | if accum < self._threshold2 * self._histAccum[ y ][ x ] and nomotion == False: 201 | self._mask[ y ][ x ] = True 202 | else: 203 | self._mask[ y ][ x ] = False 204 | 205 | self._lastAccum = accum 206 | 207 | if self._watchFrame == ( y, x ): 208 | print( "accum: {0}\t\tdevAccum: {1}\t\thistAccum: {2}".format( accum, self._devAccum[ y ][ x ], self._histAccum[ y ][ x ] ) ) 209 | 210 | #self._graph_ringbuf_MovingAverage[ 0 ] = self.movingAverage( ( self._yjump * self._movingAverageSlidingWindow / self._maxhistAccum ), self._slidingWindow ) 211 | 212 | movingAverage = ( self._devAccum[ y ][ x ] + self._countMovAvg * self._graph_ringbuf_MovingAverage[ 0 ] ) / ( self._countMovAvg + 1 ) 213 | self._maxhistAccum = max( self._maxhistAccum, movingAverage ) 214 | if self._countMovAvg == 0: 215 | self._maxhistAccum *= 0.25 216 | elif self._countMovAvg == 1: 217 | self._countMovAvg *= 0.50 218 | elif self._countMovAvg == 2: 219 | self._countMovAvg *= 0.75 220 | 221 | print( "MaxHistAccum: %d\t\tmovingAvg: %d" %( self._maxhistAccum, movingAverage ) ) 222 | self._graph_ringbuf_MovingAverage = np.roll( self._graph_ringbuf_MovingAverage, 1 ) 223 | self._graph_ringbuf_MovingAverage[ 0 ] = movingAverage 224 | #self._graph_ringbuf_MovingAverage[ 0 ] = yjump * self._histAccum[ y ][ x ] / self._maxhistAccum # 1000000 225 | 226 | 227 | #if self._watchFrame == ( y, x ): 228 | # print( "%d\t%d\t%d\t%d\t%s" % ( self._frameCount, self._devAccum[ self._watchFrame ], self._histAccum[ self._watchFrame ], accum, self._mask[ self._watchFrame ] ) ) 229 | 230 | self._histAccum[ y ][ x ] = self._devAccum[ y ][ x ] 231 | self._devAccum[ y ][ x ] = 0 232 | 233 | self._prev_frame_sum_of_values[ y ][ x ] = sum_of_values 234 | last_X = x 235 | last_Y = y 236 | 237 | if self._frameCount % self._timeSpan2 == 0: 238 | self._countMovAvg += 1 239 | 240 | # return the processed frame to be either passed to the next filter 241 | # or displayed 242 | return frame_in 243 | 244 | -------------------------------------------------------------------------------- /vidpipe/BackgroundRemove.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import cv2 6 | import numpy as np 7 | from FrameProcessor import FrameProcessor 8 | 9 | ''' 10 | Still in progress.... 11 | 12 | Filter to remove the background and only keep the parts of the video that are 13 | actively changing. 14 | ''' 15 | 16 | class BackgroundRemove( FrameProcessor ): 17 | 18 | def __init__ ( self ): 19 | super( BackgroundRemove, self ).__init__() 20 | self._name = "Background Remove" 21 | 22 | self._speed = 0.01 23 | self._avg = None 24 | 25 | # initializing subtractor 26 | self._fgbg = cv2.createBackgroundSubtractorMOG2( 27 | history = 500, 28 | varThreshold = 16, 29 | detectShadows = False 30 | ) 31 | 32 | def prop_AdaptSpeed_set( self, val ): 33 | self._speed = float( val / 100 ) 34 | print( self._speed ) 35 | 36 | def prop_AdaptSpeed_get( self): 37 | return int( self._speed * 100 ) 38 | 39 | def type_AdaptSpeed( self ): 40 | return int 41 | 42 | #def prop_AlgorithmV_get( self ): 43 | # pass 44 | 45 | def processFrame( self, frame_in ): 46 | 47 | ''' 48 | # version 1 - moving average 49 | if self._avg == None: 50 | self._avg = np.float32( frame_in ) 51 | cv2.accumulateWeighted( frame_in, self._avg, self._speed ) 52 | background = cv2.convertScaleAbs( self._avg ) 53 | active_area = cv2.absdiff( frame_in, background ) 54 | ''' 55 | 56 | #version 2 - MOG - Gausian Mixture-based Background/Foreground Segmentation Algorithm 57 | fgmask = self._fgbg.apply( frame_in ,learningRate = 0.01 ) 58 | #active_area = cv2.bitwise_and( frame_in, frame_in, mask = fgmask ) 59 | 60 | return fgmask 61 | 62 | -------------------------------------------------------------------------------- /vidpipe/BlockNumber.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import cv2 6 | import numpy as np 7 | from FrameProcessor import FrameProcessor 8 | from helpers import draw_rect, draw_str 9 | 10 | 11 | class BlockNumber( FrameProcessor ): 12 | 13 | # 10 x 10 grid 14 | _X = 10 # 64 pixels 15 | _Y = 10 # 48 pixels 16 | _frameCount = 0 # for adding noise 17 | 18 | def __init__( self ): 19 | super( BlockNumber, self ).__init__() 20 | self._name = "Block Number" 21 | 22 | def processFrame( self, frame_in ): 23 | # frame_in is BGR 24 | # frame_in.shape = ( 480, 640, 3 ) 25 | self._frameCount += 1 26 | 27 | # get the size of the frame 28 | h, w, _ = frame_in.shape 29 | 30 | # divide the frame into X x Y grid 31 | self._yjump = h / self._Y 32 | self._xjump = w / self._X 33 | 34 | # brute force a background 35 | #draw_rect( frame_in, 0, 0, 640, 480, ( 0, 0, 0 ) ) 36 | 37 | for y in range( 0, self._Y ): 38 | for x in range( 0, self._X ): 39 | # show the block number - (x, y) 40 | ptx = int( x * self._xjump + .25 * self._xjump ) 41 | pty = int( y * self._yjump + .5 * self._yjump ) 42 | draw_str( frame_in, ptx, pty, "(%d,%d)" % ( x, y ) ) 43 | 44 | # return the processed frame to be either passed to the next filter 45 | # or displayed 46 | return frame_in 47 | 48 | -------------------------------------------------------------------------------- /vidpipe/BlurFilter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | from FrameProcessor import FrameProcessor 5 | 6 | 7 | class BlurFilter( FrameProcessor ): 8 | 9 | ''' 10 | blur_kernel (kernel size) determines how many pixels to sample during the convolution 11 | sigma defines how much to modulate them by 12 | For more info: http://http.developer.nvidia.com/GPUGems3/gpugems3_ch40.html 13 | ''' 14 | 15 | _blur_kernel = 5 # good starting point is 5 - very light blur 16 | _sigma = 0 17 | 18 | def __init__( self ): 19 | super( BlurFilter, self ).__init__() 20 | self._name = "Blur Filter" 21 | self._sigma = 0.3 * ( ( self._blur_kernel - 1 ) * 0.5 - 1 ) + 0.8 22 | 23 | def prop_BlurSize_set( self, val ): 24 | # val must be odd 25 | if val % 2 == 0: 26 | val += 1 # hackish but 1 point won't matter enough to worry about 27 | self._blur_kernel = val 28 | self._sigma = 0.3 * ( ( self._blur_kernel - 1 ) * 0.5 - 1 ) + 0.8 29 | 30 | def prop_BlurSize_get( self): 31 | return self._blur_kernel 32 | 33 | def type_BlurSize( self ): 34 | return int 35 | 36 | def processFrame( self, frame_in ): 37 | # http://docs.opencv.org/modules/imgproc/doc/filtering.html#gaussianblur 38 | blurred = cv2.GaussianBlur( frame_in, ( self._blur_kernel, self._blur_kernel ), self._sigma ) 39 | return blurred 40 | -------------------------------------------------------------------------------- /vidpipe/CameraDevice.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | from PyQt5 import QtCore 6 | 7 | 8 | class CameraDevice( QtCore.QObject ): 9 | 10 | _DEFAULT_FPS = 30 11 | 12 | newFrame = QtCore.pyqtSignal( np.ndarray ) 13 | 14 | def __init__(self, filename = None, cameraId=0, mirrored=True, parent=None): 15 | super(CameraDevice, self).__init__(parent) 16 | 17 | self.mirrored = mirrored 18 | 19 | self._cameraDevice = cv2.VideoCapture( filename if filename else cameraId ) 20 | 21 | self._timer = QtCore.QTimer( self ) 22 | self._timer.timeout.connect( self._queryFrame ) 23 | self._timer.setInterval( int( 1000 / self.fps ) ) 24 | 25 | if filename: 26 | self._maxFrameCount = self._cameraDevice.get( cv2.CAP_PROP_FRAME_COUNT ); 27 | self._frameCount = 0 28 | 29 | self.paused = False 30 | self._maxFrameCount = -1 31 | 32 | # from: https://stackoverflow.com/questions/9710520/opencv-createimage-function-isnt-working 33 | def _createBlankImage( self, w, h, rgb_colors = ( 0, 0, 0 ) ): 34 | """Create new image(numpy array) filled with certain color in RGB""" 35 | # Create black blank image 36 | image = np.zeros((h, w, 3), np.uint8) 37 | 38 | # Since OpenCV uses BGR, convert the color first 39 | color = tuple(reversed(rgb_colors)) 40 | 41 | # Fill image with color 42 | image[:] = color 43 | 44 | return image 45 | 46 | @QtCore.pyqtSlot() 47 | def _queryFrame(self): 48 | success, frame = self._cameraDevice.read() 49 | 50 | if not success: 51 | print( "Error getting frame" ) 52 | else: 53 | if self.mirrored: 54 | h, w, channels = frame.shape 55 | mirroredFrame = self._createBlankImage( w, h ) 56 | mirroredFrame = cv2.flip(frame, 1) 57 | frame = mirroredFrame 58 | self.newFrame.emit( frame ) 59 | self._frameCount += 1 60 | 61 | if self._maxFrameCount > -1 and self._frameCount % self._maxFrameCount == 0: 62 | print( "Repeat at: %d" % self._frameCount ) 63 | 64 | @property 65 | def paused(self): 66 | return not self._timer.isActive() 67 | 68 | @paused.setter 69 | def paused(self, p): 70 | if p: 71 | self._timer.stop() 72 | else: 73 | self._timer.start() 74 | 75 | @property 76 | def frameSize(self): 77 | w = self._cameraDevice.get( cv2.CAP_PROP_FRAME_WIDTH ) 78 | h = self._cameraDevice.get( cv2.CAP_PROP_FRAME_HEIGHT ) 79 | return int(w), int(h) 80 | 81 | @property 82 | def fps( self ): 83 | fps = int( self._cameraDevice.get( cv2.CAP_PROP_FPS ) ) 84 | if not fps > 0: 85 | fps = self._DEFAULT_FPS 86 | return fps 87 | -------------------------------------------------------------------------------- /vidpipe/CameraWidget.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | from OpenCVQImage import OpenCVQImage 5 | from PyQt5.QtCore import QEvent, QPoint, QSize, Qt, pyqtSignal, pyqtSlot 6 | from PyQt5.QtGui import QPainter 7 | from PyQt5.QtWidgets import QSizePolicy, QWidget 8 | 9 | 10 | class CameraWidget( QWidget ): 11 | 12 | newFrame = pyqtSignal( np.ndarray ) 13 | 14 | def __init__( self, parent = None ): 15 | super( CameraWidget, self ).__init__( parent ) 16 | 17 | self._frame = None 18 | 19 | def setCamera( self, cameraDevice ): 20 | self._cameraDevice = cameraDevice 21 | self._cameraDevice.newFrame.connect( self._onNewFrame ) 22 | 23 | #w, h = self._cameraDevice.frameSize 24 | #self.setMinimumSize(w, h) 25 | #self.setMaximumSize( 960, 1280) 26 | #self.setMinimumSize( 640, 480) 27 | #self.setMaximumSize( w, h ) 28 | #self.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed ) 29 | #self.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Expanding ) 30 | 31 | @pyqtSlot( np.ndarray ) 32 | def _onNewFrame(self, frame): 33 | self._frame = frame.copy() 34 | self.newFrame.emit( self._frame ) 35 | self.update() 36 | 37 | def setNewFrame( self, frame ): 38 | self._frame = frame 39 | 40 | def changeEvent( self, e ): 41 | if e.type() == QEvent.EnabledChange: 42 | if self.isEnabled(): 43 | self._cameraDevice.newFrame.connect( self._onNewFrame ) 44 | else: 45 | self._cameraDevice.newFrame.disconnect( self._onNewFrame ) 46 | 47 | 48 | def paintEvent(self, e): 49 | if self._frame is None: 50 | return 51 | 52 | # Assuming OpenCVQImage(self._frame) correctly converts the NumPy array to QImage 53 | qimage = OpenCVQImage(self._frame) 54 | 55 | # Get the current size of the QWidget 56 | widgetSize = self.size() 57 | 58 | # Scale the QImage to fit the QWidget, maintaining the aspect ratio 59 | scaledImage = qimage.scaled(widgetSize, aspectRatioMode=Qt.KeepAspectRatio) 60 | 61 | # Create a QPainter to draw the QImage 62 | painter = QPainter(self) 63 | 64 | # Calculate the top-left point to center the image (if aspect ratio is kept) 65 | x = (widgetSize.width() - scaledImage.width()) // 2 66 | y = (widgetSize.height() - scaledImage.height()) // 2 67 | 68 | # Draw the scaled image 69 | painter.drawImage(QPoint(x, y), scaledImage) 70 | 71 | ''' 72 | def paintEvent( self, e ): 73 | if self._frame is None: 74 | return 75 | painter = QPainter( self ) 76 | painter.drawImage( QPoint( 0, 0 ), OpenCVQImage( self._frame ) ) 77 | ''' 78 | def sizeHint( self ): 79 | w, h = self._cameraDevice.frameSize 80 | return QSize( w, h ) 81 | 82 | def minimumnSizePolicy( self ): 83 | return self.sizeHint() 84 | 85 | -------------------------------------------------------------------------------- /vidpipe/EdgeDetector.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | from FrameProcessor import FrameProcessor 5 | from helpers import combine 6 | 7 | class EdgeDetector( FrameProcessor ): 8 | 9 | _color = ( 25, 100, 200 ) 10 | 11 | _lower_thresh = 10.0 # good starting point is 10 12 | _upper_thresh = 200.0 # good starting point is 200 13 | 14 | def __init__( self ): 15 | super( EdgeDetector, self ).__init__() 16 | self._name = "Edge Detector" 17 | self._testBool = False 18 | 19 | def prop_ThreshLower_set( self, thresh ): 20 | self._lower_thresh = thresh 21 | 22 | def prop_ThreshLower_get( self): 23 | return self._lower_thresh 24 | 25 | def prop_ThreshUpper_set( self, thresh ): 26 | self._upper_thresh = thresh 27 | 28 | def prop_ThreshUpper_get( self ): 29 | return self._upper_thresh 30 | 31 | def type_ThreshUpper( self ): 32 | return int 33 | 34 | def type_ThreshLower( self ): 35 | return int 36 | 37 | def processFrame( self, frame_in ): 38 | self._activeRects = [] 39 | self._boundingBox = [] 40 | 41 | gray = cv2.cvtColor( frame_in, cv2.COLOR_BGR2GRAY ) 42 | gray = cv2.equalizeHist( gray ) 43 | edged_g = cv2.Canny( gray, self._lower_thresh, self._upper_thresh ) 44 | 45 | # draw edges on main image 46 | color = self._color 47 | pen_thickness = 4 48 | ( contours, _ ) = cv2.findContours( edged_g.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE ) 49 | cv2.drawContours( frame_in, contours, -1, color, pen_thickness ) 50 | 51 | # draw a bounding box 52 | # NOTE: skip the bounding box since it's not very useful 53 | ''' 54 | contours = sorted( contours, key = cv2.contourArea, reverse = True )#[ : 20 ] 55 | for r in contours: 56 | rect = cv2.boundingRect( r ) # rect is x, y, w, h 57 | self._activeRects.append( rect ) 58 | 59 | cv2.rectangle( frame_in, ( rect[ 0 ], rect[ 1 ] ), ( rect[ 0 ] + rect[ 2 ], rect[ 1 ] + rect[ 3 ] ), ( 0, 255, 255 ), 1 ) 60 | 61 | self._boundingBox = combine( self._activeRects ) 62 | ''' 63 | return frame_in 64 | 65 | 66 | -------------------------------------------------------------------------------- /vidpipe/FilterListOrderMapper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from PyQt5.QtCore import QEvent, QObject, pyqtSignal, pyqtSlot 4 | from PyQt5.QtWidgets import QListWidgetItem 5 | 6 | # QListWidget isn't set up to easily capture drag-rearrange events 7 | # This is a hack class to capture a dragged list rearrange event and spit out a signal 8 | class FilterListOrderMapper( QObject ): 9 | listChanged = pyqtSignal() 10 | 11 | def eventFilter( self, sender, event ): 12 | 13 | if event.type() == QEvent.ChildRemoved: 14 | #if event.type() == QEvent.ChildAdded: 15 | #if event.type() == QEvent.Drop: 16 | self.listChanged.emit() 17 | return False 18 | 19 | -------------------------------------------------------------------------------- /vidpipe/FrameProcessor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import numpy as np 4 | from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot 5 | 6 | 7 | class FrameProcessor( QObject ): 8 | propStartsWith = "prop_" 9 | propEndsWithSetter = "_set" 10 | propEndsWithGetter = "_get" 11 | propTypeStartsWith = "type_" 12 | 13 | _activeRects = [] 14 | _boundingBox = [] 15 | 16 | # color of the filter and outlines 17 | # None will default to standard gray 18 | _color = None 19 | 20 | def __init__ ( self ): 21 | super( FrameProcessor, self ).__init__() 22 | self._name = "Frame Processor" 23 | self._enabled = False 24 | 25 | def loadConfig( self, config ): 26 | print( ">>>>>>>>>>>TODO: Load configuration" ) 27 | 28 | def saveConfig( self, config ): 29 | print( ">>>>>>>>>>>TODO: Save configuration" ) 30 | 31 | def color( self ): 32 | return self._color 33 | 34 | @property 35 | def name( self ): 36 | return self._name 37 | 38 | def processFrame( self, frame_in ): 39 | return frame_in 40 | 41 | def prop_Enabled_get( self ): 42 | return self._enabled 43 | 44 | def prop_Enabled_set( self, value ): 45 | if type( value ) != bool and value != True and value != False: 46 | raise TypeError( "Enabled must be either True or False" ) 47 | self._enabled = value 48 | print( "Setting %s to %s" % ( self.name, value ) ) 49 | 50 | def type_Enabled( self ): 51 | return bool 52 | 53 | def getBoundingBox( self ): 54 | return self._boundingBox # CAREFUL!!: returns (x1, y1, x2, y2) NOT x, y, w, h 55 | 56 | def getRects( self ): 57 | return self._activeRects 58 | 59 | # Ignore below. Only test code follows..... 60 | if __name__ == '__main__': 61 | import inspect 62 | print( "Testing...." ) 63 | 64 | fp = FrameProcessor() 65 | 66 | print( "Name is %s" % fp.name ) 67 | 68 | try: 69 | fp.enabled = 1 70 | except TypeError: 71 | print( "Caught ValueError exception on setting to int" ) 72 | 73 | try: 74 | fp.enabled = "True" 75 | except TypeError: 76 | print( "Caught ValueError exception on setting to string" ) 77 | 78 | fp.enabled = True 79 | print( "Setting to true. Did it work?: %s" % ( fp.enabled == True ) ) 80 | 81 | fp.enabled = False 82 | print( "Setting to false. Did it work?: %s" % ( fp.enabled == False ) ) 83 | 84 | print( "Getting options:" ) 85 | attribs = [ funct.replace( FrameProcessor.propStartsWith, "" ) for funct in dir( fp ) if callable( getattr( fp, funct ) ) and funct.startswith( FrameProcessor.propStartsWith ) ] 86 | print( "\t", [ ftn.replace( FrameProcessor.propEndsWithSetter, "" ) for ftn in attribs if ftn.endswith( FrameProcessor.propEndsWithSetter ) ] ) 87 | print( "\t", [ ftn.replace( FrameProcessor.propEndsWithGetter, "" ) for ftn in attribs if ftn.endswith( FrameProcessor.propEndsWithGetter ) ] ) 88 | 89 | print( "Finished" ) 90 | 91 | -------------------------------------------------------------------------------- /vidpipe/Histogram.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import math # for sin, remove after testing 6 | # remove later 7 | import random 8 | 9 | import cv2 10 | import numpy as np 11 | from FrameProcessor import FrameProcessor 12 | from helpers import draw_str 13 | 14 | 15 | class HistogramFilter( FrameProcessor ): 16 | _color = ( 80, 180, 80 ) 17 | 18 | # 10 x 10 grid 19 | _X = 10 # 64 pixels 20 | _Y = 10 # 48 pixels 21 | 22 | _deltaT = 1 # time, in frame count-ish 23 | _depth = 30 # depth of the histograph 24 | _threshold = 0.05 # 5% value change - LOWER is more sensitive 25 | 26 | _frameCount = 0 # always running frame count 27 | _Counter = 0 28 | 29 | _total = 0 # used to calc average 30 | _last = 0 # last value stored 31 | _count = 0 # how many values in the histagram so far 32 | 33 | ringlen = 500 34 | _graph_ringbuf = np.zeros( ringlen, np.uint8 ) 35 | _maxScale = 1 36 | _scale = 100000 37 | 38 | _enableDumpFile = False 39 | _fileDataDumpName = "histogram.txt" 40 | _fileDataDump = None 41 | 42 | _countCumulativeAverage = 0 43 | 44 | def __init__( self ): 45 | super( HistogramFilter, self ).__init__() 46 | self._name = "Histogram Filter" 47 | 48 | self._prevFrameSigma = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 18446744073709551615 49 | self._SigmaDeltaAccumulator = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 18446744073709551615 50 | self._SigmaDelta = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 18446744073709551615 51 | self._timeSpan2Mask = np.zeros( ( self._Y, self._X ), np.bool_ ) 52 | 53 | self._slidingWindow = 30 54 | self._movingAverageSlidingWindow = np.zeros( self._slidingWindow, np.uint64 ) 55 | self._graph_ringbuf_MovingAverage = np.zeros( self.ringlen, np.uint8 ) 56 | 57 | self._enabled = False 58 | self._watchFrame = ( 0, 9 ) # top right 59 | 60 | if self._enableDumpFile: 61 | self._fileDataDump = open( self._fileDataDumpName, 'w' ) 62 | 63 | self._cumulativeAverage = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 18446744073709551615 64 | 65 | def prop_Watch_set( self, val ): 66 | # TODO: error check 67 | self._watchFrame = tuple( val )[ :: -1 ] 68 | self._movingAverageSlidingWindow = np.zeros( self._slidingWindow, np.uint64 ) 69 | self._graph_ringbuf_MovingAverage = np.zeros( self.ringlen, np.uint8 ) 70 | 71 | def prop_Watch_get( self): 72 | return self._watchFrame[ :: -1 ] 73 | 74 | def type_Watch( self ): 75 | return tuple 76 | 77 | def prop_Scale_set( self, scale ): 78 | self._scale = scale 79 | 80 | def prop_Scale_get( self): 81 | return self._scale 82 | 83 | def type_Scale( self ): 84 | return int 85 | 86 | def movingAverage( self, values, window ): 87 | weights = np.repeat(1.0, window)/window 88 | sma = np.convolve(values, weights, 'valid') 89 | return sma 90 | 91 | def processFrame( self, frame_in ): 92 | # frame_in is BGR 93 | # frame_in.shape = ( 480, 640, 3 ) 94 | 95 | self._frameCount += 1 96 | 97 | # get the size of the frame 98 | h, w, _ = frame_in.shape 99 | 100 | # divide the frame into X x Y grid 101 | yjump = int( h / self._Y ) 102 | xjump = int( w / self._X ) 103 | yjump = yjump 104 | xjump = xjump 105 | 106 | # for spiting out data 107 | outBuffer = "" 108 | 109 | # brute force a background 110 | #draw_rect( frame_in, ( 0, 0 ), ( 640, 480 ), ( 0, 0, 0 ) ) 111 | 112 | for y in range( 0, self._Y ): 113 | for x in range( 0, self._X ): 114 | 115 | # F1 sigma - sum for each portion of the grid 116 | # TODO: change to count the number of pixels change to monitor a % of area changed 117 | # sum is mixing both degree of change AND area changed 118 | single_frame_sum = int( frame_in[ int( y * yjump ) : int( ( y + 1 ) * yjump ), int( x * xjump ) : int( ( x + 1 ) * xjump ) ].sum() ) 119 | 120 | # Fdelta - calc a delta for each portion after Z # of frames - 1st derivitate, change over time 121 | frame2frame_difference = abs( single_frame_sum - self._prevFrameSigma[ y ][ x ] ) 122 | 123 | if self._timeSpan2Mask[ y ][ x ] == True: 124 | frame_in[ int( y * yjump ) : int( ( y + 1 ) * yjump ), int( x * xjump ) : int( ( x + 1 ) * xjump ) ] = 255 125 | 126 | if self._watchFrame == ( y, x ): 127 | # start with a clear image 128 | #frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] = 0 129 | vis = frame_in[ int( y * yjump ) : int( ( y + 1 ) * yjump ), int( x * xjump ) : int( ( x + 1 ) * xjump ) ] 130 | 131 | # show midway mark for refrence 132 | cv2.line( vis, ( 0, yjump - int( yjump / 2 ) ), ( xjump - 1, yjump - int( yjump / 2 ) ), ( 128, 128, 128 ), 1 ) 133 | 134 | # plot the values and the moving average 135 | for xx in range( 1, xjump ): 136 | cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf[ xx ] ) ), ( 255, 255, 0 ), 1 ) 137 | cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf_MovingAverage[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf_MovingAverage[ xx ] ) ), ( 0, 25, 255 ), 2 ) 138 | 139 | if self._timeSpan2Mask[ y ][ x ] == True: 140 | cv2.circle( vis, ( xjump - 6, 4 ), 3, ( 0, 25, 255 ), -1 ) 141 | 142 | # running calculation for Sigma Delta 143 | self._SigmaDeltaAccumulator[ y ][ x ] += frame2frame_difference 144 | 145 | # at time trigger Delta Sigma Delta calcuation 146 | if self._frameCount % ( self._deltaT * 15 ) == 0: 147 | 148 | if self._SigmaDeltaAccumulator[ y ][ x ] > self._SigmaDelta[ y ][ x ]: 149 | delta_sigma_delta = self._SigmaDeltaAccumulator[ y ][ x ] - self._SigmaDelta[ y ][ x ] 150 | else: 151 | delta_sigma_delta = self._SigmaDelta[ y ][ x ] - self._SigmaDeltaAccumulator[ y ][ x ] 152 | 153 | #outBuffer += "{0}:{1}:{2}\t".format( x, y, delta_sigma_delta ) 154 | outBuffer += "{0}\t".format( delta_sigma_delta ) 155 | 156 | if self._countCumulativeAverage > 1: # skip two times 157 | self._cumulativeAverage[ y ][ x ] = ( delta_sigma_delta + ( self._countCumulativeAverage * self._cumulativeAverage[ y ][ x ] ) ) / ( self._countCumulativeAverage + 1 ) 158 | 159 | diff = 0 160 | if delta_sigma_delta > self._cumulativeAverage[ y ][ x ]: 161 | diff = delta_sigma_delta - self._cumulativeAverage[ y ][ x ] 162 | else: 163 | diff = self._cumulativeAverage[ y ][ x ] - delta_sigma_delta 164 | 165 | if self._watchFrame == ( y, x ): 166 | print( "{0},{1}\t\tdelta_sigma_delta:{2}\t\tdiff:{3}".format( y, x, delta_sigma_delta, diff ) ) 167 | 168 | self._timeSpan2Mask[ y ][ x ] = diff < 0.4 * self._cumulativeAverage[ y ][ x ] 169 | 170 | # http://en.wikipedia.org/wiki/Moving_average 171 | if self._watchFrame == ( y, x ): 172 | print( "{0},{1}\t\t{2}\t{3}\t\t{4}\t\t{5}".format( y, x, delta_sigma_delta, diff, self._cumulativeAverage[ y ][ x ], self._timeSpan2Mask[ y ][ x ] ) ) 173 | #print( "SigDeltSig: %d" % delta_sigma_delta ) 174 | 175 | ''' 176 | ############ Sample data to verify it's working right 177 | ############ testing with a sin wave 178 | gg = math.sin( math.radians( self._frameCount % 360 ) ) * 10000 + 10000 # random numbers -10000 and +10000 179 | self._graph_ringbuf = np.roll( self._graph_ringbuf, 1 ) 180 | 181 | self._graph_ringbuf[ 0 ] = int( yjump * gg / self._scale ) 182 | 183 | self._movingAverageSlidingWindow = np.roll( self._movingAverageSlidingWindow, 1 ) 184 | self._movingAverageSlidingWindow[ 0 ] = gg 185 | self._graph_ringbuf_MovingAverage = np.roll( self._graph_ringbuf_MovingAverage, 1 ) 186 | self._graph_ringbuf_MovingAverage[ 0 ] = self.movingAverage( ( yjump * self._movingAverageSlidingWindow / self._scale ), self._slidingWindow ) 187 | ########### testing 188 | ''' 189 | 190 | self._graph_ringbuf = np.roll( self._graph_ringbuf, 1 ) 191 | self._graph_ringbuf[ 0 ] = int( yjump * delta_sigma_delta / self._scale ) 192 | 193 | #self._movingAverageSlidingWindow = np.roll( self._movingAverageSlidingWindow, 1 ) 194 | #self._movingAverageSlidingWindow[ 0 ] = gg 195 | 196 | self._graph_ringbuf_MovingAverage = np.roll( self._graph_ringbuf_MovingAverage, 1 ) 197 | #self._graph_ringbuf_MovingAverage[ 0 ] = self.movingAverage( ( yjump * self._movingAverageSlidingWindow / scale ), self._slidingWindow ) 198 | self._graph_ringbuf_MovingAverage[ 0 ] = yjump * self._cumulativeAverage[ y ][ x ] / self._scale 199 | 200 | #print( "MovAvg: %d" % self._graph_ringbuf_MovingAverage[ 0 ] ) 201 | 202 | print( "Count: %d CumCount: %d" % ( self._Counter, self._countCumulativeAverage ) ) 203 | self._Counter += 1 204 | 205 | self._SigmaDelta[ y ][ x ] = self._SigmaDeltaAccumulator[ y ][ x ] 206 | self._SigmaDeltaAccumulator[ y ][ x ] = 0 207 | 208 | self._prevFrameSigma[ y ][ x ] = single_frame_sum 209 | last_X = x 210 | last_Y = y 211 | 212 | if self._frameCount % ( self._deltaT * 15 ) == 0: 213 | self._countCumulativeAverage += 1 214 | 215 | if self._enableDumpFile and len( outBuffer ) > 0: 216 | outBuffer += "\n" 217 | self._fileDataDump.write( outBuffer ) 218 | 219 | # return the processed frame to be either passed to the next filter 220 | # or displayed 221 | return frame_in 222 | 223 | -------------------------------------------------------------------------------- /vidpipe/OpenCVQImage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | import numpy as np 5 | from PyQt5 import QtGui 6 | 7 | # Converts a NumPy array to QImage 8 | 9 | class OpenCVQImage( QtGui.QImage ): 10 | 11 | def __init__( self, opencvBgrImg ): 12 | # depth = cv2.IPL_DEPTH_8U 13 | 14 | if len( opencvBgrImg.shape ) == 3: 15 | h, w, nChannels = opencvBgrImg.shape 16 | opencvRgbImg = np.zeros( ( h, w, 3 ), np.uint8 ) 17 | opencvRgbImg = cv2.cvtColor( opencvBgrImg, cv2.COLOR_BGR2RGB ) 18 | else: 19 | # img_format = QtGui.QImage.Format_Mono 20 | h, w = opencvBgrImg.shape 21 | # opencvRgbImg = np.zeros( ( h, w, 3 ), np.uint8 ) 22 | opencvRgbImg = cv2.cvtColor( opencvBgrImg, cv2.COLOR_GRAY2RGB ) 23 | # cv2.mixChannels( [ opencvBgrImg ], [ opencvRgbImg ], [ 0, 2 ] ) 24 | 25 | # if depth != cv.IPL_DEPTH_8U or nChannels != 3: 26 | # raise ValueError("the input image must be 8-bit, 3-channel") 27 | 28 | self._imgData = opencvRgbImg.tostring() 29 | super( OpenCVQImage, self ).__init__( self._imgData, w, h, QtGui.QImage.Format_RGB888 ) 30 | -------------------------------------------------------------------------------- /vidpipe/SampleFilter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | from FrameProcessor import FrameProcessor 5 | 6 | 7 | class SampleFilter( FrameProcessor ): 8 | 9 | # the color shown in the filter list box (left hand list box of filters) 10 | # this is the color that should be used in the processFrame function for showing details in the frame_in 11 | _color = ( 0, 255, 0 ) 12 | 13 | # the name of the filter that shows up in the filter list 14 | _name = "Sample Filter" 15 | 16 | def __init__( self ): 17 | super( SampleFilter, self ).__init__() 18 | 19 | # Called for every frame of video 20 | # Don't do any long running processing in this function 21 | # Delays in this function will increase the value shown in the video as "time: X ms" 22 | 23 | # frame_in is a numpy array 24 | # The frame_in is BGR and contains the video frame details 25 | # Any alteration of the frame_in data is passed to the next filter and is shown in the videoFiltered frame 26 | 27 | # To show an area of interest or activity, update the self._activeRects 28 | 29 | # To show the entire area that's affected by the filter, update the self._boundingBox 30 | # The bounding box will affect the preview video (left video window) 31 | def processFrame( self, frame_in ): 32 | # frame_in is BGR 33 | 34 | # get the size of the frame 35 | h, w, colors = frame_in.shape 36 | 37 | # set a bounding box to show in the live video where activity or areas of interest are located 38 | # For instance, if the filter is tracking a ball, set the bounding box around the ball 39 | # If the filter affects the entire frame, like a black and white filter, do not set the bounding box 40 | # self._boundingBox = ( 100, 100, w / 2 , h / 2 ) 41 | 42 | # Once processing is complete, the processed frame is returned and passed to the next filter 43 | # in the chain. The changes from this filter will be input to the next filter 44 | 45 | # if you want to take actions that will affect the video frame but do not want to pass it to the next filter 46 | # copy the frame_in and take the actions on the copy 47 | return frame_in 48 | 49 | -------------------------------------------------------------------------------- /vidpipe/SimpleMotionDetection.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import cv2 6 | import numpy as np 7 | from FrameProcessor import FrameProcessor 8 | from helpers import combine, draw_rect 9 | 10 | ''' 11 | Filter to detect motion. The 'simple' means it's a very simple implemenation: 12 | Just track the difference between this frame and the previous frame and if it's 13 | above a threashold, mark it as 'activity' 14 | 15 | ''' 16 | 17 | class SimpleMotionDetection( FrameProcessor ): 18 | 19 | # 10 x 10 grid 20 | _X = 10 # 64 pixels for a 640x480 frame 21 | _Y = 10 # 48 pixels for a 640x480 frame 22 | _threshold = 0.05 # 5% value change - LOWER is more sensitive 23 | # the percence difference between this frame and the prev frame that counts as motion 24 | 25 | _scale = 100000 26 | 27 | _frameCount = 0 # always running frame count 28 | 29 | def __init__( self ): 30 | super( SimpleMotionDetection, self ).__init__() 31 | self._name = "SimpleMotion Filter" 32 | 33 | self._prev_frame_sum_of_values = np.zeros( ( self._Y, self._X ), np.uint64 ) # max of 4.2 bill 34 | 35 | self._enabled = False 36 | self._watchFrame_enabled = False 37 | self._watchFrame = ( 0, 8 ) # NOTE: Order is Y, X 38 | 39 | self._graph_ringbuf_MovingAverage = np.zeros( 100, np.float32 ) 40 | self._graph_ringbuf = np.zeros( 100, np.uint8 ) 41 | 42 | def prop_ChangeThresh_set( self, thresh ): 43 | self._threshold = thresh / 1000 44 | 45 | def prop_ChangeThresh_get( self): 46 | return self._threshold * 1000 47 | 48 | def type_ChangeThresh( self ): 49 | return int 50 | 51 | def prop_Scale_set( self, scale ): 52 | self._scale = scale 53 | self._graph_ringbuf = np.zeros( 100, np.uint8 ) 54 | self._frameCount = 0 55 | 56 | def prop_Scale_get( self): 57 | return self._scale 58 | 59 | def type_Scale( self ): 60 | return int 61 | 62 | def prop_Watch_set( self, val ): 63 | # TODO: error check 64 | self._watchFrame = tuple( val )[ :: -1 ] 65 | self._graph_ringbuf_MovingAverage = np.zeros( 100, np.float32 ) 66 | self._graph_ringbuf = np.zeros( 100, np.uint8 ) 67 | self._frameCount = 0 68 | 69 | def prop_Watch_get( self): 70 | return self._watchFrame[ :: -1 ] 71 | 72 | def type_Watch( self ): 73 | return tuple 74 | 75 | def processFrame( self, frame_in ): 76 | # frame_in is BGR 77 | # frame_in.shape = ( 480, 640, 3 ) 78 | 79 | self._activeRects = [] 80 | self._boundingBox = [] 81 | 82 | # get the size of the frame 83 | h, w, _ = frame_in.shape 84 | 85 | # divide the frame into X x Y grid 86 | yjump = int( h / self._Y ) 87 | xjump = int( w / self._X ) 88 | 89 | # brute force a background 90 | #draw_rect( frame_in, ( 0, 0 ), ( 640, 480 ), ( 0, 0, 0 ) ) 91 | 92 | for y in range( 0, self._Y ): 93 | for x in range( 0, self._X ): 94 | 95 | # sum for each portion of the grid 96 | # TODO: change to count the number of pixels change to monitor a % of area changed 97 | # sum is mixing both degree of change AND area changed 98 | sum_of_values = int( frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ].sum() ) 99 | 100 | # calc a delta for each portion after Z # of frames - 1st derivitate, change over time 101 | dev_from_hist = abs( sum_of_values - self._prev_frame_sum_of_values[ y ][ x ] ) 102 | 103 | #if the | delta | < Threshold then blank out that sector 104 | if dev_from_hist < self._threshold * self._prev_frame_sum_of_values[ y ][ x ]: 105 | frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] = 0 106 | else: 107 | self._activeRects.append( ( x * xjump, y * yjump, xjump, yjump ) ) 108 | 109 | # debug trace window that show a histogram 110 | if self._watchFrame_enabled and self._watchFrame == ( y, x ): 111 | self._graph_ringbuf = np.roll( self._graph_ringbuf, 1 ) 112 | graphValue = yjump * dev_from_hist / self._scale 113 | self._graph_ringbuf[ 0 ] = graphValue 114 | 115 | movAverage = ( graphValue + self._frameCount * self._graph_ringbuf_MovingAverage[ 0 ] ) / ( self._frameCount + 1 ) 116 | self._graph_ringbuf_MovingAverage = np.roll( self._graph_ringbuf_MovingAverage, 1 ) 117 | self._graph_ringbuf_MovingAverage[ 0 ] = movAverage 118 | 119 | vis = frame_in[ y * yjump : ( y + 1 ) * yjump, x * xjump : ( x + 1 ) * xjump ] 120 | 121 | # plot the values and the moving average 122 | for xx in range( 1, xjump ): 123 | cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf[ xx ] ) ), ( 255, 255, 0 ), 1 ) 124 | #cv2.line( vis, ( xx - 1, yjump - int( self._graph_ringbuf_MovingAverage[ xx - 1 ] ) ), ( xx, yjump - int( self._graph_ringbuf_MovingAverage[ xx ] ) ), ( 0, 25, 255 ), 2 ) 125 | 126 | # show midway mark for refrence 127 | cv2.line( vis, ( 0, yjump - int( yjump / 2 ) ), ( xjump - 1, yjump - int( yjump / 2 ) ), ( 128, 128, 128 ), 1 ) 128 | cv2.line( vis, ( 0, yjump - int( self._graph_ringbuf_MovingAverage[ 0 ] ) ), ( xjump - 1, yjump - int( self._graph_ringbuf_MovingAverage[ 0 ] ) ), ( 0, 25, 255 ), 2 ) 129 | 130 | self._prev_frame_sum_of_values[ y ][ x ] = sum_of_values 131 | last_X = x 132 | last_Y = y 133 | 134 | self._boundingBox = combine( self._activeRects ) 135 | 136 | # return the processed frame to be either passed to the next filter 137 | # or displayed 138 | self._frameCount += 1 139 | return frame_in 140 | 141 | -------------------------------------------------------------------------------- /vidpipe/dialog_main_auto.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'dialog_main.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.15.10 6 | # 7 | # WARNING: Any manual changes made to this file will be lost when pyuic5 is 8 | # run again. Do not edit this file unless you know what you are doing. 9 | 10 | 11 | from PyQt5 import QtCore, QtGui, QtWidgets 12 | from CameraWidget import CameraWidget 13 | 14 | 15 | class Ui_Dialog(object): 16 | def setupUi(self, Dialog): 17 | Dialog.setObjectName("Dialog") 18 | Dialog.resize(1592, 473) 19 | self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog) 20 | self.verticalLayout_2.setObjectName("verticalLayout_2") 21 | self.horizontalLayout_3 = QtWidgets.QHBoxLayout() 22 | self.horizontalLayout_3.setObjectName("horizontalLayout_3") 23 | self.label_2 = QtWidgets.QLabel(Dialog) 24 | self.label_2.setObjectName("label_2") 25 | self.horizontalLayout_3.addWidget(self.label_2) 26 | self.label = QtWidgets.QLabel(Dialog) 27 | self.label.setObjectName("label") 28 | self.horizontalLayout_3.addWidget(self.label) 29 | self.verticalLayout_2.addLayout(self.horizontalLayout_3) 30 | self.horizontalLayout = QtWidgets.QHBoxLayout() 31 | self.horizontalLayout.setObjectName("horizontalLayout") 32 | self.verticalLayout_3 = QtWidgets.QVBoxLayout() 33 | self.verticalLayout_3.setObjectName("verticalLayout_3") 34 | self.horizontalLayout_6 = QtWidgets.QHBoxLayout() 35 | self.horizontalLayout_6.setObjectName("horizontalLayout_6") 36 | self.frame = QtWidgets.QFrame(Dialog) 37 | self.frame.setMinimumSize(QtCore.QSize(640, 360)) 38 | self.frame.setMaximumSize(QtCore.QSize(640, 360)) 39 | self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) 40 | self.frame.setFrameShadow(QtWidgets.QFrame.Raised) 41 | self.frame.setObjectName("frame") 42 | self.videoLive = CameraWidget(self.frame) 43 | self.videoLive.setGeometry(QtCore.QRect(0, 0, 640, 360)) 44 | self.videoLive.setMinimumSize(QtCore.QSize(640, 360)) 45 | self.videoLive.setMaximumSize(QtCore.QSize(640, 360)) 46 | self.videoLive.setObjectName("videoLive") 47 | self.horizontalLayout_6.addWidget(self.frame) 48 | self.frame_2 = QtWidgets.QFrame(Dialog) 49 | self.frame_2.setMinimumSize(QtCore.QSize(640, 360)) 50 | self.frame_2.setMaximumSize(QtCore.QSize(640, 360)) 51 | self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) 52 | self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) 53 | self.frame_2.setObjectName("frame_2") 54 | self.videoFiltered = CameraWidget(self.frame_2) 55 | self.videoFiltered.setGeometry(QtCore.QRect(0, 0, 640, 360)) 56 | self.videoFiltered.setMinimumSize(QtCore.QSize(640, 360)) 57 | self.videoFiltered.setMaximumSize(QtCore.QSize(640, 360)) 58 | self.videoFiltered.setObjectName("videoFiltered") 59 | self.horizontalLayout_6.addWidget(self.frame_2) 60 | self.verticalLayout_3.addLayout(self.horizontalLayout_6) 61 | self.horizontalLayout_2 = QtWidgets.QHBoxLayout() 62 | self.horizontalLayout_2.setObjectName("horizontalLayout_2") 63 | self.label_Status = QtWidgets.QLabel(Dialog) 64 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed) 65 | sizePolicy.setHorizontalStretch(0) 66 | sizePolicy.setVerticalStretch(0) 67 | sizePolicy.setHeightForWidth(self.label_Status.sizePolicy().hasHeightForWidth()) 68 | self.label_Status.setSizePolicy(sizePolicy) 69 | self.label_Status.setObjectName("label_Status") 70 | self.horizontalLayout_2.addWidget(self.label_Status) 71 | self.btnShowHist = QtWidgets.QPushButton(Dialog) 72 | self.btnShowHist.setObjectName("btnShowHist") 73 | self.horizontalLayout_2.addWidget(self.btnShowHist) 74 | self.pushButton_2 = QtWidgets.QPushButton(Dialog) 75 | self.pushButton_2.setObjectName("pushButton_2") 76 | self.horizontalLayout_2.addWidget(self.pushButton_2) 77 | self.verticalLayout_3.addLayout(self.horizontalLayout_2) 78 | self.horizontalLayout.addLayout(self.verticalLayout_3) 79 | self.filterList = QtWidgets.QListWidget(Dialog) 80 | self.filterList.setObjectName("filterList") 81 | self.horizontalLayout.addWidget(self.filterList) 82 | self.horizontalLayout.setStretch(0, 1) 83 | self.verticalLayout_2.addLayout(self.horizontalLayout) 84 | 85 | self.retranslateUi(Dialog) 86 | QtCore.QMetaObject.connectSlotsByName(Dialog) 87 | 88 | def retranslateUi(self, Dialog): 89 | _translate = QtCore.QCoreApplication.translate 90 | Dialog.setWindowTitle(_translate("Dialog", "Dialog")) 91 | self.label_2.setText(_translate("Dialog", "Preview")) 92 | self.label.setText(_translate("Dialog", "Processed")) 93 | self.label_Status.setText(_translate("Dialog", "This is status text!!!")) 94 | self.btnShowHist.setText(_translate("Dialog", "Color Histogram")) 95 | self.pushButton_2.setText(_translate("Dialog", "Don\'t Push Me")) 96 | -------------------------------------------------------------------------------- /vidpipe/gui/Makefile: -------------------------------------------------------------------------------- 1 | dlg_main : dialog_main.ui 2 | mv ../dialog_main_auto.py ../dialog_main_auto.old || true 3 | pyuic5 dialog_main.ui -o dialog_main_auto.py 4 | sed -i '' 's/QtWidgets.QWidget/CameraWidget/g' dialog_main_auto.py 5 | echo "from CameraWidget import CameraWidget" | sed -i '' '/from PyQt5 import QtCore, QtGui, QtWidgets/r /dev/stdin' dialog_main_auto.py 6 | cp dialog_main_auto.py ../ 7 | 8 | # NOTE: the rediculous sed command to insert the line is due to the Mac OS/BSD version of sed 9 | -------------------------------------------------------------------------------- /vidpipe/gui/dialog_main.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | Dialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 1592 10 | 473 11 | 12 | 13 | 14 | Dialog 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Preview 23 | 24 | 25 | 26 | 27 | 28 | 29 | Processed 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 640 46 | 360 47 | 48 | 49 | 50 | 51 | 640 52 | 360 53 | 54 | 55 | 56 | QFrame::StyledPanel 57 | 58 | 59 | QFrame::Raised 60 | 61 | 62 | 63 | 64 | 0 65 | 0 66 | 640 67 | 360 68 | 69 | 70 | 71 | 72 | 640 73 | 360 74 | 75 | 76 | 77 | 78 | 640 79 | 360 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 640 90 | 360 91 | 92 | 93 | 94 | 95 | 640 96 | 360 97 | 98 | 99 | 100 | QFrame::StyledPanel 101 | 102 | 103 | QFrame::Raised 104 | 105 | 106 | 107 | 108 | 0 109 | 0 110 | 640 111 | 360 112 | 113 | 114 | 115 | 116 | 640 117 | 360 118 | 119 | 120 | 121 | 122 | 640 123 | 360 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 0 138 | 0 139 | 140 | 141 | 142 | This is status text!!! 143 | 144 | 145 | 146 | 147 | 148 | 149 | Color Histogram 150 | 151 | 152 | 153 | 154 | 155 | 156 | Don't Push Me 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /vidpipe/gui/dialog_main_auto.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Form implementation generated from reading ui file 'dialog_main.ui' 4 | # 5 | # Created by: PyQt5 UI code generator 5.15.10 6 | # 7 | # WARNING: Any manual changes made to this file will be lost when pyuic5 is 8 | # run again. Do not edit this file unless you know what you are doing. 9 | 10 | 11 | from PyQt5 import QtCore, QtGui, QtWidgets 12 | from CameraWidget import CameraWidget 13 | 14 | 15 | class Ui_Dialog(object): 16 | def setupUi(self, Dialog): 17 | Dialog.setObjectName("Dialog") 18 | Dialog.resize(1592, 473) 19 | self.verticalLayout_2 = QtWidgets.QVBoxLayout(Dialog) 20 | self.verticalLayout_2.setObjectName("verticalLayout_2") 21 | self.horizontalLayout_3 = QtWidgets.QHBoxLayout() 22 | self.horizontalLayout_3.setObjectName("horizontalLayout_3") 23 | self.label_2 = QtWidgets.QLabel(Dialog) 24 | self.label_2.setObjectName("label_2") 25 | self.horizontalLayout_3.addWidget(self.label_2) 26 | self.label = QtWidgets.QLabel(Dialog) 27 | self.label.setObjectName("label") 28 | self.horizontalLayout_3.addWidget(self.label) 29 | self.verticalLayout_2.addLayout(self.horizontalLayout_3) 30 | self.horizontalLayout = QtWidgets.QHBoxLayout() 31 | self.horizontalLayout.setObjectName("horizontalLayout") 32 | self.verticalLayout_3 = QtWidgets.QVBoxLayout() 33 | self.verticalLayout_3.setObjectName("verticalLayout_3") 34 | self.horizontalLayout_6 = QtWidgets.QHBoxLayout() 35 | self.horizontalLayout_6.setObjectName("horizontalLayout_6") 36 | self.frame = QtWidgets.QFrame(Dialog) 37 | self.frame.setMinimumSize(QtCore.QSize(640, 360)) 38 | self.frame.setMaximumSize(QtCore.QSize(640, 360)) 39 | self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) 40 | self.frame.setFrameShadow(QtWidgets.QFrame.Raised) 41 | self.frame.setObjectName("frame") 42 | self.videoLive = CameraWidget(self.frame) 43 | self.videoLive.setGeometry(QtCore.QRect(0, 0, 640, 360)) 44 | self.videoLive.setMinimumSize(QtCore.QSize(640, 360)) 45 | self.videoLive.setMaximumSize(QtCore.QSize(640, 360)) 46 | self.videoLive.setObjectName("videoLive") 47 | self.horizontalLayout_6.addWidget(self.frame) 48 | self.frame_2 = QtWidgets.QFrame(Dialog) 49 | self.frame_2.setMinimumSize(QtCore.QSize(640, 360)) 50 | self.frame_2.setMaximumSize(QtCore.QSize(640, 360)) 51 | self.frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel) 52 | self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised) 53 | self.frame_2.setObjectName("frame_2") 54 | self.videoFiltered = CameraWidget(self.frame_2) 55 | self.videoFiltered.setGeometry(QtCore.QRect(0, 0, 640, 360)) 56 | self.videoFiltered.setMinimumSize(QtCore.QSize(640, 360)) 57 | self.videoFiltered.setMaximumSize(QtCore.QSize(640, 360)) 58 | self.videoFiltered.setObjectName("videoFiltered") 59 | self.horizontalLayout_6.addWidget(self.frame_2) 60 | self.verticalLayout_3.addLayout(self.horizontalLayout_6) 61 | self.horizontalLayout_2 = QtWidgets.QHBoxLayout() 62 | self.horizontalLayout_2.setObjectName("horizontalLayout_2") 63 | self.label_Status = QtWidgets.QLabel(Dialog) 64 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Fixed) 65 | sizePolicy.setHorizontalStretch(0) 66 | sizePolicy.setVerticalStretch(0) 67 | sizePolicy.setHeightForWidth(self.label_Status.sizePolicy().hasHeightForWidth()) 68 | self.label_Status.setSizePolicy(sizePolicy) 69 | self.label_Status.setObjectName("label_Status") 70 | self.horizontalLayout_2.addWidget(self.label_Status) 71 | self.btnShowHist = QtWidgets.QPushButton(Dialog) 72 | self.btnShowHist.setObjectName("btnShowHist") 73 | self.horizontalLayout_2.addWidget(self.btnShowHist) 74 | self.pushButton_2 = QtWidgets.QPushButton(Dialog) 75 | self.pushButton_2.setObjectName("pushButton_2") 76 | self.horizontalLayout_2.addWidget(self.pushButton_2) 77 | self.verticalLayout_3.addLayout(self.horizontalLayout_2) 78 | self.horizontalLayout.addLayout(self.verticalLayout_3) 79 | self.filterList = QtWidgets.QListWidget(Dialog) 80 | self.filterList.setObjectName("filterList") 81 | self.horizontalLayout.addWidget(self.filterList) 82 | self.horizontalLayout.setStretch(0, 1) 83 | self.verticalLayout_2.addLayout(self.horizontalLayout) 84 | 85 | self.retranslateUi(Dialog) 86 | QtCore.QMetaObject.connectSlotsByName(Dialog) 87 | 88 | def retranslateUi(self, Dialog): 89 | _translate = QtCore.QCoreApplication.translate 90 | Dialog.setWindowTitle(_translate("Dialog", "Dialog")) 91 | self.label_2.setText(_translate("Dialog", "Preview")) 92 | self.label.setText(_translate("Dialog", "Processed")) 93 | self.label_Status.setText(_translate("Dialog", "This is status text!!!")) 94 | self.btnShowHist.setText(_translate("Dialog", "Color Histogram")) 95 | self.pushButton_2.setText(_translate("Dialog", "Don\'t Push Me")) 96 | -------------------------------------------------------------------------------- /vidpipe/helpers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import cv2 4 | 5 | 6 | # expects rect( x1, y1, w, h ) 7 | def combine( rects, thresh = 1 ): 8 | 9 | if len( rects ) == 0: 10 | return ( 0, 0, 0, 0 ) 11 | 12 | rect_array_x = [ [ rect[ 0 ], rect[ 0 ] + rect[ 2 ] ] for rect in rects ] 13 | rect_array_y = [ [ rect[ 1 ], rect[ 1 ] + rect[ 3 ] ] for rect in rects ] 14 | 15 | rect_array_x = [ number for inner in rect_array_x for number in inner ] 16 | rect_array_y = [ number for inner in rect_array_y for number in inner ] 17 | 18 | max_x = max( rect_array_x ) 19 | max_y = max( rect_array_y ) 20 | min_x = min( rect_array_x ) 21 | min_y = min( rect_array_y ) 22 | 23 | return ( min_x, min_y, max_x, max_y ) 24 | 25 | # expects rect( x1, y1, x2, y2 ) 26 | def intersection_rect( rect1, rect2 ): 27 | # rect is ( x, y, w, h ) 28 | # 0 1 2 3 29 | 30 | # rect is ( x1, y1, x2, y2 ) 31 | # 0 1 2 3 32 | x_tl = max( rect1[ 0 ], rect2[ 0 ] ) 33 | y_tl = max( rect1[ 1 ], rect2[ 1 ] ) 34 | x_br = min( rect1[ 2 ], rect2[ 2 ] ) 35 | y_br = min( rect1[ 3 ], rect2[ 3 ] ) 36 | if ( x_tl < x_br and y_tl < y_br ): 37 | #return (x_tl, y_tl, x_br - x_tl, y_br - y_tl); 38 | return (x_tl, y_tl, x_br, y_br); 39 | 40 | return None 41 | 42 | def intersection( rects ): 43 | num_rects = len( rects ) 44 | if num_rects == 0: 45 | return None 46 | if num_rects == 1: 47 | return rects[ 0 ] 48 | 49 | intersect_rect = None 50 | for rect_outer in rects: 51 | if intersect_rect == None: 52 | intersect_rect = rect_outer 53 | continue 54 | 55 | intersect_rect = intersection_rect( rect_outer, intersect_rect ) 56 | 57 | # we only care about when all intersect 58 | if intersect_rect == None: 59 | break 60 | 61 | return intersect_rect 62 | 63 | def draw_rect( dst, x, y, w, h, color ): 64 | cv2.rectangle( dst, ( int( x ), int( y ) ), ( int( w ), int( h ) ), color, -1 ) 65 | 66 | # blatently stolen from opencv/samples/python2/common.py 67 | def clock(): 68 | return cv2.getTickCount() / cv2.getTickFrequency() 69 | 70 | def draw_str(dst, x, y, s): 71 | cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 4.0, (0, 0, 0), thickness = 7, lineType=cv2.LINE_AA) 72 | cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 4.0, (255, 255, 255), thickness = 2, lineType=cv2.LINE_AA) 73 | 74 | 75 | ''' 76 | x_overlap = Math.max(0, Math.min(x12,x22) - Math.max(x11,x21)); 77 | y_overlap = Math.max(0, Math.min(y12,y22) - Math.max(y11,y21)); 78 | ''' 79 | -------------------------------------------------------------------------------- /vidpipe/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from __future__ import division 4 | 5 | import random 6 | import sys 7 | 8 | import cv2 9 | import numpy as np 10 | from ActivityFilter import ActivityFilter 11 | from BackgroundRemove import BackgroundRemove 12 | from BlockNumber import BlockNumber 13 | from BlurFilter import BlurFilter 14 | from CameraDevice import CameraDevice 15 | from dialog_main_auto import Ui_Dialog 16 | from EdgeDetector import EdgeDetector 17 | from FilterListOrderMapper import FilterListOrderMapper 18 | from FrameProcessor import FrameProcessor 19 | from helpers import clock, combine, draw_rect, draw_str, intersection_rect 20 | from Histogram import HistogramFilter 21 | from PyQt5.QtCore import (QEvent, QObject, QPoint, QRegExp, QSignalMapper, Qt, 22 | QVariant, pyqtSignal, pyqtSlot) 23 | from PyQt5.QtGui import QColor, QPalette, QRegExpValidator, QValidator 24 | from PyQt5.QtWidgets import (QAbstractItemView, QApplication, QCheckBox, 25 | QDialog, QFrame, QGroupBox, QHBoxLayout, QLabel, 26 | QLayout, QLineEdit, QListWidgetItem, QMainWindow, 27 | QSpinBox, QVBoxLayout, QWidget) 28 | from SimpleMotionDetection import SimpleMotionDetection 29 | 30 | 31 | class KnobTurner( QObject, Ui_Dialog ): 32 | 33 | _frameCount = 0 # running total frames shown 34 | _frameRate_RunningAvg = -1.0 # decaying average frame rate (displayed on video) 35 | _alpha = 0.01 # how fast to update the screen refresh frame rate display variable 36 | _showHist = False 37 | _histogramWindowName = "Color Histogram" 38 | _cameraId = 1 # the camera ID of the system, typically 0 or 1 39 | 40 | class Mapper( QObject ): 41 | 42 | def __init__(self, caller, called, action = None ): 43 | QObject.__init__( self ) 44 | self._caller = caller 45 | self._called = called 46 | self._action = action 47 | 48 | @property 49 | def caller( self ): 50 | return self._caller 51 | 52 | @property 53 | def called( self ): 54 | return self._called 55 | 56 | @property 57 | def action( self ): 58 | return self._action 59 | 60 | def __init__( self ): 61 | print( ">>>>>>>>>>>>>>>TODO: Restore the latest set of options??" ) 62 | Ui_Dialog.__init__( self ) 63 | QObject.__init__( self ) 64 | 65 | # TODO: read these from a config file or from a subdirectory 66 | self._filters = [ 67 | BlurFilter(), 68 | SimpleMotionDetection(), 69 | ActivityFilter(), 70 | HistogramFilter(), 71 | BlockNumber(), 72 | EdgeDetector(), 73 | BackgroundRemove() 74 | ] 75 | 76 | @pyqtSlot( ) 77 | def resetFilterListModel( self ): 78 | # if we get here then the filter list has been drag-rearranged 79 | 80 | # reset the filter list based off the filterList order 81 | self._filters = [] 82 | prev = None 83 | for indx in range( 0, self.filterList.count() ): 84 | fltr = self.filterList.item( indx ).data( Qt.UserRole ) 85 | self._filters.append( fltr ) 86 | 87 | for indx in range( 0, self.filterList.count() ): 88 | print("Index: %d Name: %s" % ( indx, self.filterList.item( indx ).data( Qt.UserRole ).name ) ) 89 | 90 | def getFilterProperties( self, fltr ): 91 | attribs = [ funct.replace( FrameProcessor.propStartsWith, "" ) for funct in dir( fltr ) if callable( getattr( fltr, funct ) ) and funct.startswith( FrameProcessor.propStartsWith ) ] 92 | 93 | setters = [ ftn.replace( FrameProcessor.propEndsWithSetter, "" ) for ftn in attribs if ftn.endswith( FrameProcessor.propEndsWithSetter ) ] 94 | getters = [ ftn.replace( FrameProcessor.propEndsWithGetter, "" ) for ftn in attribs if ftn.endswith( FrameProcessor.propEndsWithGetter ) ] 95 | 96 | return getters, setters 97 | 98 | def check_state( self, caller ): 99 | validator = caller.validator() 100 | state = validator.validate( caller.text(), 0 )[ 0 ] 101 | if state == QValidator.Acceptable: 102 | color = '#c4df9b' # green 103 | elif state == QValidator.Intermediate: 104 | color = '#fff79a' # yellow 105 | else: 106 | color = '#f6989d' # red 107 | caller.setStyleSheet( 'QLineEdit { background-color: %s }' % color ) 108 | return ( state == QValidator.Acceptable ) 109 | 110 | @pyqtSlot( QObject ) 111 | def saveFilterValue( self, obj ): 112 | assert( isinstance( obj.caller, QSpinBox ) or isinstance( obj.caller, QCheckBox ) or isinstance( obj.caller, QLineEdit ) ) 113 | 114 | if isinstance( obj.caller, QSpinBox ): 115 | newVal = obj.caller.value() 116 | elif isinstance( obj.caller, QCheckBox ): 117 | newVal = obj.caller.isChecked() 118 | elif isinstance( obj.caller, QLineEdit ): 119 | if self.check_state( obj.caller ) != True: 120 | return 121 | newVal = [ int( t ) for t in obj.caller.text().split( "," ) ] 122 | 123 | try: 124 | func = getattr( obj.called, obj.action ) 125 | except AttributeError: 126 | print( "Whoops, for some reason the callback isn't valid." ) 127 | else: 128 | result = func( newVal ) 129 | 130 | # reset the frame rate 131 | self._frameRate_RunningAvg = -1 132 | 133 | def setupUi( self, dlg ): 134 | Ui_Dialog.setupUi( self, dlg ) 135 | 136 | self.btnShowHist.clicked.connect( self.showHistogram ) 137 | 138 | self._filterListOrderMapper = FilterListOrderMapper() 139 | self._filterListOrderMapper.listChanged.connect( self.resetFilterListModel ) 140 | 141 | self.filterList.installEventFilter( self._filterListOrderMapper ) 142 | self.filterList.setDragDropMode( QAbstractItemView.InternalMove ) 143 | 144 | self._optionMapper = QSignalMapper( dlg ) 145 | self._optionMapper.mapped[ QObject ].connect( self.saveFilterValue ) 146 | self._optionSave = [] # this is only for making sure the Mapper object doesn't get garbage collected 147 | 148 | #regx = QRegExp( "([0-9]{1,3}[\,][ ]*){2}[0-9]{1,3}" ) 149 | regx = QRegExp( "([0-9]{1,3}[\,][ ]*){1,2}[0-9]{1,3}" ) 150 | 151 | for fltr in self._filters: 152 | print( "Filter added: %s" % fltr.name ) 153 | 154 | fltr.loadConfig( None ) 155 | 156 | self.label_Status.setText( "Loading filters" ) 157 | getters, setters = self.getFilterProperties( fltr ) 158 | print( "\tAvailable GETable options: ", getters ) 159 | print( "\tAvailable SETable options: ", setters ) 160 | 161 | group = QGroupBox() 162 | vbl = QVBoxLayout( group ) 163 | 164 | # Row ------ 165 | fm = QFrame() 166 | vb = QVBoxLayout( fm ) 167 | vb.setSizeConstraint( QLayout.SetDefaultConstraint ) 168 | 169 | # add the enabled checkbox first always 170 | cb2 = QCheckBox( fltr.name ) 171 | cb2.setCheckState( getattr( fltr, FrameProcessor.propStartsWith + "Enabled" + FrameProcessor.propEndsWithGetter )() ) 172 | if fltr.color(): 173 | cb2.setStyleSheet( 'background-color:#%02x%02x%02x' % ( fltr.color()[ :: -1 ] ) ) 174 | vb.addWidget( cb2 ) 175 | # watch for values changing 176 | cb2.stateChanged.connect( self._optionMapper.map ) 177 | self._optionSave.append( 178 | KnobTurner.Mapper( cb2, fltr, 179 | FrameProcessor.propStartsWith + "Enabled" + FrameProcessor.propEndsWithSetter ) ) 180 | self._optionMapper.setMapping( cb2, self._optionSave[ -1 ] ) 181 | 182 | for item in setters: 183 | prop_type = getattr( fltr, FrameProcessor.propTypeStartsWith + item )() 184 | if prop_type is int: 185 | hz = QHBoxLayout() 186 | lb1 = QLabel( "%s:" % item ) 187 | sp1 = QSpinBox() 188 | sp1.setRange( 0, 10000000 ) # TODO: add this as a query to the filter 189 | sp1.setValue( int( getattr( fltr, FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithGetter )() ) ) 190 | vb.addWidget( lb1 ) 191 | vb.addWidget( sp1 ) 192 | 193 | # watch for values changing 194 | sp1.valueChanged.connect( self._optionMapper.map ) 195 | self._optionSave.append( 196 | KnobTurner.Mapper( sp1, fltr, 197 | FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithSetter ) ) 198 | self._optionMapper.setMapping( sp1, self._optionSave[ -1 ] ) 199 | 200 | elif prop_type is bool: 201 | if item == "Enabled": 202 | continue 203 | else: 204 | cb2 = QCheckBox( item ) 205 | cb2.setCheckState( getattr( fltr, FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithGetter )() ) 206 | vb.addWidget( cb2 ) 207 | 208 | # watch for values changing 209 | cb2.stateChanged.connect( self._optionMapper.map ) 210 | self._optionSave.append( 211 | KnobTurner.Mapper( cb2, fltr, 212 | FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithSetter ) ) 213 | self._optionMapper.setMapping( cb2, self._optionSave[ -1 ] ) 214 | elif prop_type is tuple: 215 | hz = QHBoxLayout() 216 | lb1 = QLabel( "%s:" % item ) 217 | 218 | val = getattr( fltr, FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithGetter )() 219 | le = QLineEdit( "{0}".format( val ).replace( "(","" ).replace( ")", "" ).replace( "[", "" ).replace( "]", "" ) ) 220 | 221 | le.setValidator( QRegExpValidator( regx ) ) 222 | le.textChanged.connect( self._optionMapper.map ) 223 | le.textChanged.emit( le.text() ) 224 | 225 | self._optionSave.append( 226 | KnobTurner.Mapper( le, fltr, 227 | FrameProcessor.propStartsWith + item + FrameProcessor.propEndsWithSetter ) ) 228 | self._optionMapper.setMapping( le, self._optionSave[ -1 ] ) 229 | 230 | vb.addWidget( lb1 ) 231 | vb.addWidget( le ) 232 | # end Row 2 ----- 233 | 234 | vbl.addWidget( fm ) 235 | vbl.setSizeConstraint( QLayout.SetDefaultConstraint ) # default value, being explicit 236 | 237 | lwi = QListWidgetItem() 238 | lwi.setSizeHint( vbl.sizeHint() ) 239 | lwi.setData( Qt.UserRole, QVariant( fltr ) ) # attach the filter to this item in the list 240 | self.filterList.addItem( lwi ) 241 | self.filterList.setItemWidget( lwi, group ) 242 | 243 | self.label_Status.setText( "Loading filters... Done" ) 244 | 245 | self.label_Status.setText( "Starting cameras..." ) 246 | self.startCamera() 247 | self.label_Status.setText( "Starting cameras... Done" ) 248 | 249 | self.showWindows() 250 | 251 | self.label_Status.setText( "Ready" ) 252 | 253 | def startCamera( self ): 254 | print( "Starting camera" ) 255 | #vid = "drop.avi" # use video instead of camera 256 | vid = None 257 | self._cameraDevice = CameraDevice( vid, self._cameraId ) 258 | 259 | self.videoLive.setCamera( self._cameraDevice ) 260 | self.videoLive.newFrame.connect( self.processPreviewFrame ) 261 | 262 | self.videoFiltered.setCamera( self._cameraDevice ) 263 | self.videoFiltered.newFrame.connect( self.processFilteredFrame ) 264 | 265 | def showHistogram( self ): 266 | self._showHist = not self._showHist 267 | 268 | if not self._showHist: 269 | cv2.destroyWindow( self._histogramWindowName ) 270 | 271 | def updateHistogram( self ): 272 | bin_count = self.hist.shape[ 0 ] 273 | bin_w = 40 274 | img = np.zeros( ( 256, bin_count * bin_w, 3 ), np.uint8 ) 275 | for i in range( 0, bin_count ): 276 | h = int( self.hist[ i ] ) 277 | cv2.rectangle( img, ( i * bin_w + 2, 255 ), # top left corner 278 | ( ( i + 1 ) * bin_w - 2, 255 - h ), # bottom right corner 279 | ( int( 180.0 * i / bin_count ), 255, 255 ), # color 280 | -1 ) # -1 is fill shape 281 | img = cv2.cvtColor( img, cv2.COLOR_HSV2BGR ) 282 | cv2.imshow( self._histogramWindowName, img ) 283 | 284 | def showWindows( self ): 285 | self.videoLive.show() 286 | self.videoFiltered.show() 287 | print( "Live video size: {}".format( self.videoLive.sizeHint() ) ) 288 | 289 | @pyqtSlot( np.ndarray ) 290 | def processPreviewFrame(self, frame ): 291 | 292 | # update histogram every 15th frame (picked arbitrarily) 293 | if self._showHist == True and self._frameCount % 15 == 0: 294 | hsv = cv2.cvtColor( frame, cv2.COLOR_BGR2HSV ) 295 | hist = cv2.calcHist( [ hsv ], [ 0 ], None, [ 16 ], [ 0, 180 ] ) 296 | cv2.normalize( hist, hist, 0, 255, cv2.NORM_MINMAX ); 297 | self.hist = hist.reshape( -1 ) 298 | 299 | self.updateHistogram() 300 | 301 | intersect_box = None 302 | colors = [] 303 | boxes = [] 304 | for fltr in self._filters: 305 | if fltr.prop_Enabled_get(): 306 | box = fltr.getBoundingBox() # CAREFUL!!: returns (x1, y1, x2, y2) NOT x, y, w, h **** 307 | if len( box ) != 0: 308 | colors.append( fltr.color() ) 309 | boxes.append( box ) 310 | if intersect_box == None: 311 | intersect_box = box 312 | else: 313 | intersect_box = intersection_rect( intersect_box, box ) 314 | 315 | # fade the color for all but the intersection of active areas 316 | if intersect_box != None: 317 | rectW = intersect_box[ 2 ] - intersect_box[ 0 ] 318 | rectH = intersect_box[ 3 ] - intersect_box[ 1 ] 319 | saverect = frame[ intersect_box[ 1 ] : intersect_box[ 1 ] + rectH, intersect_box[ 0 ] : intersect_box[ 0 ] + rectW ] 320 | 321 | frame = cv2.cvtColor( frame, cv2.COLOR_BGR2GRAY ) 322 | ## TODO: this crashes now with 'TypeError: No loop matching the specified signature and casting was found for ufunc true_divide' - new numpy 323 | # frame /= 2 # cut the overal luminocity of the preview video by half to highlight the in-frame portion 324 | frame = cv2.cvtColor( frame, cv2.COLOR_GRAY2BGR ) 325 | 326 | # restore the color to only the intersection 327 | if intersect_box != None: 328 | frame[ intersect_box[ 1 ] : intersect_box[ 1 ] + rectH, intersect_box[ 0 ] : intersect_box[ 0 ] + rectW ] = saverect 329 | 330 | # paint the boxes back on top of the gray image 331 | for index, box in enumerate( boxes ): 332 | cv2.rectangle( frame, ( box[ 0 ], box[ 1 ] ), ( box[ 2 ], box[ 3 ] ), colors[ index ], 2 ) 333 | 334 | self.videoLive.setNewFrame( frame ) 335 | 336 | @pyqtSlot( np.ndarray ) 337 | def processFilteredFrame(self, frame ): 338 | t = clock() 339 | 340 | for fltr in self._filters: 341 | if fltr.prop_Enabled_get() == True: # I'm cheating here because I know this property exists for all filters 342 | frame = fltr.processFrame( frame ) 343 | 344 | # show time 345 | delta_t = clock() - t 346 | if self._frameRate_RunningAvg == -1: 347 | self._frameRate_RunningAvg = delta_t 348 | self._frameRate_RunningAvg = ( self._alpha * delta_t ) + ( 1.0 - self._alpha ) * self._frameRate_RunningAvg 349 | # TODO: adjust the location of the text based off the size of the font 350 | draw_str( frame, 20, 44, 'time: %.1f ms' % ( self._frameRate_RunningAvg * 1000 ) ) 351 | 352 | # last guy puts the frame up 353 | self.videoFiltered.setNewFrame( frame ) 354 | 355 | @pyqtSlot() 356 | def shutDown( self ): 357 | print( ">>>>>>>>>>>>>>>TODO: Print and/or save the latest set of options!!" ) 358 | 359 | for fltr in self._filters: 360 | fltr.saveConfig( None ) 361 | 362 | print( "Shutting down" ) 363 | 364 | def main(): 365 | app = QApplication( sys.argv ) 366 | 367 | window = QDialog() 368 | ui = KnobTurner() 369 | ui.setupUi( window ) 370 | 371 | app.lastWindowClosed.connect( ui.shutDown ) 372 | 373 | window.show() 374 | window.raise_() 375 | sys.exit( app.exec_() ) 376 | 377 | if __name__ == '__main__': 378 | main() 379 | --------------------------------------------------------------------------------