├── .gitignore
├── LICENSE
├── README.md
├── data
├── img
│ ├── aps_00.gif
│ ├── ev_00.gif
│ └── schema_framework.png
├── noise_neg_0.1lux.npy
├── noise_neg_161lux.npy
├── noise_neg_3klux.mat
├── noise_neg_3klux.npy
├── noise_pos_0.1lux.npy
├── noise_pos_161lux.npy
├── noise_pos_3klux.mat
└── noise_pos_3klux.npy
├── examples
└── 00_video_2_events
│ ├── 0_get_video_youtube.py
│ ├── 1_example_video_to_events.py
│ └── 2_make_video.py
├── simuDVSICNS_Linux.yml
├── simuDVSICNS_Windows.yml
└── src
├── arbiter.py
├── dat_files.py
├── dvs_sensor.py
├── event_buffer.py
└── event_display.py
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .DS_Store
3 | .idea/*
4 | src/__pycache__/*
5 | /data/hummingbird_video.mp4
6 | /examples/00_video_2_events/outputs/
7 |
--------------------------------------------------------------------------------
/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 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # IEBCS
2 | ICNS Event Based Camera Simulator
3 |
4 | The code base has been recently cut down to a maintainable reference python implementation. For now, if you want the blender interoperability or the C++ implementation, download a previous version of this repository at your own risk.
5 |
6 | This repository contains:
7 | * /data/: Stores distributions used to sample the noise of the sensor and other resources.
8 | * /examples/: An example of loading frames, and passing them as input to the simulator.
9 |
10 | This Figure summarizes the differences with others tools, such as
11 | [ESIM](https://github.com/uzh-rpg/rpg_esim) and
12 | [V2E](https://github.com/SensorsINI/v2e):
13 |
14 | 
15 |
16 | ## -- Requirements --
17 |
18 | Tested with Python 3.12.
19 |
20 | Create a virtual environment using conda:
21 | ```
22 | pip install opencv-python
23 | pip install tqdm
24 | ```
25 |
26 | Additional requirements:
27 | * yt-dlp: example 00 downloads a video from youtube.
28 | ```
29 | pip install yt-dlp
30 | ```
31 |
32 | ## -- Examples --
33 |
34 | ### 00: Video -> events
35 |
36 | Simulate events from a video.
37 |
38 | The example sets up a sensor with the following parameters:
39 | * latency = 100 μs
40 | * jitter = 10 μs
41 | * refractory period = 100 μs
42 | * time constant log front-end = 40 μs
43 | * positive/negative log threshold = 0.4
44 | * threshold noise = 0.01
45 | * The noise is sampled from 2 distributions acquired with a real sensor under 161lux.
46 |
47 |
48 |
49 | The artifacts are due to the low framerate compared to the speed of the wings. This can be improved by using high frame rate video, or by generating intermediate frames.
50 |
51 | To use, first make sure your working directory is:
52 | ```
53 | examples/00_video_to_events
54 | ```
55 |
56 | Then run the python files contained within this directory in order.
57 | A video showing events, as well as the event file in binary format, should be generated within the `./output` directory.
--------------------------------------------------------------------------------
/data/img/aps_00.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/img/aps_00.gif
--------------------------------------------------------------------------------
/data/img/ev_00.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/img/ev_00.gif
--------------------------------------------------------------------------------
/data/img/schema_framework.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/img/schema_framework.png
--------------------------------------------------------------------------------
/data/noise_neg_0.1lux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_neg_0.1lux.npy
--------------------------------------------------------------------------------
/data/noise_neg_161lux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_neg_161lux.npy
--------------------------------------------------------------------------------
/data/noise_neg_3klux.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_neg_3klux.mat
--------------------------------------------------------------------------------
/data/noise_neg_3klux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_neg_3klux.npy
--------------------------------------------------------------------------------
/data/noise_pos_0.1lux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_pos_0.1lux.npy
--------------------------------------------------------------------------------
/data/noise_pos_161lux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_pos_161lux.npy
--------------------------------------------------------------------------------
/data/noise_pos_3klux.mat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_pos_3klux.mat
--------------------------------------------------------------------------------
/data/noise_pos_3klux.npy:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/neuromorphicsystems/IEBCS/8fdab5c3d078435d091fa8a94ad657e1fedf0c59/data/noise_pos_3klux.npy
--------------------------------------------------------------------------------
/examples/00_video_2_events/0_get_video_youtube.py:
--------------------------------------------------------------------------------
1 |
2 | import yt_dlp
3 |
4 | URLS = ['https://www.youtube.com/watch?v=RtUQ_pz5wlo']
5 |
6 | def format_selector(ctx):
7 | """ Select the best video and the best audio that won't result in an mkv.
8 | NOTE: This is just an example and does not handle all cases """
9 |
10 | # formats are already sorted worst to best
11 | formats = ctx.get('formats')[::-1]
12 |
13 | # acodec='none' means there is no audio
14 | best_video = next(f for f in formats
15 | if f['vcodec'] != 'none' and f['acodec'] == 'none')
16 |
17 |
18 | # These are the minimum required fields for a merged format
19 | yield {
20 | 'format_id': f'{best_video["format_id"]}',
21 | 'ext': best_video['ext'],
22 | 'requested_formats': [best_video],
23 | # Must be + separated list of protocols
24 | 'protocol': f'{best_video["protocol"]}',
25 | }
26 |
27 |
28 | ydl_opts = {
29 | 'format': format_selector,
30 | 'outtmpl': {'default': '../../data/hummingbird_video.%(ext)s'},
31 | }
32 |
33 | with yt_dlp.YoutubeDL(ydl_opts) as ydl:
34 | ydl.download(URLS)
--------------------------------------------------------------------------------
/examples/00_video_2_events/1_example_video_to_events.py:
--------------------------------------------------------------------------------
1 | # Joubert Damien, 03-02-2020 - updated by AvS 22-02-2024
2 | """
3 | Script converting a video into events.
4 | The framerate of the video might not be the real framerate of the original video.
5 | The user specifies this parameter at the beginning.
6 | Please run get_video_youtube.py before executing this script.
7 | """
8 | import cv2
9 | import sys
10 | sys.path.append("../../src")
11 | from event_buffer import EventBuffer
12 | from dvs_sensor import DvsSensor
13 | from event_display import EventDisplay
14 | from arbiter import SynchronousArbiter, BottleNeckArbiter, RowArbiter
15 | from tqdm import tqdm
16 | import os
17 |
18 | if not os.path.exists("./outputs"):
19 | os.mkdir("./outputs")
20 |
21 | filename = "../../data/hummingbird_video.mp4"
22 | th_pos = 0.4 # ON threshold = 50% (ln(1.5) = 0.4)
23 | th_neg = 0.4 # OFF threshold = 50%
24 | th_noise= 0.01 # standard deviation of threshold noise
25 | lat = 100 # latency in us
26 | tau = 40 # front-end time constant at 1 klux in us
27 | jit = 10 # temporal jitter standard deviation in us
28 | bgnp = 0.1 # ON event noise rate in events / pixel / s
29 | bgnn = 0.01 # OFF event noise rate in events / pixel / s
30 | ref = 100 # refractory period in us
31 | dt = 1000 # time between frames in us
32 | time = 0
33 |
34 | cap = cv2.VideoCapture(filename)
35 |
36 | # Initialise the DVS sensor
37 | dvs = DvsSensor("MySensor")
38 | dvs.initCamera(int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
39 | lat=lat, jit = jit, ref = ref, tau = tau, th_pos = th_pos, th_neg = th_neg, th_noise = th_noise,
40 | bgnp=bgnp, bgnn=bgnn)
41 | # To use the measured noise distributions, uncomment the following line
42 | dvs.init_bgn_hist("../../data/noise_pos_161lux.npy", "../../data/noise_neg_161lux.npy")
43 |
44 | # Skip the first 50 frames of the video to remove video artifacts
45 | for i in range(50):
46 | ret, im = cap.read()
47 |
48 | # Convert the image from uint8, such that 255 = 1e4, representing 10 klux
49 | im = cv2.cvtColor(im, cv2.COLOR_RGB2LUV)[:, :, 0] / 255.0 * 1e4
50 |
51 | # Set as the initial condition of the sensor
52 | dvs.init_image(im)
53 |
54 | # Create the event buffer
55 | ev_full = EventBuffer(1)
56 |
57 | # Create the arbiter - optional, pick from one below
58 | # ea = BottleNeckArbiter(0.01, time) # This is a mock arbiter
59 | # ea = RowArbiter(0.01, time) # Old arbiter that handles rows in random order
60 | ea = SynchronousArbiter(0.1, time, im.shape[0]) # DVS346-like arbiter
61 |
62 | # Create the display
63 | render_timesurface = 1
64 | ed = EventDisplay("Events",
65 | cap.get(cv2.CAP_PROP_FRAME_WIDTH),
66 | cap.get(cv2.CAP_PROP_FRAME_HEIGHT),
67 | dt,
68 | render_timesurface)
69 |
70 | if cap.isOpened():
71 | # Loop over num_frames frames
72 | num_frames = 50
73 | for frame in tqdm(range(num_frames), desc="Converting video to events"):
74 | # Get frame from the video
75 | ret, im = cap.read()
76 | if im is None:
77 | break
78 | # Convert the image from uint8, such that 255 = 1e4, representing 10 klux
79 | im = cv2.cvtColor(im, cv2.COLOR_RGB2LUV)[:, :, 0] / 255.0 * 1e4
80 | # Calculate the events
81 | ev = dvs.update(im, dt)
82 | # Simulate the arbiter
83 | # num_produced = ev.i
84 | # ev = ea.process(ev, dt)
85 | # num_released = ev.i
86 | # statistics for the arbiter
87 | # print("{} produced, {} released".format(num_produced, num_released))
88 | # Display the events
89 | ed.update(ev, dt)
90 | # Add the events to the buffer for the full video
91 | ev_full.increase_ev(ev)
92 |
93 | cap.release()
94 | # Save the events to a .dat file
95 | ev_full.write('outputs/ev_{}_{}_{}_{}_{}_{}.dat'.format(lat, jit, ref, tau, th_pos, th_noise))
--------------------------------------------------------------------------------
/examples/00_video_2_events/2_make_video.py:
--------------------------------------------------------------------------------
1 | """
2 | Make video of the events
3 | """
4 | import cv2
5 | import numpy as np
6 | import sys
7 | sys.path.append("../../src")
8 | from dat_files import load_dat_event
9 |
10 | fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
11 | filename = './outputs/ev_100_10_100_40_0.4_0.01.dat'
12 | ts, x, y, p = load_dat_event(filename)
13 | res = [1920, 1080]
14 | out = cv2.VideoWriter('{}.avi'.format(filename[:-4]), fourcc, 20.0, (res[0], res[1]))
15 | tw = 1000
16 | img = np.zeros((res[1], res[0]), dtype=float)
17 | tsurface = np.zeros((res[1], res[0]), dtype=np.int64)
18 | indsurface = np.zeros((res[1], res[0]), dtype=np.int8)
19 |
20 | for t in range(ts[0], ts[-1], tw):
21 | # Get events in the current time window
22 | ind = np.where((ts > t) & (ts < t + tw))
23 |
24 | # Create a matrix holding the time stamps of the events
25 | tsurface[:, :] = 0
26 | tsurface[y[ind], x[ind]] = t + tw
27 |
28 | # And another holding their polarity (use -1 for OFF events)
29 | indsurface[y[ind], x[ind]] = 2.0 * p[ind] - 1
30 |
31 | # Find which pixels to process
32 | ind = np.where(tsurface > 0)
33 |
34 | # And update the image
35 | img[:, :] = 125
36 | img[ind] = 125 + indsurface[ind] * np.exp(-(t + tw - tsurface[ind].astype(np.float32))/ (tw/30)) * 125
37 |
38 | # Convert to color and display
39 | img_c = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_GRAY2BGR)
40 | img_c = cv2.putText(img_c, '{} us'.format(t + tw), (0, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
41 | (255, 255, 255))
42 | img_c = cv2.applyColorMap(img_c, cv2.COLORMAP_VIRIDIS)
43 | cv2.imshow("debug", img_c)
44 | cv2.waitKey(1)
45 |
46 | # Write video to file
47 | out.write(img_c)
48 | out.release()
--------------------------------------------------------------------------------
/simuDVSICNS_Linux.yml:
--------------------------------------------------------------------------------
1 | name: IEBCS
2 | channels:
3 | - conda-forge
4 | dependencies:
5 | - zstd=1.5.5
6 | - xz=5.2.6
7 | - xorg-libxau=1.0.11
8 | - unicodedata2=15.0.0
9 | - tornado=6.3.3
10 | - python=3.10.12
11 | - pthread-stubs=0.4
12 | - pillow=10.0.1
13 | - pandas=2.1.1
14 | - openssl=3.1.3
15 | - openjpeg=2.5.0
16 | - numpy=1.26.0
17 | - matplotlib-base=3.5.3
18 | - matplotlib=3.5.3
19 | - loris=0.5.3
20 | - llvm-openmp=16.0.6
21 | - libzlib=1.2.13
22 | - libxcb=1.15
23 | - libwebp-base=1.3.2
24 | - libtiff=4.6.0
25 | - libssh2=1.11.0
26 | - libsqlite=3.43.0
27 | - libopenblas=0.3.24
28 | - libjpeg-turbo=2.1.5.1
29 | - libgfortran5=13.2.0
30 | - libgfortran
31 | - libev=4.33
32 | - libedit=3.1.20221030
33 | - libdeflate=1.18
34 | - libcurl=8.3.0
35 | - libbrotlienc=1.1.0
36 | - libbrotlidec=1.1.0
37 | - libbrotlicommon=1.1.0
38 | - libaec=1.0.6
39 | - lerc=4.0.0
40 | - lcms2=2.15
41 | - krb5=1.21.2
42 | - kiwisolver=1.4.5
43 | - hdf5=1.14.2
44 | - h5py=3.9.0
45 | - fonttools=4.42.1
46 | - cached-property=1.5.2
47 | - c-ares=1.19.1
48 | - brotli-bin=1.1.0
49 | - brotli=1.1.0
50 | - pip
51 | - pip:
52 | - aedat==2.0.2
53 | - bpy==3.6.0
54 | - build==1.0.3
55 | - charset-normalizer==3.2.0
56 | - cython==3.0.2
57 | - idna==3.4
58 | - mathutils==3.3.0
59 | - opencv-python==4.8.0.76
60 | - pyproject-hooks==1.0.0
61 | - python-mnist==0.7
62 | - requests==2.31.0
63 | - tomli==2.0.1
64 | - urllib3==2.0.4
65 | - zstandard==0.21.0
66 |
67 |
--------------------------------------------------------------------------------
/simuDVSICNS_Windows.yml:
--------------------------------------------------------------------------------
1 | name: IEBCS
2 | channels:
3 | - conda-forge
4 | - defaults
5 | dependencies:
6 | - brotli=1.1.0
7 | - bzip2=1.0.8
8 | - c-ares=1.19.1
9 | - ca-certificates=2023.7.22
10 | - cached-property=1.5.2
11 | - cycler=0.11.0
12 | - fonttools=4.42.1
13 | - freetype=2.12.1
14 | - h5py=3.9.0
15 | - hdf5=1.14.2
16 | - kiwisolver=1.4.5
17 | - krb5=1.21.2
18 | - lcms2=2.15
19 | - lerc=4.0.0
20 | - libaec=1.0.6
21 | - libbrotlicommon=1.1.0
22 | - libbrotlidec=1.1.0
23 | - libbrotlienc=1.1.0
24 | - libcurl=8.3.0
25 | - libdeflate=1.18
26 | - libexpat=2.5.0
27 | - libffi=3.4.2
28 | - libjpeg-turbo=2.1.5.1
29 | - libpng=1.6.39
30 | - libsqlite=3.43.0
31 | - libssh2=1.11.0
32 | - libtiff=4.6.0
33 | - libwebp-base=1.3.2
34 | - libzlib=1.2.13
35 | - loris=0.5.3
36 | - matplotlib=3.5.3
37 | - numpy=1.26.0
38 | - openjpeg=2.5.0
39 | - openssl=3.1.3
40 | - pandas=2.1.1
41 | - pillow=10.0.1
42 | - pytz=2023.3.post1
43 | - setuptools=68.2.2
44 | - six=1.16.0
45 | - tk=8.6.12
46 | - tornado=6.3.3
47 | - tqdm=4.66.1
48 | - tzdata=2023c
49 | - wheel=0.41.2
50 | - xz=5.2.6
51 | - zstd=1.5.5
52 | - pip:
53 | - aedat==2.0.2
54 | - bpy==3.6.0
55 | - build==1.0.3
56 | - charset-normalizer==3.2.0
57 | - cython==3.0.2
58 | - idna==3.4
59 | - opencv-python==4.8.0.76
60 | - pyproject-hooks==1.0.0
61 | - python-mnist==0.7
62 | - requests==2.31.0
63 | - tomli==2.0.1
64 | - urllib3==2.0.4
65 | - zstandard==0.21.0
66 | - mathutils==3.3.0
67 |
--------------------------------------------------------------------------------
/src/arbiter.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from event_buffer import EventBuffer
3 |
4 |
5 | class BottleNeckArbiter():
6 | """Simple bottleneck arbiter - doesn't match anything in the real world"""
7 | # t_per_event = 0.1 # Time spent to process one event (us)
8 | # ev_acc = EventBuffer(0) # Events accumulated
9 | # time = 0 # Current time (us)
10 |
11 | def __init__(self, t_per_event, time):
12 | """ Initialise the arbiter
13 | Args:
14 | t_per_event: # Time spent to process one event (us)
15 | time: starting time (us)
16 | """
17 | self.t_per_event = t_per_event
18 | self.time = time
19 | self.ev_acc = EventBuffer(0)
20 |
21 | def process(self, new_ev, dt):
22 | """
23 | Args:
24 | new_event: incomming events as EventBuffer
25 | dt: time since the last update (us)
26 | """
27 | tps_process = float(self.t_per_event) * (self.ev_acc.i + new_ev.i)
28 | self.time = self.time + dt
29 | release_ev = EventBuffer(0)
30 | if tps_process == 0:
31 | return release_ev
32 | self.ev_acc.increase_ev(new_ev)
33 | nb_event_pross = min(self.ev_acc.i, int(dt / tps_process))
34 | delta = 0
35 | if self.ev_acc.ts[0] < self.time - dt:
36 | delta = self.time - dt - self.ev_acc.ts[0]
37 | release_ev.add_array(
38 | self.ev_acc.ts[:nb_event_pross] + delta + tps_process * np.arange(0, nb_event_pross, 1),
39 | self.ev_acc.y[:nb_event_pross],
40 | self.ev_acc.x[:nb_event_pross],
41 | self.ev_acc.p[:nb_event_pross]
42 | )
43 | self.ev_acc.remove_elt(nb_event_pross)
44 | return release_ev
45 |
46 |
47 | class RowArbiter():
48 | """The row arbiter is a simple arbiter, processing events row by row."""
49 | # t_per_event = 0.1 # Time spent to process one event (us)
50 | # ev_acc = EventBuffer(0) # Events accumulated
51 | # time = 0 # Current time (us)
52 | def __init__(self, t_per_event, time):
53 | """ Initialise the arbiter
54 | Args:
55 | t_per_event: # Time spent to process one event (us)
56 | time: starting time (us)
57 | """
58 | self.t_per_event = t_per_event
59 | self.time = time
60 | self.ev_acc = EventBuffer(0)
61 |
62 | def process(self, new_ev, dt):
63 | """
64 | Args:
65 | new_event: incomming events as EventBuffer
66 | dt: time since the last update (us)
67 | """
68 | tps_process = float(self.t_per_event) * (self.ev_acc.i + new_ev.i)
69 | self.time = self.time + dt
70 | release_ev = EventBuffer(0)
71 | if tps_process == 0:
72 | return release_ev
73 | self.ev_acc.increase_ev(new_ev)
74 | nb_event_pross = int(dt / tps_process)
75 | i = 0
76 | delta = 0
77 | if self.ev_acc.ts[0] < self.time - dt:
78 | delta = self.time - dt - self.ev_acc.ts[0]
79 | while self.ev_acc.i > 0 and self.ev_acc.ts[0] <= self.time and nb_event_pross > i:
80 | i += 1
81 | ind = np.where((self.ev_acc.y == self.ev_acc.y[0]) & (self.ev_acc.ts <= self.time))
82 | ts_inter = np.full(ind[0].shape, self.ev_acc.ts[0] + delta + tps_process * i)
83 | release_ev.add_array(ts_inter, self.ev_acc.y[ind], self.ev_acc.x[ind], self.ev_acc.p[ind])
84 | self.ev_acc.remove_row(self.ev_acc.y[0], -1)
85 | return release_ev
86 |
87 |
88 | class SynchronousArbiter():
89 | """Synchronous row arbiter - based on DAVIS346 arbiter"""
90 | # clock_period = 0.001 # Clock's period (us)
91 | # ev_acc = EventBuffer(0) # Events accumulated
92 | # time = 0 # Current time (us)
93 | # cur_row = 0 # current row processed
94 | # max_row= 200 # Number of rows in sensor
95 | def __init__(self, clock_period, time, max_row):
96 | """ Initialise the arbiter
97 | Args:
98 | max_row: number of rows
99 | clock_period: # Clock's period (us)
100 | time: starting time (us)
101 | """
102 | self.clock_period = clock_period
103 | self.time = time
104 | self.cur_row = 0
105 | self.max_row = max_row
106 | self.ev_acc = EventBuffer(0)
107 |
108 | def process(self, new_ev, dt):
109 | """
110 | Args:
111 | new_event: incomming events as EventBuffer
112 | dt: time since the last update (us)
113 | """
114 | rows_to_process = int(dt // self.clock_period)
115 | t_max = self.time + dt
116 | release_ev = EventBuffer(0)
117 | self.ev_acc.increase_ev(new_ev)
118 |
119 | times = self.time + np.arange(1, rows_to_process + 1) * self.clock_period
120 | rows = np.mod(np.arange(self.cur_row + 1, self.cur_row + rows_to_process + 1), self.max_row)
121 |
122 | for time, row in zip(times, rows):
123 | self.time = time
124 | self.cur_row = row
125 | mask = (self.ev_acc.y[:self.ev_acc.i] == row) & (self.ev_acc.ts[:self.ev_acc.i] < time)
126 |
127 | if np.any(mask):
128 | ts_inter = np.full(np.sum(mask), time)
129 | release_ev.add_array(
130 | ts_inter, self.ev_acc.y[:self.ev_acc.i][mask],
131 | self.ev_acc.x[:self.ev_acc.i][mask],
132 | self.ev_acc.p[:self.ev_acc.i][mask]
133 | )
134 | self.ev_acc.remove_row(row, time)
135 |
136 | if self.ev_acc.i == 0:
137 | break
138 |
139 | self.time = t_max
140 | return release_ev
--------------------------------------------------------------------------------
/src/dat_files.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import struct
3 | from datetime import datetime
4 |
5 | def load_dat_event(filename, start=0, stop=-1, display=False):
6 | """ Load .dat events from file.
7 | Args:
8 | filename: Path of the .dat file
9 | start: starting timestamp (us)
10 | stop: if different than -1, last timestamp
11 | display: display file info
12 | Returns:
13 | ts, x, y, pol numpy arrays of timestamps, positions, and polarities
14 | """
15 | f = open(filename, 'rb')
16 | if f == -1:
17 | print("The file does not exist")
18 | return
19 | else:
20 | if display: print("Load DAT Events: " + filename)
21 | l = f.readline()
22 | all_lines = l
23 | while l[0] == 37:
24 | p = f.tell()
25 | if display: print(l)
26 | l = f.readline()
27 | all_lines = all_lines + l
28 | # f.close()
29 | all_lines = str(all_lines)
30 | # f = open(filename, 'rb')
31 | f.seek(p, 0)
32 | evType = np.uint8(f.read(1)[0])
33 | evSize = np.uint8(f.read(1)[0])
34 | p = f.tell()
35 | l_last = f.tell()
36 | if start > 0:
37 | t = np.uint32(struct.unpack(" 0:
45 | t = np.uint32(struct.unpack(" 0:
61 | v = int(all_lines[ind+8])
62 | if v >= 2:
63 | x_mask = np.uint32(0x00007FF)
64 | y_mask = np.uint32(0x0FFFC000)
65 | pol_mask = np.uint32(0x10000000)
66 | x_shift = 0
67 | y_shift = 14
68 | pol_shift = 28
69 | else:
70 | x_mask = np.uint32(0x00001FF)
71 | y_mask = np.uint32(0x0001FE00)
72 | pol_mask = np.uint32(0x00020000)
73 | x_shift = 0
74 | y_shift = 9
75 | pol_shift = 17
76 | x = data[1::2] & x_mask
77 | x = x >> x_shift
78 | y = data[1::2] & y_mask
79 | y = y >> y_shift
80 | pol = data[1::2] & pol_mask
81 | pol = pol >> pol_shift
82 | if len(ts) > 0:
83 | if display:
84 | print("First Event: ", ts[0], " us")
85 | print("Last Event: ", ts[-1], " us")
86 | print("Number of Events: ", ts.shape[0])
87 | return ts, x, y, pol
88 |
89 |
90 | def write_event_dat(filename, ts, x, y, pol,
91 | event_type='dvs', width=None, height=None):
92 | """ Write the events in a .DAT file
93 | The file header begins with %, then event type (one byte uint8) and event lenght
94 | (one byte uint8), then the data are stores ts (4 bytes uint32) and x-y-pol (4 bytes uint32)
95 | Args:
96 | filename: path of the file to create
97 | ts: stimestamp
98 | x, y: positions of the pixels
99 | p: polarities (0 or 1)
100 | """
101 | f = open(filename, 'wb')
102 | if f == -1:
103 | print("Cannot open the file")
104 | return
105 | if event_type in ['dvs', 'cd', 'td']:
106 | f.write(bytes("% Data file containing DVS events.\n", encoding='utf8'))
107 | elif event_type in ['aps', 'em']:
108 | f.write(bytes("% Data file containing EM events.\n", encoding='utf8'))
109 | else:
110 | raise Exception("Specify a valid event type: 'dvs', 'cd', 'td', 'aps' or 'em'")
111 |
112 | f.write(bytes("% Version 2\n", encoding='utf8'))
113 | f.write(bytes("% Date " + str(datetime.now().replace(microsecond=0)) + '\n', encoding='utf8'))
114 |
115 | if width is None:
116 | width = x.max() + 1
117 | if height is None:
118 | height = y.max() + 1
119 | f.write(bytes("% Height " + str(height) + '\n', encoding='utf8'))
120 | f.write(bytes("% Width " + str(width) + '\n', encoding='utf8'))
121 |
122 | f.write(bytes(np.uint8([0]))) # Event Type
123 | f.write(bytes(np.uint8([8]))) # Event length
124 | arr = np.zeros(2 * ts.shape[0], dtype=np.uint32)
125 | arr[::2] = ts
126 | x_mask = np.uint32(0x00007FF)
127 | y_mask = np.uint32(0x0FFFC000)
128 | pol_mask = np.uint32(0x10000000)
129 | x_shift = 0
130 | y_shift = 14
131 | pol_shift = 28
132 | buf = np.array(x, dtype=np.uint32) << x_shift
133 | arr[1::2] += x_mask & buf
134 | buf = np.array(y, dtype=np.uint32) << y_shift
135 | arr[1::2] += y_mask & buf
136 | buf = np.array(pol, dtype=np.uint32) << pol_shift
137 | arr[1::2] += pol_mask & buf
138 | arr.tofile(f)
139 | f.close()
140 |
141 | if __name__ == '__main__':
142 | ts, x, y, pol = load_dat_event("ev_100_10_100_300_0.3_0.01.dat", start=0, stop=-1, display=True)
143 | print(ts.shape)
144 |
--------------------------------------------------------------------------------
/src/dvs_sensor.py:
--------------------------------------------------------------------------------
1 | # Damien JOUBERT 17-01-2020 - Updated by AvS 23-02-2024
2 | import numpy as np
3 | from event_buffer import EventBuffer
4 | from tqdm import tqdm
5 |
6 | # Global variables
7 | # Log bin for the noise distributions
8 | bins = []
9 | for dec in range(-3, 5, 1):
10 | bins.append(np.arange(10 ** dec, 10 ** (dec + 1), 10 ** dec))
11 | bins = np.array(bins)
12 | FREQ = bins.reshape(bins.shape[0] * bins.shape[1])
13 |
14 | # Noise generation methods
15 | NOISE_FREQ = 1 # Pixels have the same +/- noise frequency but with different phases
16 | NOISE_MEASURE = 2 # Pixels have a noise distribution measured in one lighting conditions
17 |
18 |
19 | class DvsSensor:
20 | """ Class to initialise and simulate the DVS sensor """
21 | # shape = (50, 50) # Size of the imager
22 | # m_th_pos = 0.2 # Mean positive sensitivity (%)
23 | # m_th_neg = -0.2 # Mean negative sensitivity (%)
24 | # m_th_noise = 0.02 # Mean reset noise standard deviation of the transistor (%)
25 | # m_latency = 100 # Mean Latency (us)
26 | # tau = 100 # Time constant (us) of the logarithmic part at 1 klux
27 | # m_jitter = 30 # Mean jitter (us)
28 | # m_bgn_pos = 0.1 # Mean positive background frequency (Hz)
29 | # m_bgn_neg = 0.01 # Mean negative background frequency (Hz)
30 | # m_bgn_pos_per = np.uint64(1e6 / m_bgn_pos) # Mean positive background period (us)
31 | # m_bgn_neg_per = np.uint64(1e6 / m_bgn_neg) # Mean negative background period (us)
32 | # ref = 50 # Refractory period (us)
33 | # time = 0 # Time of the internal counter (us)
34 | # noise_model = NOISE_FREQ # Model of noise used
35 | # last_v = np.zeros(shape, dtype=np.double) # Voltage of each pixel during the last reset
36 | # cur_v = np.zeros(shape, dtype=np.double) # Voltage of each pixel at the time t
37 | # cur_th_pos = np.zeros(shape, dtype=np.double) # Current Positive Threshold
38 | # cur_th_neg = np.zeros(shape, dtype=np.double) # Current Negative Threshold
39 | # cur_ref = np.zeros(shape, dtype=np.uint64) # Time when the pixel will have to be reset
40 | # bgn_pos_next = np.zeros(shape, dtype=np.uint64) # Next expected positive noise event
41 | # bgn_neg_next = np.zeros(shape, dtype=np.uint64) # Next expected negative noise event
42 | # bgn_hist_pos = np.zeros((1, 1, 45), dtype=float) # Positive noise cumulative distributions
43 | # bgn_hist_neg = np.zeros((1, 1, 45), dtype=float) # Negative noise cumulative distributions
44 | # time_px = np.zeros(shape, dtype=np.uint64) # Time t at the pixel (us)
45 | # tau_p = np.zeros(shape, dtype=np.double) # Time constant of each pixel (us)
46 |
47 | def __init__(self, name):
48 | """ Init the sensor by creating the Blender Camera
49 | Args:
50 | name: string to identify the sensor
51 | """
52 | self.name = name
53 |
54 | def set_shape(self, x, y):
55 | """ Set the shape of the sensor
56 | Args:
57 | x, y: size of the imager
58 | """
59 | self.shape = (x, y)
60 |
61 | def initCamera(self, x, y, lat, jit, ref, tau, th_pos, th_neg, th_noise, bgnp, bgnn):
62 | """ Set the properties of the DVS sensor
63 |
64 | In this version the sensor positive and negative event's properties are symmetrical
65 | Args:
66 | th_pos: Mean threshold (log change)
67 | th_neg: Mean threshold (log change)
68 | th_n: Threshold noise (log change)
69 | lat: asymptotic (infinite contrast) latency (us)
70 | tau: Time constant of the log conversion (us)
71 | jit: asymptotic jitter (us)
72 | bgn: Mean frequency of the noise (Hz)
73 | """
74 | self.shape = (x, y)
75 | self.m_th_pos = th_pos
76 | self.m_th_neg = -th_neg
77 | self.m_th_noise = th_noise
78 | self.m_latency = lat
79 | self.tau = tau
80 | self.m_jitter = jit
81 | self.m_bgn_pos = bgnp
82 | self.m_bgn_neg = bgnn
83 | self.m_bgn_pos_per = np.uint64(1e6 / bgnp)
84 | self.m_bgn_neg_per = np.uint64(1e6 / bgnn)
85 | self.ref = ref
86 | self.shape = (self.shape[1], self.shape[0])
87 | self.last_v = np.zeros(self.shape, dtype=np.double)
88 | self.cur_v = np.zeros(self.shape, dtype=np.double)
89 | self.cur_ref = np.zeros(self.shape, dtype=np.uint64)
90 | self.time_px = np.zeros(self.shape, dtype=np.uint64)
91 | self.tau_p = np.zeros(self.shape, dtype=np.double)
92 | self.cur_ref[:] = np.iinfo(np.uint64).max
93 | self.init_bgn()
94 | self.init_thresholds()
95 | self.time = 0
96 |
97 | def init_bgn(self):
98 | """ Initialise the phases of the background noise
99 | This noise model does not include noise differences between pixel: every pixel will fire noise events a the
100 | same frequency but with a random phase
101 | """
102 | self.noise_model = NOISE_FREQ
103 | self.bgn_pos_next = np.array(np.random.randint(0, self.m_bgn_pos_per, self.shape), dtype=np.uint64)
104 | self.bgn_neg_next = np.array(np.random.randint(0, self.m_bgn_neg_per, self.shape), dtype=np.uint64)
105 |
106 | def init_bgn_hist(self, filename_noise_pos, filename_noise_neg):
107 | """ Load measured distributions of the noise,
108 | Pick randomly one noise distribution for each pixel and Initialise also randomly the phases of the
109 | background noise
110 | Args:
111 | filename_noise_pos: path of the positive noise's filename
112 | filename_noise_neg: path of the negative noise's filename
113 | """
114 | self.noise_model = NOISE_MEASURE
115 | noise_pos = np.load(filename_noise_pos)
116 | noise_pos = np.reshape(noise_pos, (noise_pos.shape[0] * noise_pos.shape[1], noise_pos.shape[2]))
117 | if len(noise_pos) == 0:
118 | print(filename_noise_pos, " is not correct")
119 | return
120 | noise_neg = np.load(filename_noise_neg)
121 | noise_neg = np.reshape(noise_neg, (noise_neg.shape[0] * noise_neg.shape[1], noise_neg.shape[2]))
122 | if len(noise_neg) == 0:
123 | print(filename_noise_neg, " is not correct")
124 | return
125 |
126 | # Load histogram and Update next noise event
127 | self.bgn_hist_pos = np.zeros((self.shape[0] * self.shape[1], 72), dtype=float)
128 | self.bgn_hist_neg = np.zeros((self.shape[0] * self.shape[1], 72), dtype=float)
129 | self.bgn_pos_next = np.zeros((self.shape[0], self.shape[1]), dtype=np.uint64)
130 | self.bgn_neg_next = np.zeros((self.shape[0], self.shape[1]), dtype=np.uint64)
131 |
132 | # Pick two spectra for each pixel (one for ON and one for OFF events)
133 | id_n = np.random.uniform(0, noise_neg.shape[0], size=(self.shape[0] * self.shape[1])).astype(int)
134 | id_p = np.random.uniform(0, noise_pos.shape[0], size=(self.shape[0] * self.shape[1])).astype(int)
135 | self.bgn_hist_pos = noise_pos[id_p, :]
136 | self.bgn_hist_neg = noise_neg[id_n, :]
137 |
138 | # Normalise noise spectra
139 | s_p = np.sum(self.bgn_hist_pos, axis=1)
140 | s_n = np.sum(self.bgn_hist_neg, axis=1)
141 | id_p = np.where(s_p == 0)
142 | self.bgn_hist_pos[id_p, 0] = 1
143 | id_n = np.where(s_n == 0)
144 | self.bgn_hist_neg[id_n, 0] = 1
145 | id_p = np.where(s_p > 0)
146 | self.bgn_hist_pos[id_p, :] = self.bgn_hist_pos[id_p, :] / \
147 | np.repeat(self.bgn_hist_pos[id_p, -2].reshape((1, id_p[0].shape[0], 1)),
148 | self.bgn_hist_pos.shape[1],
149 | axis=2)
150 | id_n = np.where(s_n > 0)
151 | self.bgn_hist_neg[id_n, :] = self.bgn_hist_neg[id_n, :] / \
152 | np.repeat(self.bgn_hist_neg[id_n, -2].reshape((1, id_n[0].shape[0], 1)),
153 | self.bgn_hist_neg.shape[1],
154 | axis=2)
155 |
156 | # Draw the next noise event time for each pixel
157 | for x in tqdm(range(0, self.shape[0], 1), desc="Noise Init"):
158 | for y in range(0, self.shape[1], 1):
159 | self.bgn_pos_next[x, y] = np.uint64(self.get_next_noise(x, y, 1) * np.random.uniform(0, 1))
160 | self.bgn_neg_next[x, y] = np.uint64(self.get_next_noise(x, y, 0) * np.random.uniform(0, 1))
161 |
162 | def init_thresholds(self):
163 | """ Initialise the thresholds of the comparators
164 | The positive and negative threshold share the same noise, which can be changed if necessary
165 | """
166 | self.cur_th_pos = np.clip(np.array(np.random.normal(self.m_th_pos, self.m_th_noise, self.shape),
167 | dtype=np.double), 0, 1000)
168 | self.cur_th_neg = np.clip(np.array(np.random.normal(self.m_th_neg, self.m_th_noise, self.shape),
169 | dtype=np.double), -1000, 0)
170 |
171 | def init_image(self, img):
172 | """ Initialise the first flux values of the sensor
173 | Args:
174 | img: image whose greylevel corresponds to a radiometric value
175 | It is assumed the maximum radiometric value is 1e6
176 | """
177 | if img.shape[1] != self.shape[1] or img.shape[0] != self.shape[0]:
178 | print("Error: the size of the image doesn't match with the sensor ")
179 | return
180 | self.last_v = np.log(img + 1)
181 | self.cur_v = np.log(img + 1)
182 | self.tau_p = self.tau * 1e3 / (img + 1)
183 | self.time_px[:, :] = 0
184 | self.time = 0
185 |
186 | def check_noise(self, dt, img_l):
187 | """ Generate event packet of noise
188 | Check if the time at each pixel crossed a next noise event threshold during the update
189 | In this method, every pixel has the same noise rate.
190 | Args:
191 | dt: delay between to images (us)
192 | img_l: log value of the input image
193 | Returns:
194 | A packet of events of type EventBuffer
195 | """
196 | ind_pos_noise = np.where(self.time + dt > self.bgn_pos_next)
197 | ind_neg_noise = np.where(self.time + dt > self.bgn_neg_next)
198 | pk_noise = EventBuffer(len(ind_pos_noise[0]) + len(ind_neg_noise[0]))
199 | if len(ind_pos_noise[0]) > 0:
200 | pk_noise.add_array(self.bgn_pos_next[ind_pos_noise], ind_pos_noise[0], ind_pos_noise[1], 1)
201 | self.time_px[ind_pos_noise] = self.bgn_pos_next[ind_pos_noise]
202 | self.bgn_pos_next[ind_pos_noise] += self.m_bgn_pos_per
203 | self.cur_v[ind_pos_noise] = img_l[ind_pos_noise]
204 | self.last_v[ind_pos_noise] = img_l[ind_pos_noise]
205 | if len(ind_neg_noise[0]) > 0:
206 | pk_noise.add_array(self.bgn_neg_next[ind_neg_noise], ind_neg_noise[0], ind_neg_noise[1], 0)
207 | self.time_px[ind_neg_noise] = self.bgn_neg_next[ind_neg_noise]
208 | self.bgn_neg_next[ind_neg_noise] += self.m_bgn_neg_per
209 | self.cur_v[ind_neg_noise] = img_l[ind_neg_noise]
210 | self.last_v[ind_neg_noise] = img_l[ind_neg_noise]
211 | pk_noise.sort()
212 | return pk_noise
213 |
214 | def check_noise_hist(self, dt, img_l):
215 | """ Generate event packet of noise
216 | Check if the time at each pixel crossed a next noise event threshold during the update
217 | This method uses a measured noise distribution for each pixel
218 | Args:
219 | dt: delay between two updates (us)
220 | img_l: logarithmic value of the input image
221 | Returns:
222 | A packet of events of type EventBuffer
223 | """
224 | ind_pos_noise = np.where(self.time + dt > self.bgn_pos_next)
225 | ind_neg_noise = np.where(self.time + dt > self.bgn_neg_next)
226 | pk_noise = EventBuffer(len(ind_pos_noise[0]) + len(ind_neg_noise[0]))
227 | if len(ind_pos_noise[0]) > 0:
228 | pk_noise.add_array(self.bgn_pos_next[ind_pos_noise], ind_pos_noise[0], ind_pos_noise[1], 1)
229 | self.time_px[ind_pos_noise] = self.bgn_pos_next[ind_pos_noise]
230 | self.cur_v[ind_pos_noise] = img_l[ind_pos_noise]
231 | self.last_v[ind_pos_noise] = img_l[ind_pos_noise]
232 | for i in range(0, len(ind_pos_noise[0]), 1):
233 | self.bgn_pos_next[ind_pos_noise[0][i], ind_pos_noise[1][i]] += \
234 | self.get_next_noise(ind_pos_noise[1][i], ind_pos_noise[0][i], 1)
235 | if len(ind_neg_noise[0]) > 0:
236 | pk_noise.add_array(self.bgn_neg_next[ind_neg_noise], ind_neg_noise[0], ind_neg_noise[1], 0)
237 | self.time_px[ind_neg_noise] = self.bgn_neg_next[ind_neg_noise]
238 | self.cur_v[ind_neg_noise] = img_l[ind_neg_noise]
239 | self.last_v[ind_neg_noise] = img_l[ind_neg_noise]
240 | for i in range(0, len(ind_neg_noise[0]), 1):
241 | self.bgn_neg_next[ind_neg_noise[0][i], ind_neg_noise[1][i]] += \
242 | self.get_next_noise(ind_neg_noise[1][i], ind_neg_noise[0][i], 0)
243 | pk_noise.sort()
244 | return pk_noise
245 |
246 | def get_next_noise(self, x, y, pol):
247 | """ Updates the next noise event
248 | Take a value between 0 and 1 and find the delay of the next noise event
249 | Args:
250 | x, y: coordinate of the pixel
251 | pol: polarity of the noise
252 | Returns:
253 | the delay of the next noise event in us
254 | """
255 | val = np.random.uniform(0, 1)
256 | pos = y * self.shape[0] + x
257 | if pol == 1:
258 | ind = np.where(self.bgn_hist_pos[pos, :] >= val)
259 | next = FREQ[ind[0][0]]
260 | else:
261 | ind = np.where(self.bgn_hist_neg[pos, :] >= val)
262 | next = FREQ[ind[0][0]]
263 | return np.uint64(1e6 / next)
264 |
265 | def get_latency(self, time_end, last_v, cur_th, cur_v, img_l, time_px):
266 | """ Obtain the latency of the pixel
267 | Method: Linearly interpolates the time when it crosses the threshold
268 | and add the constant latency of the comparator stage.
269 | Args:
270 | time_end: time of the change (us)
271 | last_v: voltage at the last spike (np.array)
272 | cur_th: threshold (np.array)
273 | cur_v: voltage at time_px (np.array)
274 | last_v: voltage during the last spike (np.array)
275 | Returns:
276 | np.array of the latencies in us
277 | """
278 | return np.uint64((last_v + cur_th - cur_v) / (img_l - cur_v) * (time_end - time_px) + \
279 | np.random.normal(self.m_latency, self.m_jitter, last_v.shape[0]))
280 |
281 | def get_latency_tau(self, cur_th, cur_v, img_l, tau_p):
282 | """ Obtain the latency of the pixel
283 | Method: First order low pass filter interpolation of the time when
284 | it crosses the threshold and add the constant latency of the
285 | comparator stage
286 | Args:
287 | last_v: voltage at the last spike
288 | cur_th: threshold
289 | cur_v: voltage at time_px
290 | tau_p: time constants of the pixels
291 | Returns:
292 | np.array of the latencies in us
293 | """
294 | amp = np.divide(cur_th - cur_v, img_l - cur_v)
295 | jit = np.sqrt(self.m_jitter ** 2 + np.power(self.m_th_noise * tau_p / (img_l - cur_v), 2))
296 | t_ev = np.random.normal(self.m_latency - tau_p*np.log(1 - amp), jit)
297 | return np.uint64(np.clip(t_ev, 0, 10000))
298 |
299 | def update(self, img, dt):
300 | """ Update the sensor with a nef irradiance's frame
301 | Follow the ICNS model
302 | Args:
303 | img: radiometric value in the focal plane
304 | dt: delay between the frame and the last one (us)
305 | Returns:
306 | EventBuffer of the created events
307 | """
308 | if img.shape[1] != self.shape[1] or img.shape[0] != self.shape[0]:
309 | print("Error: the size of the image doesn't match with the sensor ")
310 | return
311 |
312 | # Convert in the log domain
313 | img_l = np.array(img, dtype=np.double)
314 | ind = np.where(img > 0)
315 | if len(ind[0]) == 0:
316 | print("ERROR: update: flux image with only zeros")
317 | return
318 | img_l[ind] = np.log(img[ind] + 1)
319 |
320 | # Update time constants - self.tau defined at 1 klux
321 | self.tau_p[ind] = self.tau * 1e3 / (img[ind] + 1)
322 |
323 | # Update refractory and reset pixels
324 | ind_ref = np.where(self.cur_ref < self.time + dt)
325 | px_delta_ref = np.array(self.cur_ref[ind_ref] - self.time, dtype=float)
326 | if len(ind_ref[0]) > 0:
327 | # Calculate voltage at the reset time (end of refractory period)
328 | self.last_v[ind_ref] = self.cur_v[ind_ref] + (img_l[ind_ref] - self.cur_v[ind_ref]) * \
329 | (1 - np.exp(-px_delta_ref / self.tau_p[ind_ref]))
330 | # End the refractory period
331 | self.time_px[ind_ref] = self.cur_ref[ind_ref]
332 | self.cur_ref[ind_ref] = np.iinfo(np.uint64).max
333 | # And update the reference voltage for these pixels
334 | self.cur_v[ind_ref] = self.last_v[ind_ref]
335 |
336 | # Get noise events and reset pixels
337 | if self.noise_model == NOISE_FREQ:
338 | pk_noise = self.check_noise(dt, img_l)
339 | else:
340 | pk_noise = self.check_noise_hist(dt, img_l)
341 |
342 | # Calculate voltage change at the end of the frame
343 | px_delta_t = np.array(self.time + dt - self.time_px[ind], dtype=float)
344 | target = np.zeros(img_l.shape)
345 | target[ind] = self.cur_v[ind] + (img_l[ind] - self.cur_v[ind]) * \
346 | (1 - np.exp(-px_delta_t / self.tau_p[ind]))
347 | dif = target - self.last_v
348 |
349 | # Check in which pixels the change is larger than the thresholds
350 | ind_pos = np.where((dif > self.cur_th_pos) & (self.cur_ref == np.iinfo(np.uint64).max))
351 | ind_neg = np.where((dif < self.cur_th_neg) & (self.cur_ref == np.iinfo(np.uint64).max))
352 |
353 | # Generate events for these pixels
354 | pk = EventBuffer(0)
355 | while len(ind_pos[0]) + len(ind_neg[0]) > 0:
356 | pk.increase(len(ind_pos[0]) + len(ind_neg[0]))
357 |
358 | # ON events
359 | if len(ind_pos[0]) > 0:
360 | # Get event times
361 | # Use this for first order interpolation
362 | t_event = self.get_latency_tau(
363 | self.last_v[ind_pos] + self.cur_th_pos[ind_pos],
364 | self.cur_v[ind_pos],
365 | img_l[ind_pos],
366 | self.tau_p[ind_pos]
367 | )
368 | # Or this for linear interpolation
369 | # t_event = self.get_latency(self.time + dt,
370 | # self.last_v[ind_pos],
371 | # self.cur_th_pos[ind_pos],
372 | # self.cur_v[ind_pos],
373 | # img_l[ind_pos],
374 | # self.time_px[ind_pos]
375 | # )
376 | # Add to the event buffer
377 | pk.add_array(self.time_px[ind_pos] + t_event, ind_pos[0], ind_pos[1], 1)
378 | # Update the threshold with noise
379 | self.cur_th_pos[ind_pos] = np.clip(
380 | np.random.normal(self.m_th_pos, self.m_th_noise, len(ind_pos[0])),
381 | 0,
382 | 1000
383 | )
384 | # Start the refractory period for those pixels that fired
385 | self.cur_ref[ind_pos] = self.time_px[ind_pos] + t_event + self.ref
386 |
387 | # OFF events
388 | if len(ind_neg[0]) > 0:
389 | # Get event times
390 | # Use this for first order interpolation
391 | t_event = self.get_latency_tau(
392 | self.last_v[ind_neg] + self.cur_th_neg[ind_neg],
393 | self.cur_v[ind_neg],
394 | img_l[ind_neg],
395 | self.tau_p[ind_neg]
396 | )
397 | # Or this for linear interpolation
398 | # t_event = self.get_latency(self.time + dt,
399 | # self.last_v[ind_neg],
400 | # self.cur_th_neg[ind_neg],
401 | # self.cur_v[ind_neg],
402 | # img_l[ind_neg],
403 | # self.time_px[ind_neg]
404 | # )
405 | # Add to the event buffer
406 | pk.add_array(self.time_px[ind_neg] + t_event, ind_neg[0], ind_neg[1], 0)
407 | # Update the threshold with noise
408 | self.cur_th_neg[ind_neg] = np.clip(
409 | np.random.normal(self.m_th_neg, self.m_th_noise, len(ind_neg[0])),
410 | -1000,
411 | 0
412 | )
413 | # Start the refractory period for those pixels that fired
414 | self.cur_ref[ind_neg] = self.time_px[ind_neg] + t_event + self.ref
415 |
416 | # Check if any of these refractory periods finish before the end of the frame
417 | ind_ref = np.where(self.cur_ref < self.time + dt)
418 | px_delta_ref = np.array(self.cur_ref[ind_ref]-self.time_px[ind_ref], dtype=float)
419 | if len(ind_ref[0]) > 0:
420 | # Calculate voltage at the reset time (end of refractory period)
421 | self.last_v[ind_ref] = self.cur_v[ind_ref] + (img_l[ind_ref] - self.cur_v[ind_ref]) * \
422 | (1 - np.exp(-px_delta_ref / self.tau_p[ind_ref]))
423 | # End the refractory period
424 | self.time_px[ind_ref] = self.cur_ref[ind_ref]
425 | self.cur_ref[ind_ref] = np.iinfo(np.uint64).max
426 | # And update the reference voltage for these pixels
427 | self.cur_v[ind_ref] = self.last_v[ind_ref]
428 |
429 | # Now check if there are any new threshold crossings since the previous event
430 | dif = np.zeros((self.shape[0], self.shape[1]))
431 | px_delta_ref = np.array(self.time + dt - self.time_px[ind_ref], dtype=float)
432 | target[ind_ref] = self.cur_v[ind_ref] + (img_l[ind_ref] - self.cur_v[ind_ref]) * \
433 | (1 - np.exp(-px_delta_ref / self.tau_p[ind_ref]))
434 | dif[ind_ref] = target[ind_ref] - self.last_v[ind_ref]
435 | ind_pos = np.where(dif > self.cur_th_pos)
436 | ind_neg = np.where(dif < self.cur_th_neg)
437 | # Repeat this loop until no more threshold crossings are found
438 |
439 | # Update pixel voltages at end of frame
440 | px_delta_t = np.array(self.time + dt - self.time_px[ind], dtype=float)
441 | self.cur_v[ind] = self.cur_v[ind] + (img_l[ind] - self.cur_v[ind]) * \
442 | (1 - np.exp(-px_delta_t / self.tau_p[ind]))
443 |
444 | # Update simulation time
445 | self.time += dt
446 | self.time_px[:] = self.time
447 |
448 | # Merge noise and signal events and sort by time
449 | pk_end = EventBuffer(0)
450 | pk_end.merge(pk, pk_noise)
451 | pk_end.sort()
452 |
453 | return pk_end
454 |
455 |
456 |
457 |
--------------------------------------------------------------------------------
/src/event_buffer.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | import numpy as np
3 | from dat_files import write_event_dat
4 |
5 |
6 | class EventBuffer():
7 | """ Structure to handle a buffer of dvs events """
8 | x = 0 # Array of x values
9 | y = 0 # Array of y values
10 | ts = 0 # Array of timestamps values (us)
11 | p = 0 # Array of polarity values (0 negative, 1 positive)
12 | i = 0 # Position of the next event
13 |
14 | def __init__(self, size):
15 | """ Resize the buffers
16 | Args:
17 | size: size of the new buffer, Minimum: 1
18 | """
19 | if size == 0:
20 | size = 1
21 | self.x = np.zeros(size, dtype=np.uint16)
22 | self.y = np.zeros(size, dtype=np.uint16)
23 | self.p = np.zeros(size, dtype=np.uint8)
24 | self.ts = np.zeros(size, dtype=np.uint64)
25 | self.i = 0
26 |
27 | def get_x(self):
28 | return self.x[:self.i]
29 |
30 | def get_y(self):
31 | return self.y[:self.i]
32 |
33 | def get_p(self):
34 | return self.p[:self.i]
35 |
36 | def get_ts(self):
37 | return self.ts[:self.i]
38 |
39 | def increase(self, nsize):
40 | """ Increase the size of a buffer to self.shape[0] size + nsize
41 | Args:
42 | nsize: number of free space elements to add
43 | """
44 | prev_shape = self.x.shape[0]
45 | x = np.zeros(prev_shape + nsize, dtype=np.uint16)
46 | y = np.zeros(prev_shape + nsize, dtype=np.uint16)
47 | p = np.zeros(prev_shape + nsize, dtype=np.uint8)
48 | ts = np.zeros(prev_shape + nsize, dtype=np.uint64)
49 | x[:prev_shape] = self.x
50 | y[:prev_shape] = self.y
51 | p[:prev_shape] = self.p
52 | ts[:prev_shape] = self.ts
53 | self.x = x
54 | self.y = y
55 | self.p = p
56 | self.ts = ts
57 |
58 | def remove_time(self, t_min, t_max):
59 | """
60 | Only keep events between t_min and t_max
61 | """
62 | ind = np.where((self.ts < t_min) | (self.ts > t_max))
63 | self.x = np.delete(self.x, ind)
64 | self.y = np.delete(self.y, ind)
65 | self.ts = np.delete(self.ts, ind)
66 | self.p = np.delete(self.p, ind)
67 | self.i = self.ts.shape[0]
68 |
69 | def remove_elt(self, nsize):
70 | """
71 | Remove the nsize first elements
72 | """
73 | if self.i - nsize < 0:
74 | nsize = self.i
75 | ind = np.arange(0, nsize, 1)
76 | self.x = np.delete(self.x, ind)
77 | self.y = np.delete(self.y, ind)
78 | self.ts = np.delete(self.ts, ind)
79 | self.p = np.delete(self.p, ind)
80 | self.i = self.i - nsize
81 |
82 | def remove_ev(self, p):
83 | """
84 | Remove the event at the position p
85 | """
86 | if self.i <= p:
87 | return
88 | self.x = np.delete(self.x, p)
89 | self.y = np.delete(self.y, p)
90 | self.ts = np.delete(self.ts, p)
91 | self.p = np.delete(self.p, p)
92 | self.i -= 1
93 |
94 | def remove_row(self, r, t):
95 | """
96 | Remove the event in row r at time t
97 | """
98 | if t == -1:
99 | ind = np.where((self.y == r) & (self.ts > 0))
100 | else:
101 | ind = np.where((self.y == r) & (self.ts < t) & (self.ts > 0))
102 | self.x = np.delete(self.x, ind)
103 | self.y = np.delete(self.y, ind)
104 | self.ts = np.delete(self.ts, ind)
105 | self.p = np.delete(self.p, ind)
106 | self.i -= ind[0].shape[0]
107 |
108 | def increase_ev(self, ev):
109 | """ Extend the event buffer with another event buffer
110 | If ev can be inserted into self, ev inserted, if not, increase the size of a buffer to original
111 | self.shape[0] + ev.shape[0]
112 | Args:
113 | ev: the EventBuffer added
114 | """
115 | if len(self.x) > 0 and not ev is None:
116 | if self.i + ev.x.shape[0] > self.x.shape[0] - 1:
117 | prev_shape = self.x.shape[0]
118 | x = np.zeros(prev_shape + ev.ts.shape[0], dtype=np.uint16)
119 | y = np.zeros(prev_shape + ev.ts.shape[0], dtype=np.uint16)
120 | p = np.zeros(prev_shape + ev.ts.shape[0], dtype=np.uint8)
121 | ts = np.zeros(prev_shape + ev.ts.shape[0], dtype=np.uint64)
122 | x[:self.i] = self.x[:self.i]
123 | y[:self.i] = self.y[:self.i]
124 | p[:self.i] = self.p[:self.i]
125 | ts[:self.i] = self.ts[:self.i]
126 | x[self.i:self.i + ev.x.shape[0]] = ev.x
127 | y[self.i:self.i + ev.x.shape[0]] = ev.y
128 | p[self.i:self.i + ev.x.shape[0]] = ev.p
129 | ts[self.i:self.i + ev.x.shape[0]] = ev.ts
130 | self.x = x
131 | self.y = y
132 | self.p = p
133 | self.ts = ts
134 | else:
135 | self.x[self.i:self.i + ev.i] = ev.x[:ev.i]
136 | self.y[self.i:self.i + ev.i] = ev.y[:ev.i]
137 | self.p[self.i:self.i + ev.i] = ev.p[:ev.i]
138 | self.ts[self.i:self.i + ev.i] = ev.ts[:ev.i]
139 | self.i += ev.i
140 |
141 | def copy(self, i1, ep, i2):
142 | """ Copy the i2 th event of the EventBuffer ep in to the i1 th position
143 | Args:
144 | i1: self will have a new event in i1
145 | ep: EventBuffer where the event comes from
146 | i2: i2th event from ep is takem
147 | """
148 | if i1 < len(self.x):
149 | self.x[i1] = ep.x[i2]
150 | self.y[i1] = ep.y[i2]
151 | self.ts[i1] = ep.ts[i2]
152 | self.p[i1] = ep.p[i2]
153 | self.i = i1 + 1
154 |
155 | def merge(self, ep1, ep2):
156 | """ Resize the EventBuffer and merge into the two EventBuffers ep1 nd ep2, sorted by their timestamps
157 | Args:
158 | ep1, ep2: eventBuffer
159 | """
160 | self.__init__(len(ep1.x) + len(ep2.x))
161 | i1 = 0
162 | i2 = 0
163 | for j in range(0, ep1.i + ep2.i, 1):
164 | if i1 == ep1.i:
165 | self.copy(j, ep2, i2)
166 | i2 += 1
167 | elif i2 == ep2.i:
168 | self.copy(j, ep1, i1)
169 | i1 += 1
170 | else:
171 | if ep1.ts[i1] < ep2.ts[i2]:
172 | self.copy(j, ep1, i1)
173 | i1 += 1
174 | else:
175 | self.copy(j, ep2, i2)
176 | i2 += 1
177 | self.i = ep1.i + ep2.i
178 |
179 | def sort(self):
180 | """ Sort the EventBuffer according to its timestamp """
181 | ind = np.argsort(self.ts[:self.i])
182 | self.ts[:self.i] = self.ts[:self.i][ind]
183 | self.x[:self.i] = self.x[:self.i][ind]
184 | self.y[:self.i] = self.y[:self.i][ind]
185 | self.p[:self.i] = self.p[:self.i][ind]
186 |
187 | def add(self, ts, y, x, p):
188 | """
189 | Add an event (ts, x, y, p) to the EventBuffer (push strategy)
190 | If y == -1, if means that x[0] contains the x position and x[1] the y position.
191 | Args:
192 | ts, y, x, p: new event array
193 | """
194 | if self.x.shape[0] == self.i:
195 | self.increase(1000)
196 | self.add(ts, y, x, p)
197 | else:
198 | self.ts[self.i] = ts
199 | self.x[self.i] = x
200 | self.y[self.i] = y
201 | self.p[self.i] = p
202 | self.i += 1
203 |
204 | def add_array(self, ts, y, x, p, inc=1000):
205 | """
206 | Add n events (ts, x, y, p) to the EventBuffer (push strategy)
207 | Args:
208 | ts, y, x, p: new event array
209 | inc: increment size
210 | """
211 | s = len(ts)
212 | if s > len(self.ts) - self.i:
213 | self.increase(inc)
214 | self.add_array(ts, y, x, p)
215 | else:
216 | self.ts[self.i:self.i + s] = ts
217 | self.x[self.i:self.i + s] = x
218 | self.y[self.i:self.i + s] = y
219 | self.p[self.i:self.i + s] = p
220 | self.i += s
221 |
222 | def write(self, filename, width=None, height=None):
223 | """ Write the events into a .dat file
224 | Args:
225 | filename: path of the file
226 | """
227 | # sort events to have a monotonically timestamps
228 | self.sort()
229 | write_event_dat(filename, self.ts[:self.i], self.x[:self.i], self.y[:self.i], self.p[:self.i],
230 | event_type='dvs', width=width, height=height)
231 |
--------------------------------------------------------------------------------
/src/event_display.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import cv2
3 |
4 |
5 | class EventDisplay():
6 | """ Structure to handle the thread created by OpenCV to render an image """
7 | name = "test" # Name of the window
8 | time = 0 # Internal counter of the display (us)
9 | last_frame = 0 # Time of the last frame
10 | frametime = 100000 # Time to refresh the display (us)
11 | time_surface = np.zeros((10, 10), dtype=np.uint64) # Timestamp of the last event in the focal plane
12 | pol_surface = np.zeros((10, 10), dtype=np.uint8) # Polarity of the last event in the focal plane
13 | im = np.zeros((10, 10, 3), dtype=np.uint8) # Image to render
14 | render = 0 # 0: binary image, 1: ts
15 | render_tau = 40000 # tau decay of the time surface (us)
16 | display_time = True
17 |
18 | def __init__(self, name, dx, dy, frametime, render=0):
19 | """ Initialize the Display by reseting the internal timer of the structure and providing the right size of
20 | buffers
21 | Args:
22 | name: name of the windows
23 | dy dx: size of the data
24 | frametime: delay between two frames (us)
25 | render: rendering method: 0 = binary, 1 = timesurface
26 | """
27 | self.name = name
28 | self.time = 0
29 | self.last_frame = 0
30 | self.frametime = frametime
31 | self.time_surface = np.zeros((int(dy), int(dx)), dtype=np.uint64)
32 | self.pol_surface = np.zeros((int(dy), int(dx)), dtype=np.uint8)
33 | self.im = np.zeros((int(dy), int(dx), 3), dtype=np.uint8)
34 | self.render = 0
35 | self.render_tau = 3 * frametime
36 |
37 | def reset(self):
38 | """ Reset timers and buffers to 0 """
39 | self.time = 0
40 | self.last_frame = 0
41 | self.time_surface[:] = 0
42 | self.pol_surface[:] = 0
43 |
44 | def update(self, pk, dt):
45 | """ During the time dt, the EventBuffer was created. This function adds these events to the structure and
46 | triggers a display if needed
47 | Args:
48 | pk: EventBuffer
49 | dt: delay since the last update
50 | """
51 | self.time_surface[pk.y[:pk.i], pk.x[:pk.i]] = pk.ts[:pk.i]
52 | self.pol_surface[pk.y[:pk.i], pk.x[:pk.i]] = pk.p[:pk.i]
53 | self.time += dt
54 | self.last_frame += dt
55 | if self.last_frame > self.frametime:
56 | self.last_frame = 0
57 | self.im[:] = 125
58 | if self.render == 0:
59 | ind = np.where((self.time_surface > self.time - self.frametime) & (self.time_surface <= self.time))
60 | self.im[:, :, 0][ind] = self.pol_surface[ind]*255
61 | self.im[:, :, 1][ind] = self.pol_surface[ind]*255
62 | self.im[:, :, 2][ind] = self.pol_surface[ind]*255
63 | if self.render == 1:
64 | self.im[:, :, 0] = (self.pol_surface * 2 - 1) * 125 * np.exp(-(self.time - self.time_surface.astype(np.double)) / self.render_tau)
65 | if self.display_time: self.im = cv2.putText(self.im, '{} s'.format(self.time / 1e6), (0, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 255))
66 | cv2.imshow(self.name, self.im)
67 | cv2.waitKey(10)
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------