[
  {
    "path": ".gitignore",
    "content": "build/\n*.pyc\n*.mat\n*~\n*.m\n*.c\n*.so\n*.hdf\n*.ipynb\n.eggs/\n.idea/\n.ipynb_checkpoints/\ncrisp.egg-info/\ndist/\ncrisp/fastintegrate/fastint.c\n"
  },
  {
    "path": "CITATION",
    "content": "To cite this software please use the following BibTex information\n\n@inproceedings{Ovren2015,\ntitle = {{Gyroscope-based video stabilisation with auto-calibration}},\nauthor = {Ovrén, Hannes and Forssén, Per-Erik},\nbooktitle = {2015 IEEE International Conference on Robotics and Automation (ICRA)},\nyear = {2015},\nmonth = may,\naddress = {Seattle, WA},\npages = {2090--2097},\ndoi = {10.1109/ICRA.2015.7139474},\n}\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>."
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.md\nrecursive-include crisp/fastintegrate *\n"
  },
  {
    "path": "README.md",
    "content": "# Camera-to-IMU calibration toolbox\nThis toolbox provides a python library to perform joint calibration of a rolling shutter camera-gyroscope system.\n\nGiven gyroscope and video data, this library can find the following parameters\n\n* True gyroscope rate\n* Time offset\n* Rotation between camera and gyroscope coordinate frames\n* Gyroscope measurement bias\n\nIf you use the package for your work, please cite the following paper\n\n> Ovrén, H and Forssén, P.-E. \"Gyroscope-based video stabilisation with auto-calibration.\" In 2015 IEEE International Conference on Robotics and Automation (ICRA) (pp. 2090–2097). Seattle, WA\n\n## Can I use these methods for my application?\nThe calibration methods in this package assumes the following\n\n- Your camera is calibrated, including known readout time\n- The camera frame rate is constant, and known\n- The gyroscope frame rate is constant, and approximately known (within a few Hz, or percent)\n\nIf the video and gyroscope data are *not uniformly sampled*, but you have access\nto somewhat reliable timestamps, then you can still use the method\nif you resample the data to be uniform.\nBy \"reliable\" we mean timestamps without drift, and no (or negligble) jitter.\n\n## Changes from 1.0\nThe 2.0 version of crisp features a new fully automatic calibrator.\nThis means that there is no compelling reason to use the semi-manual methods in the previous version of crisp.\nTherefore the old example scripts have been removed, and the old functions are not imported into the module namespace.\nNo old functions have been removed, so if you want to use them they are still available in submodules.\n\n## Installation\nTo use the package you need the following Python packages:\n\n* NumPy\n* SciPy\n* OpenCV\n* matplotlib\n\nThe easiest way is to install from PyPI:\n\n    $ pip install crisp\n\nIf you want to build the package from source, you also need the *Cython* package.\nTo build and install the `crisp` module just run the following commands:\n\n    $ python setup.py build\n    $ python setup.py install\n    \nFor a user-only installation add `--user` to the install command.\n\n## Usage\nThe gyroscope and video data are first loaded into a stream object (`GyroStream`, and a subclass of `VideoStream` respectively).\nTo be able to understand how points are mapped from the real world to the image, the video stream also need a `CameraModel` (-subclass) instance.\n\n    import crisp\n    \n    gyro = crisp.GyroStream.from_data(some_data_array)\n    camera_model = crisp.AtanCameraModel(...) # One specific choice of camera model\n    video = crisp.VideoStream.from_file(camera_model, video_file_path)\n\n\nWe then tie the streams together using a `AutoCalibrator` instance.\nSince the calibration proces need to have estimates of the time offset and relative rotation,\nthese are first estimated using the `initialize()` member. This initialization only requires that\nyou give an approximate gyroscope sample rate (in Hz).\n\n    calibrator = crisp.AutoCalibrator(video, gyro)\n    calibrator.initialize(guessed_gyro_rate)\n    result = calibrator.calibrate() # Dict of calibrated parameters\n\nInitialization and calibration errors can be caught by handling `InitializationError` and `CalibrationError`.\n\n### Example scripts\nWe bundle one example script `gopro_dataset_example.py` which shows how to use the \nlibrary with the data in our dataset (http://www.cvl.isy.liu.se/research/datasets/gopro-gyro-dataset/).\nThis is the same dataset that was used to produce the above mentioned ICRA 2015 paper.\n\n## Feedback\n* For any questions regarding the method and paper, please send an e-mail to hannes.ovren@liu.se.\n* For issues about the code, you are welcome to either use the tools (issue reporting, etc.) provided by GitHub, or send an e-mail.\n\n## License\nAll code in this repository is licensed under the GPL version 3.\n"
  },
  {
    "path": "conda.recipe/bld.bat",
    "content": "\"%PYTHON%\" setup.py install\nif errorlevel 1 exit 1\n\n:: Add more build steps here, if they are necessary.\n\n:: See\n:: http://docs.continuum.io/conda/build.html\n:: for a list of environment variables that are set during the build process.\n"
  },
  {
    "path": "conda.recipe/build.sh",
    "content": "#!/bin/bash\n\n$PYTHON setup.py install\n\n# Add more build steps here, if they are necessary.\n\n# See\n# http://docs.continuum.io/conda/build.html\n# for a list of environment variables that are set during the build process.\n"
  },
  {
    "path": "conda.recipe/meta.yaml",
    "content": "package:\n  name: crisp\n  version: \"2.2.1\"\n\nsource:\n    git_url: https://github.com/hovren/crisp.git\n    git_rev: v2.2.1\n    \n# build:\n  # noarch_python: True\n  # preserve_egg_dir: True\n  # entry_points:\n    # Put any entry points (scripts to be generated automatically) here. The\n    # syntax is module:function.  For example\n    #\n    # - crisp = crisp:main\n    #\n    # Would create an entry point called crisp that calls crisp.main()\n\n\n  # If this is a new build for the same version, increment the build\n  # number. If you do not include this key, it defaults to 0.\n  # number: 1\n\nrequirements:\n  build:\n    - python\n    - setuptools\n    - numpy\n    - mock\n    - nose\n    - scipy\n    - matplotlib\n\n  run:\n    - python\n    - numpy\n    - scipy\n    - opencv\n    - matplotlib\n\ntest:\n  # Python imports\n  imports:\n    - crisp\n\n  # commands:\n    # You can put test commands to be run here.  Use this to test that the\n    # entry points work.\n\n\n  # You can also put a file called run_test.py in the recipe that will be run\n  # at test time.\n\n  # requires:\n    # Put any additional test requirements here.  For example\n    # - nose\n\nabout:\n  home: https://github.com/hovren/crisp\n  license: GNU General Public License (GPL)\n  summary: 'Camera-to-IMU calibration and synchronization toolkit'\n\n# See\n# http://docs.continuum.io/conda/build.html for\n# more information about meta.yaml\n"
  },
  {
    "path": "crisp/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\n========================================\nCamera-to-IMU calibration toolbox\n========================================\nThis package solves the task of finding the parameters\nthat relate gyroscope data with video data.\n\nTo run, please see the README or the class AutoCalibrator.\n\"\"\"\nfrom __future__ import absolute_import\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2015, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nfrom .camera import CameraModel, AtanCameraModel, OpenCVCameraModel\nfrom .stream import GyroStream, VideoStream, OpenCvVideoStream\nfrom .calibration import AutoCalibrator, CalibrationError, InitializationError"
  },
  {
    "path": "crisp/calibration.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nCamera-gyro calibration module\n\"\"\"\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2015, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport time\nimport warnings\nimport logging\nlogger = logging.getLogger('crisp')\n\nimport numpy as np\nimport scipy.optimize\n\nfrom . import videoslice, rotations, ransac, timesync, fastintegrate\n\nPARAM_SOURCE_ORDER = ('user', 'initialized', 'calibrated') # Increasing order of importance\nPARAM_ORDER = ('gyro_rate', 'time_offset', 'gbias_x', 'gbias_y', 'gbias_z', 'rot_x', 'rot_y', 'rot_z')\n\nMAX_OPTIMIZATION_TRACKS = 1500\nMAX_OPTIMIZATION_FEV = 800\nDEFAULT_NORM_C = 3.0\n\nclass CalibrationError(Exception):\n    pass\n\nclass InitializationError(Exception):\n    pass\n\nclass AutoCalibrator(object):\n    \"\"\"Class that handles auto calibration of a camera-gyroscope system.\n\n    This calibrator uses the method described in [1]_.\n\n    The parameters which are calibrated for are\n\n        * Gyroscope sample rate\n        * Time offset\n        * Gyroscope bias\n        * Rotation between camera and gyroscope\n\n    Notes\n    ---------------------\n    Given time offset d, and gyro rate F, the time relation is such that we\n    calculate the corresponding gyroscope sample n from video time t as\n\n        n = F ( t + d )\n\n    The rotation between camera and gyroscope, R, is expressed such that it transfers points from the gyroscope\n    coordinate frame to the camera coordinate frame as\n\n        p_camera = R * p_gyro\n\n    The bias is applied to the gyroscope measurements, w, before integration\n\n        w_adjusted = w - bias\n\n    References\n    ----------------------\n    ..  [1] Ovrén, H and Forssén, P.-E. \"Gyroscope-based video stabilisation with auto-calibration.\"\n        In 2015 IEEE International Conference on Robotics and Automation (ICRA) (pp. 2090–2097). Seattle, WA\n    \"\"\"\n    def __init__(self, video, gyro):\n        \"\"\"Create calibrator\n\n        Parameters\n        ---------------\n        video : VideoStream\n            A video stream object that provides frames and camera information\n        gyro : GyroStream\n            A gyroscope stream that provides angular velocity measurements\n        \"\"\"\n        self.video = video\n        self.gyro = gyro\n        \n        self.slices = None\n\n        # Parameters can be supplied from different sources, and it can be useful to track that\n        self.params = {\n            'user' : {}, # Supplied by the user\n            'initialized' : {}, # Estimated automatically by running initialize()\n            'calibrated' : {} # Final calibrated values\n        }\n    \n    def initialize(self, gyro_rate, slices=None, skip_estimation=False):\n        \"\"\"Prepare calibrator for calibration\n\n        This method does three things:\n        1. Create slices from the video stream, if not already provided\n        2. Estimate time offset\n        3. Estimate rotation between camera and gyroscope\n\n        Parameters\n        ------------------\n        gyro_rate : float\n            Estimated gyroscope sample rate\n        slices : list of Slice, optional\n            Slices to use for optimization\n        skip_estimation : bool\n            Do not estimate initial time offset and rotation.\n\n        Raises\n        --------------------\n        InitializationError\n            If the initialization fails\n        \"\"\"\n        self.params['user']['gyro_rate'] = gyro_rate\n\n        for p in ('gbias_x', 'gbias_y', 'gbias_z'):\n            self.params['initialized'][p] = 0.0\n\n        if slices is not None:\n            self.slices = slices\n\n        if self.slices is None:\n            self.slices = videoslice.Slice.from_stream_randomly(self.video)\n            logger.debug(\"Number of slices: {:d}\".format(len(self.slices)))\n\n        if len(self.slices) < 2:\n            logger.error(\"Calibration requires at least 2 video slices to proceed, got %d\", len(self.slices))\n            raise InitializationError(\"Calibration requires at least 2 video slices to proceed, got {:d}\".format(len(self.slices)))\n\n        if not skip_estimation:\n            time_offset = self.find_initial_offset()\n            # TODO: Detect when time offset initialization fails, and raise InitializationError\n\n            R = self.find_initial_rotation()\n            if R is None:\n                raise InitializationError(\"Failed to calculate initial rotation\")\n\n        \n    def video_time_to_gyro_sample(self, t):\n        \"\"\"Convert video time to gyroscope sample index and interpolation factor\n\n        Parameters\n        -------------------\n        t : float\n            Video timestamp\n\n        Returns\n        --------------------\n        n : int\n            Sample index that precedes t\n        tau : float\n            Interpolation factor [0.0-1.0]. If tau=0, then t falls on exactly n. If tau=1 then t falls exactly on n+1\n        \"\"\"\n        f_g = self.parameter['gyro_rate']\n        d_c = self.parameter['time_offset']\n        n = f_g * (t + d_c)\n        n0 = int(np.floor(n))\n        tau = n - n0\n        return n0, tau\n    \n    @property\n    def parameter(self):\n        \"\"\"Return the current best value of a parameter\"\"\"\n        D = {}\n        for source in PARAM_SOURCE_ORDER:\n            D.update(self.params[source])\n        return D              \n        \n    def calibrate(self, max_tracks=MAX_OPTIMIZATION_TRACKS, max_eval=MAX_OPTIMIZATION_FEV, norm_c=DEFAULT_NORM_C):\n        \"\"\"Perform calibration\n\n        Parameters\n        ----------------------\n        max_eval : int\n            Maximum number of function evaluations\n\n        Returns\n        ---------------------\n        dict\n            Optimization result\n\n        Raises\n        -----------------------\n        CalibrationError\n            If calibration fails\n        \"\"\"\n        x0 = np.array([self.parameter[param] for param in PARAM_ORDER])\n        available_tracks = np.sum([len(s.inliers) for s in self.slices])\n        if available_tracks < max_tracks:\n            warnings.warn(\"Could not use the requested {} tracks, since only {} were available in the slice data.\".format(max_tracks, available_tracks))\n            max_tracks = available_tracks\n\n        # Get subset of available tracks such that all slices are still used\n        slice_sample_idxs = videoslice.fill_sampling(self.slices, max_tracks)\n\n        func_args = (self.slices, slice_sample_idxs, self.video.camera_model, self.gyro, norm_c)\n        self.slice_sample_idxs = slice_sample_idxs\n        logger.debug(\"Starting optimization on {:d} slices and {:d} tracks\".format(len(self.slices), max_tracks))\n        start_time = time.time()\n        # TODO: Check what values of ftol and xtol are required for good results. The current setting is probably pessimistic.\n        leastsq_result = scipy.optimize.leastsq(optimization_func, x0, args=func_args, full_output=True, ftol=1e-10, xtol=1e-10, maxfev=max_eval)\n        elapsed = time.time() - start_time\n        x, covx, infodict, mesg, ier = leastsq_result\n        self.__debug_leastsq = leastsq_result\n        logger.debug(\"Optimization completed in {:.1f} seconds and {:d} function evaluations. ier={}, mesg='{}'\".format(elapsed, infodict['nfev'], ier, mesg))\n        if ier in (1,2,3,4):\n            for pname, val in zip(PARAM_ORDER, x):\n                self.params['calibrated'][pname] = val\n            return self.parameter\n        else:\n            raise CalibrationError(mesg)\n\n    def find_initial_offset(self, pyramids=6):\n        \"\"\"Estimate time offset\n        \n        This sets and returns the initial time offset estimation.\n        \n        Parameters\n        ---------------\n        pyramids : int\n            Number of pyramids to use for ZNCC calculations.\n            If initial estimation of time offset fails, try lowering this value.\n\n        Returns\n        ---------------\n        float\n            Estimated time offset\n        \"\"\"\n        flow = self.video.flow\n        gyro_rate = self.parameter['gyro_rate']\n        frame_times = np.arange(len(flow)) / self.video.frame_rate\n        gyro_times = np.arange(self.gyro.num_samples) / gyro_rate\n        time_offset = timesync.sync_camera_gyro(flow, frame_times, self.gyro.data.T, gyro_times, levels=pyramids)\n        \n        logger.debug(\"Initial time offset: {:.4f}\".format(time_offset))\n        self.params['initialized']['time_offset'] = time_offset\n        \n        return time_offset\n\n    def find_initial_rotation(self):\n        \"\"\"Estimate rotation between camera and gyroscope\n        \n        This sets and returns the initial rotation estimate.\n        Note that the initial time offset must have been estimated before calling this function!\n\n\n        Returns\n        --------------------\n        (3,3) ndarray\n            Estimated rotation between camera and gyroscope\n        \"\"\"\n        if 'time_offset' not in self.parameter:\n            raise InitializationError(\"Can not estimate rotation without an estimate of time offset. Please estimate the offset and try again.\")\n            \n        dt = float(1.0 / self.parameter['gyro_rate']) # Must be python float for fastintegrate\n        q = self.gyro.integrate(dt)\n        \n        video_axes = []\n        gyro_axes = []\n        \n        for _slice in self.slices:\n            # Estimate rotation here\n            _slice.estimate_rotation(self.video.camera_model, ransac_threshold=7.0) # sets .axis and .angle memebers\n            if _slice.axis is None:\n                continue\n            assert _slice.angle > 0\n            \n            t1 = _slice.start / self.video.frame_rate\n            n1, _ = self.video_time_to_gyro_sample(t1)\n            t2 = _slice.end / self.video.frame_rate\n            n2, _ = self.video_time_to_gyro_sample(t2)\n            \n            try:\n                qx = q[n1]\n                qy = q[n2]\n            except IndexError:\n                continue # No gyro data -> nothing to do with this slice\n                \n            Rx = rotations.quat_to_rotation_matrix(qx)\n            Ry = rotations.quat_to_rotation_matrix(qy)\n            R = np.dot(Rx.T, Ry)\n            v, theta = rotations.rotation_matrix_to_axis_angle(R)\n            if theta < 0:\n                v = -v\n                \n            gyro_axes.append(v)\n            video_axes.append(_slice.axis)\n            \n        if len(gyro_axes) < 2:\n            logger.warning(\"Rotation estimation requires at least 2 rotation axes, got {}\".format(len(gyro_axes)))\n            return None\n\n        logger.debug(\"Using {:d} slices (from initial {:d} for rotation estimation\".format(len(gyro_axes), len(self.slices)))\n\n        model_func = lambda data: rotations.procrustes(data[:3], data[3:6], remove_mean=False)[0]\n        \n        def eval_func(model, data):\n            X = data[:3].reshape(3,-1)\n            Y = data[3:6].reshape(3,-1)\n            R = model\n            Xhat = np.dot(R, Y)\n            \n            costheta = np.sum(Xhat*X, axis=0)\n            theta = np.arccos(costheta)\n            \n            return theta\n       \n        inlier_selection_prob = 0.99999\n        model_points = 2 # Set to 3 to use non-minimal case\n        inlier_ratio = 0.5\n        threshold = np.deg2rad(10.0)\n        ransac_iterations = int(np.log(1 - inlier_selection_prob) / np.log(1-inlier_ratio**model_points))\n        data = np.vstack((np.array(video_axes).T, np.array(gyro_axes).T))    \n        assert data.shape == (6, len(gyro_axes))\n        \n        R, ransac_conseus_idx = ransac.RANSAC(model_func, eval_func, data,\n                                              model_points, ransac_iterations,\n                                              threshold, recalculate=True)\n\n        n, theta = rotations.rotation_matrix_to_axis_angle(R)\n        logger.debug(\"Found rotation: n={} theta={};  r={}\".format(n, theta, n*theta))\n        logger.debug(R)\n        rx, ry, rz = theta * n\n        self.params['initialized']['rot_x'] = rx\n        self.params['initialized']['rot_y'] = ry\n        self.params['initialized']['rot_z'] = rz\n\n        return R\n\n    def print_params(self):\n        \"\"\"Print the current best set of parameters\"\"\"\n        print(\"Parameters\")\n        print(\"--------------------\")\n        for param in PARAM_ORDER:\n            print('  {:>11s} = {}'.format(param, self.parameter[param]))\n\ndef sample_at_time(t, rate):\n    s = t * rate - 0.5 # Shift half sample due to rectangular integration\n    n = int(np.floor(s))\n    tau = s - n\n    return n, tau\n\ndef robust_norm(r, c):\n    return r / (1 + (np.abs(r)/c))\n\n\ndef optimization_func(x, slices, slice_sample_idxs, camera, gyro, norm_c):\n    # Unpack parameters and convert representations\n    Fg, offset, gbias_x, gbias_y, gbias_z, rot_x, rot_y, rot_z, = x\n\n    gyro_bias = np.array([gbias_x, gbias_y, gbias_z])\n\n    # Construct coordinate frame rotation matrix\n    v = np.array([rot_x, rot_y, rot_z])\n    theta = np.linalg.norm(v)\n    v /= theta\n    R_g2c = rotations.axis_angle_to_rotation_matrix(v, theta)\n\n    Tg = float(1. / Fg) # Must be python float for fastintegrate to work\n    row_delta = camera.readout / camera.rows\n\n    errors = [] # Residual vector\n\n    # Margin of integration is amount of gyro samples per frame\n    integration_margin = int(np.ceil(Fg * camera.readout))\n\n    for _slice, sample_idxs in zip(slices, slice_sample_idxs):\n        if len(sample_idxs) < 1:\n            continue\n\n        t_start = _slice.start / camera.frame_rate + offset\n        t_end = _slice.end / camera.frame_rate + offset\n        slice_start, _ = sample_at_time(t_start, Fg)\n        slice_end, _ = sample_at_time(t_end, Fg)\n        slice_end += 1 # sample_at_time() gives first sample\n\n        # Gyro samples to integrate within\n        integration_start = slice_start\n        integration_end = slice_end + integration_margin\n\n        # Handle out of bounds cases by padding left and right using \n        # first and last gyroscope sample respectively\n        if integration_start < 0 or integration_end >= gyro.num_samples:\n            num_local_samples = integration_end - integration_start + 1\n            gyro_part = np.empty((num_local_samples, 3))\n\n            if integration_start < 0:\n                # Pad left\n                part_start = -integration_start\n                data_start = 0\n                gyro_part[:part_start] = gyro.data[0]\n            else:\n                part_start = 0\n                data_start = integration_start\n            \n            if integration_end >= gyro.num_samples:\n                # Pad right\n                rpad_len = integration_end - gyro.num_samples + 1\n                if rpad_len < num_local_samples:\n                    gyro_part[-rpad_len:] = gyro.data[-1]\n                else: # integration range outside data\n                    gyro_part[:] = gyro.data[-1]\n                part_end = -rpad_len # Not inclusive\n                data_end = gyro.num_samples\n            else:\n                part_end = num_local_samples\n                data_end = integration_end + 1\n            \n            try:\n                gyro_part[part_start:part_end] = gyro.data[data_start:data_end]\n            except ValueError:\n                pass # Completely out of bounds. This is OK.\n                \n        else: # No pad required (default case)\n            gyro_part = gyro.data[integration_start:integration_end+1]\n        \n    # TODO: Decide what to do if integration_end - integration_start < 1. This \n            \n        gyro_part_corrected = gyro_part + gyro_bias\n        q = fastintegrate.integrate_gyro_quaternion_uniform(gyro_part_corrected, Tg)\n\n        for track in _slice.points[sample_idxs]:\n            x = track[0] # Points in first frame\n            y = track[-1] # Points in last frame\n\n            # Get row time\n            tx = t_start + x[1] * row_delta\n            ty = t_end + y[1] * row_delta\n\n            # Sample index and interpolation value for point correspondences\n            nx, taux = sample_at_time(tx, Fg)\n            ny, tauy = sample_at_time(ty, Fg)\n\n            # Interpolate rotation using SLERP\n            a = nx - integration_start\n            b = ny - integration_start\n            qx = rotations.slerp(q[a], q[a+1], taux)\n            qy = rotations.slerp(q[b], q[b+1], tauy)\n\n            Rx = rotations.quat_to_rotation_matrix(qx)\n            Ry = rotations.quat_to_rotation_matrix(qy)\n            R1 = np.dot(Rx.T, Ry) # Note: Transpose order is \"wrong\", but this is because definition of Rx\n\n            R = R_g2c.dot(R1).dot(R_g2c.T)\n\n            Y = camera.unproject(y)\n            Xhat = np.dot(R, Y)\n            xhat = camera.project(Xhat)\n\n            err = x - xhat.flatten()\n            errors.extend(err.flatten())\n\n            # Symmetric errors, so let's do this again\n            R1 = np.dot(Ry.T, Rx) # Note: Transpose order is \"wrong\", but this is because definition of Rx\n            R = R_g2c.dot(R1).dot(R_g2c.T)\n\n            X = camera.unproject(x)\n            Yhat = np.dot(R, X)\n            yhat = camera.project(Yhat)\n\n            err = y - yhat.flatten()\n            errors.extend(err.flatten())\n\n    if not errors:\n        raise ValueError(\"No residuals!\")\n\n    # Apply robust norm\n    robust_errors = robust_norm(np.array(errors), norm_c)\n\n    return robust_errors\n"
  },
  {
    "path": "crisp/camera.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nCamera module\n\"\"\"\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport os\nimport glob\nimport logging\nlogger = logging.getLogger()\n\nimport numpy as np\nimport cv2\nimport scipy.interpolate\n\nfrom . import remove_slp\n\nclass CameraModel(object):\n    \"\"\"Class that describes a camera model\n\n    This encapsulates knowledge of a specific camera,\n    i.e. its parameters and how the image is formed.\n\n    Note that all cameras are assumed to be rolling shutter cameras.\n    \"\"\"\n    def __init__(self, image_size, frame_rate, readout):\n        \"\"\"Create camera model\n\n        Parameters\n        -----------------\n        image_size : tuple (rows, columns)\n            The size of the image in pixels\n        frame_rate : float\n            The frame rate of the camera\n        readout : float\n            Rolling shutter readout time. Set to 0 for global shutter cameras.\n        \"\"\"\n        self.image_size = image_size\n        self.frame_rate = frame_rate\n        self.readout = readout\n\n    @property\n    def rows(self):\n        return self.image_size[1]\n\n    @property\n    def columns(self):\n        return self.image_size[0]\n\n    def project(self, points):\n        \"\"\"Project 3D points to image coordinates.\n\n        This projects 3D points expressed in the camera coordinate system to image points.\n\n        Parameters\n        --------------------\n        points : (3, N) ndarray\n            3D points\n\n        Returns\n        --------------------\n        image_points : (2, N) ndarray\n            The world points projected to the image plane\n        \"\"\"\n        raise NotImplementedError(\"Class {} does not implement project()\".format(self.__class__.__name__))\n\n    def unproject(self, image_points):\n        \"\"\"Find (up to scale) 3D coordinate of an image point\n\n        This is the inverse of the `project` function.\n        The resulting 3D points are only valid up to an unknown scale.\n\n        Parameters\n        ----------------------\n        image_points : (2, N) ndarray\n            Image points\n\n        Returns\n        ----------------------\n        points : (3, N) ndarray\n            3D coordinates (valid up to scale)\n        \"\"\"\n        raise NotImplementedError(\"Class {} does not implement unproject()\".format(self.__class__.__name__))\n\nclass AtanCameraModel(CameraModel):\n    \"\"\"atan camera model\n\n    This implements the camera model of Devernay and Faugeras ([1]_) using the simplified form in [2]_.\n\n    References\n    -----------------------\n    ..  [1] F. Devernay and O. Faugeras, “Straight lines have to be straight: Au- tomatic calibration and removal of\n        distortion from scenes of structured environments,” Machine Vision and Applications, vol. 13, 2001.\n\n    ..  [2] Johan Hedborg and Björn Johansson. \"Real time camera ego-motion compensation and lens undistortion on GPU.\"\n        Technical report, Linköping University, Department of Electrical Engineering, Sweden, 2007\n    \"\"\"\n    def __init__(self, image_size, frame_rate, readout, camera_matrix, dist_center, dist_param):\n        \"\"\"Create model\n\n        Parameters\n        ------------------------\n        image_size : tuple (rows, columns)\n            The size of the image in pixels\n        frame_rate : float\n            The frame rate of the camera\n        readout : float\n            Rolling shutter readout time. Set to 0 for global shutter cameras.\n        camera_matrix : (3, 3) ndarray\n            The internal camera calibration matrix\n        dist_center : (2, ) ndarray\n            Distortion center in pixels\n        dist_param : float\n            Distortion parameter\n        \"\"\"\n        super(AtanCameraModel, self).__init__(image_size, frame_rate, readout)\n        self.camera_matrix = camera_matrix\n        self.inv_camera_matrix = np.linalg.inv(self.camera_matrix)\n        self.wc = dist_center\n        self.lgamma = dist_param\n\n    @classmethod\n    def from_hdf(cls, filename):\n        \"\"\"Load camera model params from a HDF5 file\n\n        The HDF5 file should contain the following datasets:\n            wc : (2,) float with distortion center\n            lgamma : float distortion parameter\n            readout : float readout value\n            size : (2,) int image size\n            fps : float frame rate\n            K : (3, 3) float camera matrix\n\n        Parameters\n        --------------------\n        filename : str\n            Path to file with parameters\n\n        Returns\n        ---------------------\n        AtanCameraModel\n            Camera model instance\n        \"\"\"\n        import h5py\n        with h5py.File(filename, 'r') as f:\n            wc = f[\"wc\"].value\n            lgamma = f[\"lgamma\"].value\n            K = f[\"K\"].value\n            readout = f[\"readout\"].value\n            image_size = f[\"size\"].value\n            fps = f[\"fps\"].value\n            instance = cls(image_size, fps, readout, K, wc, lgamma)\n            return instance\n\n    def invert(self, points):\n        \"\"\"Invert the distortion\n\n        Parameters\n        ------------------\n        points : ndarray\n            Input image points\n\n        Returns\n        -----------------\n        ndarray\n            Undistorted points\n        \"\"\"\n        X = points if not points.ndim == 1 else points.reshape((points.size, 1))\n\n        wx, wy = self.wc\n\n        # Switch to polar coordinates\n        rn = np.sqrt((X[0,:] - wx)**2 + (X[1,:] - wy)**2)\n        phi = np.arctan2(X[1,:] - wy, X[0,:]-wx)\n        # 'atan' method\n        r = np.tan(rn * self.lgamma) / self.lgamma;\n\n        # Switch back to rectangular coordinates\n        Y = np.ones(X.shape)\n        Y[0,:] = wx + r * np.cos(phi)\n        Y[1,:]= wy + r * np.sin(phi)\n        return Y\n\n    def apply(self, points):\n        \"\"\"Apply the distortion\n\n        Parameters\n        ---------------------\n        points : ndarray\n            Input image points\n\n        Returns\n        -----------------\n        ndarray\n            Distorted points\n        \"\"\"\n        X = points if not points.ndim == 1 else points.reshape((points.size, 1))\n\n        wx, wy = self.wc\n\n        # Switch to polar coordinates\n        rn = np.sqrt((X[0,:] - wx)**2 + (X[1,:] - wy)**2)\n        phi = np.arctan2(X[1,:] - wy, X[0,:] - wx)\n\n        r = np.arctan(rn * self.lgamma) / self.lgamma\n\n        # Switch back to rectangular coordinates\n        Y = np.ones(X.shape)\n        Y[0,:] = wx + r * np.cos(phi)\n        Y[1,:] = wy + r * np.sin(phi)\n\n        return Y\n\n    def project(self, points):\n        \"\"\"Project 3D points to image coordinates.\n\n        This projects 3D points expressed in the camera coordinate system to image points.\n\n        Parameters\n        --------------------\n        points : (3, N) ndarray\n            3D points\n\n        Returns\n        --------------------\n        image_points : (2, N) ndarray\n            The world points projected to the image plane\n        \"\"\"\n        K = self.camera_matrix\n        XU = points\n        XU = XU / np.tile(XU[2], (3,1))\n        X = self.apply(XU)\n        x2d = np.dot(K, X)\n        return from_homogeneous(x2d)\n\n    def unproject(self, image_points):\n        \"\"\"Find (up to scale) 3D coordinate of an image point\n\n        This is the inverse of the `project` function.\n        The resulting 3D points are only valid up to an unknown scale.\n\n        Parameters\n        ----------------------\n        image_points : (2, N) ndarray\n            Image points\n\n        Returns\n        ----------------------\n        points : (3, N) ndarray\n            3D coordinates (valid up to scale)\n        \"\"\"\n        Ki = self.inv_camera_matrix\n        X = np.dot(Ki, to_homogeneous(image_points))\n        X = X / X[2]\n        XU = self.invert(X)\n        return XU\n\n\nclass OpenCVCameraModel(CameraModel):\n    \"\"\"OpenCV camera model\n\n    This implements the camera model as defined in OpenCV.\n    For details, see the OpenCV documentation.\n    \"\"\"\n    def __init__(self, image_size, frame_rate, readout, camera_matrix, dist_coefs):\n        \"\"\"Create camera model\n\n        Parameters\n        -------------------\n        image_size : tuple (rows, columns)\n            The size of the image in pixels\n        frame_rate : float\n            The frame rate of the camera\n        readout : float\n            Rolling shutter readout time. Set to 0 for global shutter cameras.\n        camera_matrix : (3, 3) ndarray\n            The internal camera calibration matrix\n        dist_coefs : ndarray\n            Distortion coefficients [k1, k2, p1, p2 [,k3 [,k4, k5, k6]] of 4, 5, or 8 elements.\n            Can be set to None to use zero parameters\n        \"\"\"\n        super(OpenCVCameraModel, self).__init__(image_size, frame_rate, readout)\n        self.camera_matrix = camera_matrix\n        self.inv_camera_matrix = np.linalg.inv(self.camera_matrix)\n        self.dist_coefs = dist_coefs\n\n    def project(self, points):\n        \"\"\"Project 3D points to image coordinates.\n\n        This projects 3D points expressed in the camera coordinate system to image points.\n\n        Parameters\n        --------------------\n        points : (3, N) ndarray\n            3D points\n\n        Returns\n        --------------------\n        image_points : (2, N) ndarray\n            The world points projected to the image plane\n        \"\"\"\n        rvec = tvec = np.zeros(3)\n        image_points, jac = cv2.projectPoints(points.T.reshape(-1,1,3), rvec, tvec, self.camera_matrix, self.dist_coefs)\n        return image_points.reshape(-1,2).T\n\n    def unproject(self, image_points):\n        \"\"\"Find (up to scale) 3D coordinate of an image point\n\n        This is the inverse of the `project` function.\n        The resulting 3D points are only valid up to an unknown scale.\n\n        Parameters\n        ----------------------\n        image_points : (2, N) ndarray\n            Image points\n\n        Returns\n        ----------------------\n        points : (3, N) ndarray\n            3D coordinates (valid up to scale)\n        \"\"\"\n        undist_image_points = cv2.undistortPoints(image_points.T.reshape(1,-1,2), self.camera_matrix, self.dist_coefs, P=self.camera_matrix)\n        world_points = np.dot(self.inv_camera_matrix, to_homogeneous(undist_image_points.reshape(-1,2).T))\n        return world_points\n    \n    @classmethod\n    def from_hdf(cls, filepath):\n        import h5py\n        with h5py.File(filepath, 'r') as f:\n            dist_coef = f[\"dist_coef\"].value\n            K = f[\"K\"].value\n            readout = f[\"readout\"].value\n            image_size = f[\"size\"].value\n            fps = f[\"fps\"].value\n            instance = cls(image_size, fps, readout, K, dist_coef)\n            return instance\n\n\ndef to_homogeneous(X):\n    if X.ndim == 1:\n        return np.append(X, 1)\n    else:\n        _, N = X.shape\n        Y = np.ones((3, N))\n        return np.vstack((X, np.ones((N, ))))\n\ndef from_homogeneous(X):\n    Y = X / X[2]\n    return Y[:2]\n\n# Below is legacy code (pre-ICRA2015)\n\nclass Camera(object):\n    def __init__(self):\n        self.K = None\n        self.readout_time = 0.0\n        self.timestamps = []\n        self.files = [] # Filenames, same index corresponds to timestamps list\n        self._images = []\n    \n    def load_image(self, filename):\n        return cv2.imread(filename, cv2.CV_LOAD_IMAGE_GRAYSCALE)\n    \n    @property\n    def images(self):\n        if len(self._images) < 1:\n            self._images = [self.load_image(f) for f in self.files]\n        return self._images\n        \n    def image_sequence(self, first=0, last=-1):\n        file_slice = self.files[first:] if last == -1 else self.files[first:last+1]\n        for filename in file_slice:\n            img = self.load_image(filename)\n            if img is None:\n                raise IOError(\"Failed to load file %s\" % filename)\n            yield(img)\n  \nclass DepthCamera(Camera):\n    pass\n   \nclass Kinect(object):\n    DEFAULT_DEPTH_NIR_SHIFT = (1.5, -3.5)\n    DEFAULT_OPARS = [0, 0]\n    DEFAULT_NIR_K = np.array([[ 582.67750309,    0.        ,  314.96824757],\n                              [   0.        ,  584.65055308,  248.16240365],\n                              [   0.        ,    0.        ,    1.        ]])\n    DEFAULT_RGB_K = np.array([[ 519.83879135,    0.        ,  313.55797842],\n                              [   0.        ,  520.71387   ,  267.59027502],\n                              [   0.        ,    0.        ,    1.        ]])\n    \n    class NirCamera(Camera):\n        def load_image(self, filename):\n            img = cv2.imread(filename, cv2.CV_LOAD_IMAGE_UNCHANGED).astype('float32')\n            img = remove_slp.remove_slp(img)\n            img = Kinect.NirCamera.convert_nbit_float32_to_uint8(img, 10)\n            return img\n        \n        @staticmethod\n        def convert_nbit_float32_to_uint8(img, nbit):\n            \"Converts a float32 image to a uint8 under the assumption that the float32 image has a bit depth of nbit. Will copy input buffer before making changes to it\"\n            img = img.copy()\n            if nbit != 8:\n                img *= 255.0 / (2**nbit - 1)\n            return img.astype('uint8')\n    \n    def __init__(self, depth_camera, video_camera, mode):\n        self.depth_camera = depth_camera\n        self.video_camera = video_camera\n        self.video_mode = mode\n        self.set_default_params()\n        \n    def set_default_params(self):\n        self.opars =  Kinect.DEFAULT_OPARS # Depth conversion parameters\n        self.depth_nir_shift = Kinect.DEFAULT_DEPTH_NIR_SHIFT # NIR to depth shift params\n        self.depth_camera.K = Kinect.DEFAULT_NIR_K\n        self.video_camera.K = Kinect.DEFAULT_RGB_K if self.video_mode == 'rgb' else Kinect.DEFAULT_NIR_K\n    \n    @classmethod\n    def from_directory(cls, datadir, video_mode='any'):        \n        # ) Load list of NIR files\n        nir_file_list = glob.glob(os.path.join(datadir, 'i-*.pgm'))    \n        nir_file_list.sort()\n\n        # ) Load list of RGB files\n        rgb_file_list = glob.glob(os.path.join(datadir, 'r-*.ppm'))\n        rgb_file_list.sort()\n\n        if video_mode == 'any':\n            video_mode = 'rgb' if len(rgb_file_list) > len(nir_file_list) else 'nir'\n                \n        video_files = rgb_file_list if video_mode == 'rgb' else nir_file_list\n        \n        depth_camera = DepthCamera()\n        # FIXME: KinectNirCamera only handles 10-bit NIR right now\n        video_camera = Kinect.NirCamera() if video_mode == 'nir' else Camera()\n        \n        #) Load list of depth files\n        depth_files = glob.glob(os.path.join(datadir, 'd-*.pgm'))\n        depth_files.sort()\n                \n        # Get a consistent set of files\n        video_files = Kinect.purge_bad_timestamp_files(video_files)\n        depth_files = Kinect.purge_bad_timestamp_files(depth_files)\n\n        if video_mode == 'nir':\n            (video_files, depth_files, _, _) =  Kinect.find_nir_file_with_missing_depth(video_files, depth_files)\n                    \n        depth_timestamps = Kinect.timestamps_from_file_list(depth_files)\n        video_timestamps = Kinect.timestamps_from_file_list(video_files)\n        \n        depth_camera.timestamps = depth_timestamps\n        depth_camera.files = depth_files\n        video_camera.timestamps = video_timestamps\n        video_camera.files = video_files\n        \n        instance = cls(depth_camera, video_camera, video_mode)\n                    \n        return instance\n    \n    @staticmethod\n    def timestamp_from_filename(fname):\n        \"Extract timestamp from filename\"    \n        ts = int(fname.split('-')[-1].split('.')[0])\n        return ts\n    \n    @staticmethod\n    def timestamps_from_file_list(file_list):\n        \"Take list of Kinect filenames (without path) and extracts timestamps while accounting for timestamp overflow (returns linear timestamps).\"\n        timestamps = np.array([Kinect.timestamp_from_filename(fname) for fname in file_list])\n\n        # Handle overflow\n        diff = np.diff(timestamps)\n        idxs = np.flatnonzero(diff < 0)\n        ITEM_SIZE = 2**32\n        for i in idxs:\n            timestamps[i+1:] += ITEM_SIZE\n\n        return timestamps.flatten()\n\n    @staticmethod\n    def detect_bad_timestamps(ts_list):\n        EXPECTED_DELTA = 2002155 # Expected time between IR frames\n        MAX_DIFF = EXPECTED_DELTA / 4\n        bad_list = []\n        for frame_num in range(1, len(ts_list)):\n            diff = ts_list[frame_num] - ts_list[frame_num-1]\n            if abs(diff - EXPECTED_DELTA) > MAX_DIFF:\n                bad_list.append(frame_num)\n\n        return bad_list\n\n    @staticmethod\n    def purge_bad_timestamp_files(file_list):\n        \"Given a list of image files, find bad frames, remove them and modify file_list\"\n        MAX_INITIAL_BAD_FRAMES = 15\n        bad_ts = Kinect.detect_bad_timestamps(Kinect.timestamps_from_file_list(file_list))\n        \n        # Trivial case\n        if not bad_ts:\n            return file_list\n\n        # No bad frames after the initial allowed\n        last_bad = max(bad_ts)\n        if last_bad >= MAX_INITIAL_BAD_FRAMES:\n            raise Exception('Only 15 initial bad frames are allowed, but last bad frame is %d' % last_bad)\n\n        # Remove all frames up to the last bad frame\n        for i in range(last_bad + 1):\n            os.remove(file_list[i])\n\n        # Purge from the list\n        file_list = file_list[last_bad+1:]\n\n        return file_list # Not strictly needed since Python will overwrite the list\n\n    @staticmethod\n    def depth_file_for_nir_file(video_filename, depth_file_list):\n        \"\"\"Returns the corresponding depth filename given a NIR filename\"\"\"\n        (root, filename) = os.path.split(video_filename)\n        needle_ts = int(filename.split('-')[2].split('.')[0])\n        haystack_ts_list = np.array(Kinect.timestamps_from_file_list(depth_file_list))\n        haystack_idx = np.flatnonzero(haystack_ts_list == needle_ts)[0]\n        depth_filename = depth_file_list[haystack_idx]\n        return depth_filename\n        \n    @staticmethod \n    def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list):\n        \"\"\"Returns the *closest* depth file from an RGB filename\"\"\"\n        (root, filename) = os.path.split(rgb_filename)\n        rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list))\n        depth_timestamps = np.array(Kinect.timestamps_from_file_list(depth_file_list))\n        needle_ts = rgb_timestamps[rgb_file_list.index(rgb_filename)]\n        haystack_idx = np.argmin(np.abs(depth_timestamps - needle_ts))\n        depth_filename = depth_file_list[haystack_idx]\n        return depth_filename\n\n    @staticmethod\n    def find_nir_file_with_missing_depth(video_file_list, depth_file_list):\n        \"Remove all files without its own counterpart. Returns new lists of files\"\n        new_video_list = []\n        new_depth_list = []\n        for fname in video_file_list:\n            try:\n                depth_file = Kinect.depth_file_for_nir_file(fname, depth_file_list)                \n                new_video_list.append(fname)\n                new_depth_list.append(depth_file)\n            except IndexError: # Missing file\n                pass\n                \n        # Purge bad files\n        bad_nir = [f for f in video_file_list if f not in new_video_list]\n        bad_depth = [f for f in depth_file_list if f not in new_depth_list]\n        \n        return (new_video_list, new_depth_list, bad_nir, bad_depth)\n    \n    def disparity_image_to_distance(self, dval_img):\n        \"Convert image of Kinect disparity values to distance (linear method)\"\n        dist_img = dval_img / 2048.0\n        dist_img = 1 / (self.opars[0]*dist_img + self.opars[1])\n        return dist_img\n        \n    def align_depth_to_nir(self, depth_img):\n        vpad = np.zeros((4,640))\n        depth_new = np.vstack((vpad, depth_img, vpad))\n        x, y = np.mgrid[0:np.size(depth_new,1), 0:np.size(depth_new,0)]\n        xs = x + self.depth_nir_shift[1]\n        ys = y + self.depth_nir_shift[0]\n    \n        points = np.dstack((x,y)).reshape([-1,2])\n    \n        depth_new = scipy.interpolate.griddata(points, depth_new[points[:,1],points[:,0]].flatten(), (xs.T, ys.T), method='nearest')\n        return depth_new \n        \n    def depthmap_for_nir(self, nir_filename):\n        if not self.video_mode == 'nir':\n            raise Exception(\"Tried to get depth map from NIR, but capture used RGB\")\n        depth_filename = Kinect.depth_file_for_nir_file(nir_filename, self.video_camera.files, self.depth_camera.files)\n        depth_img = cv2.imread(depth_filename, cv2.CV_LOAD_IMAGE_UNCHANGED)\n        depth_img = self.disparity_image_to_distance(depth_img)\n        depth_img = self.align_depth_to_nir(depth_img)\n        return depth_img\n"
  },
  {
    "path": "crisp/cli.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCommand line interface helpers\n\"\"\"\nfrom __future__ import absolute_import\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport os\nimport csv\nimport logging\nlogger = logging.getLogger()\n\nfrom scipy.io import loadmat\n\nfrom .imu import ArduIMU, IMU\n\ndef load_imu_from_file(imu_file):\n    try:\n        imu = ArduIMU(imu_file)\n        logger.debug(\"Loaded IMU data from ArduIMU logfile %s\" % imu_file)\n        return imu\n    except (IOError, ValueError):\n        logger.debug(\"%s did not load as ArduIMU file\" % imu_file)\n        \n    try:\n        imu = IMU.from_mat_file(imu_file)\n        logger.debug(\"Loaded IMU data from .mat-file %s\" % imu_file)\n        return imu\n    except IOError:\n        logger.debug(\"%s did not load as MAT file\" % imu_file)\n    \n    return None\n\n#--------------------------------------------------------------------------\n\ndef load_vars_from_mat(filename, var_dict):\n    result_dict = {}\n    M = loadmat(filename)\n    for var_name, possible_names in list(var_dict.items()):\n        val = None\n        for key in possible_names:\n            logger.debug(\"Trying %s for variable %s in %s\" % (key, var_name, filename))\n            try:\n                val = M[key]\n                break\n            except KeyError:\n                pass\n        if val is None:\n            raise ValueError(\"Could not find a candidate for requested variable %s\" % var_name)\n        result_dict[var_name]= val\n            \n    return result_dict\n    \n#--------------------------------------------------------------------------\n\ndef load_images_timestamps_from_csv(image_csv):\n    (root, _) = os.path.split(image_csv)\n    timestamps = []\n    files = []\n    with open(image_csv, 'rb') as f:\n        reader = csv.reader(f)\n        for row in reader:\n            filename, timestamp = row[:2]\n            _, filename = os.path.split(filename)\n            timestamp = float(timestamp)\n            image_path = os.path.join(root, filename)\n            timestamps.append(timestamp)\n            files.append(image_path)\n    return files, timestamps"
  },
  {
    "path": "crisp/fastintegrate/fastintegrate.pyx",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb  3 18:10:40 2014\n\n@author: hannes\n\"\"\"\ncimport cython\n\nimport numpy as np\ncimport numpy as np\n\ncdef extern from \"math.h\":\n    double sqrt(double x)\n\nDTYPE = np.float\nctypedef np.double_t DTYPE_t\n\n@cython.boundscheck(False)\ndef integrate_gyro_quaternion_uniform(np.ndarray[DTYPE_t,ndim=2] gyro_data, np.float dt,\n                                      initial=None):\n    #NB: Quaternion q = [a, n1, n2, n3], scalar first\n    cdef unsigned int N = gyro_data.shape[0]\n    cdef np.ndarray[DTYPE_t, ndim=2] q_list = np.empty((N, 4)) # Nx4 quaternion list\n    \n    # Iterate over all (except first)\n    cdef unsigned int i, j\n    cdef DTYPE_t wx, wy, wz\n    cdef DTYPE_t q0, q1, q2, q3\n        \n    #cdef np.ndarray[DTYPE_t, ndim=1] qnew = np.zeros((4,))\n    cdef DTYPE_t qnorm\n    cdef DTYPE_t dt_half = dt / 2.0\n    \n    # Initial rotation\n    if initial is None:\n        q0 = 1.0\n        q1 = q2 = q3 = 0.0\n    else:\n        q0, q1, q2, q3 = initial\n    \n    for i in range(N):\n        wx = gyro_data[i,0]\n        wy = gyro_data[i,1]\n        wz = gyro_data[i,2]\n                \n        q_list[i, 0] = q0 + dt_half * (-wx*q1 -wy*q2 -wz*q3)\n        q_list[i, 1] = q1 + dt_half * (q0*wx + q2*wz - wy*q3)\n        q_list[i, 2] = q2 + dt_half * (wy*q0 -wz*q1 + wx*q3)\n        q_list[i, 3] = q3 + dt_half * (wz*q0 + wy*q1 -wx*q2)\n\n        # Normalize\n        qnorm = sqrt(q_list[i, 0]**2 + q_list[i, 1]**2 + q_list[i, 2]**2 + q_list[i, 3]**2)\n        for j in range(4):\n            q_list[i, j] /= qnorm\n        \n        # New prev values\n        q0 = q_list[i, 0]\n        q1 = q_list[i, 1]\n        q2 = q_list[i, 2]\n        q3 = q_list[i, 3]\n    return q_list"
  },
  {
    "path": "crisp/imu.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nIMU module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\n#--------------------------------------------------------------------------\n# Includes\n#--------------------------------------------------------------------------\n\nimport numpy as np\nimport re\n\nimport scipy.io\n\nfrom . import rotations\nfrom . import fastintegrate\nfrom . import l3g4200d\n#--------------------------------------------------------------------------\n# Classes\n#--------------------------------------------------------------------------\n\nclass IMU(object):\n    \"\"\"\n    Defines an IMU (currently only gyro)\n    \"\"\"\n    def __init__(self):\n        self.integrated = []\n        self.gyro_data = []\n        self.timestamps = []\n    \n    @classmethod\n    def from_mat_file(cls, matfilename):\n        \"\"\"Load gyro data from .mat file\n        \n        The MAT file should contain the following two arrays\n        \n        gyro : (3, N) float ndarray\n                The angular velocity measurements.\n        timestamps : (N, ) float ndarray\n                Timestamps of the measurements.\n                \n        Parameters\n        ---------------\n        matfilename : string\n                Name of the .mat file\n        \n        Returns\n        ----------------\n        A new IMU class instance\n        \"\"\"\n        M = scipy.io.loadmat(matfilename)\n        instance = cls()\n        instance.gyro_data = M['gyro']\n        instance.timestamps = M['timestamps']\n        return instance\n        \n    \n    @property    \n    def rate(self):\n        \"\"\"Get the sample rate in Hz.\n        \n        Returns\n        ---------\n        rate : float\n                The sample rate, in Hz, calculated from the timestamps        \n        \"\"\"\n        N = len(self.timestamps)\n        t = self.timestamps[-1] - self.timestamps[0]\n        rate = 1.0 * N / t\n        return rate\n\n    def zero_level_calibrate(self, duration, t0=0.0):\n        \"\"\"Performs zero-level calibration from the chosen time interval.\n        \n        This changes the previously lodaded data in-place.\n        \n        Parameters\n        --------------------\n        duration : float\n                Number of timeunits to use for calibration\n        t0 : float \n                Starting time for calibration\n                \n        Returns\n        ----------------------\n        gyro_data : (3, N) float ndarray\n                The calibrated data (note that it is also changed in-place!)\n        \"\"\"\n        \n        t1 = t0 + duration\n        indices = np.flatnonzero((self.timestamps >= t0) & (self.timestamps <= t1))\n        m = np.mean(self.gyro_data[:, indices], axis=1)\n        self.gyro_data -= m.reshape(3,1)\n        \n        return self.gyro_data\n        \n    def gyro_data_corrected(self, pose_correction=np.eye(3)):\n        \"\"\"Get relative pose corrected data.\n        \n        Parameters\n        -------------\n        pose_correction : (3,3) ndarray, optional\n                Rotation matrix that describes the relative pose between the IMU and something else (e.g. camera).\n        \n        Returns\n        ---------------\n        gyro_data : (3, N) ndarray\n                The relative pose corrected data.\n        \"\"\"\n        return pose_correction.dot(self.gyro_data)\n            \n    def integrate(self, pose_correction=np.eye(3), uniform=True):\n        \"\"\"Integrate angular velocity measurements to rotations.\n\n        Parameters\n        -------------\n        pose_correction : (3,3) ndarray, optional\n                Rotation matrix that describes the relative pose between the IMU and something else (e.g. camera).\n        uniform : bool\n                If True (default), assume uniform sample rate. This will use a faster integration method.\n        Returns\n        -------------\n        rotations : (4, N) ndarray\n                Rotations as unit quaternions with scalar as first element.\n        \"\"\"\n        \n        if uniform:\n            dt = float(self.timestamps[1]-self.timestamps[0]) # Must be python float for fastintegrate to work\n            return fastintegrate.integrate_gyro_quaternion_uniform(self.gyro_data_corrected, dt)\n        else:            \n            N = len(self.timestamps)\n            integrated = np.zeros((4, N))\n            integrated[:,0] = np.array([1, 0, 0, 0]) # Initial rotation (no rotation)\n            \n            # Iterate over all\n            for i in range(1, len(self.timestamps)):\n                w = pose_correction.dot(self.gyro_data[:, i]) # Change to correct coordinate frame\n                dt = float(self.timestamps[i] - self.timestamps[i - 1])\n                qprev = integrated[:, i - 1].flatten()\n                \n                A = np.array([[0,    -w[0],  -w[1],  -w[2]],\n                             [w[0],  0,      w[2],  -w[1]],\n                             [w[1], -w[2],   0,      w[0]],\n                             [w[2],  w[1],  -w[0],   0]])\n                qnew = (np.eye(4) + (dt/2.0) * A).dot(qprev)\n                qnorm = np.sqrt(np.sum(qnew ** 2))\n                qnew = qnew / qnorm if qnorm > 0 else 0\n                integrated[:, i] = qnew\n                #print \"%d, %s, %s, %s, %s\" % (i, w, dt, qprev, qnew)\n            return integrated\n        \n    @staticmethod\n    def rotation_at_time(t, timestamps, rotation_sequence):\n        \"\"\"Get the gyro rotation at time t using SLERP.\n        \n        Parameters\n        -----------\n        t : float\n                The query timestamp.\n        timestamps : array_like float\n                List of all timestamps\n        rotation_sequence : (4, N) ndarray\n                Rotation sequence as unit quaternions with scalar part as first element.\n                \n        Returns\n        -----------\n        q : (4,) ndarray\n                Unit quaternion representing the rotation at time t.\n        \"\"\"\n        idx = np.flatnonzero(timestamps >= (t - 0.0001))[0]\n        t0 = timestamps[idx - 1]\n        t1 = timestamps[idx]\n        tau = (t - t0) / (t1 - t0)\n        \n        q1 = rotation_sequence[:, idx - 1]\n        q2 = rotation_sequence[:, idx]\n        q = rotations.slerp(q1, q2, tau)\n        return q\n\nclass ArduIMU(IMU):\n    def __init__(self, filename):\n        super(ArduIMU, self).__init__()\n        self.filename = filename\n        ts, acc, gyro = self.__load(filename)\n        self.timestamps = ts\n        self.gyro_data = gyro\n    \n    def __load(self, gyro_data_filename):\n        f = open(gyro_data_filename, 'r')\n        # Read header\n        if not f.readline().strip().startswith('RPY'):\n            raise ValueError(\"This is not a ArduIMU log file\")\n            \n        data = np.array([[]], dtype='float32')\n        data.shape = 0,7\n        for line in f.readlines():\n            row = [int(s) for s in re.findall('\\d+', line)]\n            if len(row) == 8:\n                if row[7] != 1:\n                    pass # \"Checksum error, skipping\"\n                else:\n                    data = np.append(data, [row[0:7]], axis=0)\n\n        timestamps = data[:,0]\n        timestamps -= timestamps[0] # Start at 0\n        timestamps /= 1000.0 # Milliseconds -> seconds\n            \n        # Map from 10-bit value to voltage\n        # The arduino has mapped the range [0,Vref] to [0,1023] before removing the offset\n        Vref = 3.3    \n        data[:,1:] *= (Vref / 1023.0);\n\n        accelerometer = data[:,1:4]\n        gyroscope = data[:,4:7]\n        \n        # Scale gyro output\n        gyro_scale = 3.33 / 1000 # (V/(degrees/s)) From datasheet (not ratiometric)\n        gyroscope = np.deg2rad(gyroscope / gyro_scale) #  rad / s\n        \n        # Scale accelerometer\n        gravity = 9.81\n        gravity_scale = 0.330 # V/g\n        accelerometer /= gravity_scale; # Scale to acceleration in g's\n        accelerometer *= gravity # Scale to acceleration in m/s2\n\n        return (timestamps, accelerometer.T, gyroscope.T)\n        \nclass L3G4200DGyro(IMU):\n    def __init__(self, filename, post_process=True):\n        super(L3G4200DGyro, self).__init__()\n        self.filename = filename\n        ts, gyro = self.__load(filename, post_process)\n        self.timestamps = ts\n        self.gyro_data = gyro\n        \n    def __load(self, filename, post_process=True):\n        data, ts, T = l3g4200d.load_L3G_arduino(filename)\n        \n        # Our L3G4200D rig has some issues\n        if post_process:\n            print(\"Post processing L3G4200D data\")\n            data = l3g4200d.post_process_L3G4200D_data(data)\n            assert data.shape[0] == 3, \"Expected gyro to have 3 elements in first dim, got {0:d}\".format(data.shape[0])\n        return ts, data\n\n\n\n\n"
  },
  {
    "path": "crisp/l3g4200d.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nCreated on Wed Mar  5 10:24:38 2014\n\n@author: hannes\n\"\"\"\n\nimport numpy as np\nimport struct\n\nclass ParserException(Exception):\n    pass\n\nclass GyroParserBase(object):\n    def __init__(self):\n        self.fs = None # Full scale resolution. Max rate. (dps)\n        self.data_scale = None # mdps per digit\n        self.data = None\n\n    def parse(self, data):\n        raise NotImplemented()\n        \nclass L3GArduinoParser(GyroParserBase):\n    COMMAND_START = 0xAB\n    COMMAND_DATA  = 0xC8\n    COMMAND_SAMPLE_RATE = 0xDB\n    COMMAND_TIME_SYNC = 0xBB\n    REG_CTRL1 = 0x20\n    REG_CTRL4 = 0x23\n    FS_RATE_FACTOR = { 250 : 8.75e-3, # From L3G datasheet\n                       500 : 17.50e-3, \n                       2000 : 70e-3 }\n    \n    def __init__(self):\n        GyroParserBase.__init__(self)\n        self.reg = {} # Register -> value map\n        self.ndata = 0\n        self.actual_data_rate = None\n        self.fs = None\n        self.data_scale = None\n        self.sync_times = []\n    \n    def parse(self, input_data):\n        total_bytes = len(input_data)\n        self.data = np.empty((3, total_bytes // 6)) # Will be lower than this\n        temp_data = input_data\n        num_bytes = 0\n        while num_bytes < total_bytes - 1:\n             command = ord(temp_data[num_bytes])\n             length = ord(temp_data[num_bytes + 1])\n             data = temp_data[num_bytes+2:num_bytes+2+length]\n             #data_str = \" \".join([\"%x\" % ord(x) for x in data])\n             #print \"Command: %x, Length: %x, Data: %s\" % (command, length, data_str)\n             self.__handle(command, data)\n             num_bytes += length + 2\n        try:\n            self.data *= self.data_scale\n        except RuntimeWarning:\n            print(\"Scale warning! res=\", self.data, \"*\", self.data_scale)\n        self.data = self.data[:,0:self.ndata]\n             \n                    \n    def __handle(self, command, data):\n        if command == L3GArduinoParser.COMMAND_DATA:\n            if not self.data_scale:\n                raise ParserException(\"No data scale loaded before first data packet\")\n            raw_str = data #b''.join([chr(x) for x in data])\n            sfmt = \"<hhh\"\n            n = len(raw_str) // 6\n            for i in range(n):\n                data_str = raw_str[6*i:6*i+6]\n                x, y, z = struct.unpack(sfmt, data_str)\n                arr= np.array([x, y, z])#.reshape(3, 1)\n                self.data[:, self.ndata] = arr\n                self.ndata += 1\n        elif command == L3GArduinoParser.COMMAND_START:\n            for reg, val in zip(data[::2], data[1::2]):\n                reg = ord(reg)\n                val = ord(val)\n                self.reg[reg] = val\n                #print \"Checking reg %x with val %x\" % (reg, val)\n                if reg == L3GArduinoParser.REG_CTRL4:\n                    fsbits = (val & 0x30) >> 4\n                    fs = {0 : 250, 1 : 500, 2 : 2000, 3 : 2000}[fsbits]\n                    self.fs = fs\n                    self.data_scale = L3GArduinoParser.FS_RATE_FACTOR[self.fs]\n                if reg == L3GArduinoParser.REG_CTRL1:\n                    drbits = (val & 0xC0) >> 6\n                    self.data_rate = {0 : 100, 1 : 200, 2 : 400 , 3 : 800}[drbits]\n        elif command == L3GArduinoParser.COMMAND_SAMPLE_RATE:\n            sfmt = '<L'\n            #print \"Sample rate byte (%d) %s\" % (len(data), data.__repr__())\n            #T = struct.unpack(sfmt, data)\n            #print \"Got sample rate\", T\n            print(\"Got sample rate byte, but until implementation is changed in Arduino code, the value should not be used as it is unstable as hell.\")\n            # Note: Reimplement the Arduino code to emit timestamps on a regular basis that can be used to fix the time rate.\n            self.actual_data_rate = None#1000000. / T[0] # Hz\n        elif command == L3GArduinoParser.COMMAND_TIME_SYNC:\n            sfmt = '<L'\n            ts = struct.unpack(sfmt, data)[0] / 1000.0 # msec -> seconds\n            self.sync_times.append((self.ndata, ts))\n                    \ndef load_L3G_arduino(filename, remove_begin_spurious=False, return_parser=False):\n    \"Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)\"\n    file_data = open(filename, 'rb').read()\n    parser = L3GArduinoParser()\n    parser.parse(file_data[7:]) # Skip first \"GYROLOG\" header in file\n    data = parser.data\n    if parser.actual_data_rate:\n        T = 1. / parser.actual_data_rate\n        print(\"Found measured data rate %.3f ms (%.3f Hz)\" % (1000*T, 1. / T))\n    else:\n        T = 1. / parser.data_rate\n        print(\"Using data rate provided by gyro (probably off by a few percent!) %.3f ms (%.3f Hz)\" % (1000*T, 1. / T))\n        \n    N = parser.data.shape[1]\n    t = np.linspace(0, T*N, num=data.shape[1])\n    print(t.shape, data.shape)\n    print(\"Loaded %d samples (%.2f seconds) with expected sample rate %.3f ms (%.3f Hz)\" % (N, t[-1], T*1000.0, 1./T))\n    try:\n        print(\"Actual sample rate is %.3f ms (%.3f Hz)\" % (1000. / parser.actual_data_rate, parser.actual_data_rate, ))\n    except TypeError:\n        pass\n    \n    if remove_begin_spurious:\n        to_remove = int(0.3/T) # Remove first three tenth of second\n        data[:,:to_remove] = 0.0\n    \n    if return_parser:\n        return np.deg2rad(data), t, T, parser\n    else:\n        return np.deg2rad(data), t, T\n\ndef post_process_L3G4200D_data(data, do_plot=False):\n    def notch(Wn, bandwidth):\n        f = Wn/2.0\n        R = 1.0 - 3.0*(bandwidth/2.0)\n        K = ((1.0 - 2.0*R*np.cos(2*np.pi*f) + R**2)/(2.0 -\n        2.0*np.cos(2*np.pi*f)))\n        b,a = np.zeros(3),np.zeros(3)\n        a[0] = 1.0\n        a[1] = - 2.0*R*np.cos(2*np.pi*f)\n        a[2] = R**2\n        b[0] = K\n        b[1] = -2*K*np.cos(2*np.pi*f)\n        b[2] = K\n        return b,a\n\n    # Remove strange high frequency noise and bias\n    b,a = notch(0.8, 0.03)\n    data_filtered = np.empty_like(data)\n    from scipy.signal import filtfilt\n    for i in range(3):\n        data_filtered[i] = filtfilt(b, a, data[i])\n\n    if do_plot:\n        from matplotlib.pyplot import subplot, plot, specgram, title\n        # Plot the difference\n        ax = None\n        for i in range(3):\n            if ax is None:\n                ax = subplot(5,1,i+1)\n            else:\n                subplot(5,1,i+1, sharex=ax, sharey=ax)\n            plot(data[i])\n            plot(data_filtered[i])\n            title(['x','y','z'][i])\n        subplot(5,1,4)\n        specgram(data[0])\n        title(\"Specgram of biased X\")\n        subplot(5,1,5)\n        specgram(data_filtered[0])\n        title(\"Specgram of filtered unbiased X\")\n\n    return data_filtered\n"
  },
  {
    "path": "crisp/pose.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nRelative pose calibration module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport logging\nlogger = logging.getLogger()\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\n\nfrom . import timesync\nfrom . import tracking\nfrom . import rotations\n\ndef estimate_pose(image_sequences, imu_sequences, K):\n    \"\"\"Estimate sync between IMU and camera based on gyro readings and optical flow.\n    \n    The user should first create at least two sequences of corresponding image and \n    gyroscope data.\n    From each sequence we calculate the rotation axis (one from images, one from IMU/gyro).\n    The final set of len(image_sequences) corresponding rotation axes are then used to calculate\n    the relative pose between the IMU and camera.\n    \n    The returned rotation is such that it transfers vectors in the gyroscope coordinate\n    frame to the camera coordinate frame:\n    \n        X_camera = R * X_gyro\n    \n    \n    Parameters\n    ------------\n    image_sequences : list of list of ndarrays \n            List of image sequences (list of ndarrays) to use. Must have at least two sequences.\n    imu_sequences : list of (3, N) ndarray\n            Sequence of gyroscope measurements (angular velocities).\n    K : (3,3) ndarray\n            Camera calibration matrix\n            \n    Returns\n    -----------\n    R : (3,3) ndarray\n            The relative pose (gyro-to-camera) such that X_camera = R * X_gyro\n    \"\"\"\n    assert len(image_sequences) == len(imu_sequences)\n    assert len(image_sequences) >= 2\n    # Note: list(image_sequence) here makes sure any generator type input is expanded to an actual list\n    sync_correspondences = [_get_point_correspondences(list(image_sequence)) for image_sequence in image_sequences]\n    \n    # ) Procrustes on corresponding pairs\n    PROCRUSTES_MAX_POINTS = 15 # Number of tracks/points to use for procrustes\n    logger.debug(\"Running procrustes on track-retrack results\")\n    image_rotation_axes = []\n    for i, points in enumerate(sync_correspondences):\n        if points.size < 1:\n            logger.error('Shape of points are %s', str(points.shape))\n            raise Exception(\"Did not get enough points when tracking\")\n        num_points_to_use = min(PROCRUSTES_MAX_POINTS, points.shape[0])\n        logger.debug(\"Using %d tracks to calculate procrustes\", num_points_to_use)\n        idxs_to_use = np.random.permutation(points.shape[0])[:num_points_to_use]\n        assert points.shape[-1] == 2\n        x = points[idxs_to_use,0,:].T.reshape(2,-1)\n        y = points[idxs_to_use,-1,:].T.reshape(2,-1)\n\n        x = np.vstack((x, np.ones((1, x.shape[1]))))\n        y = np.vstack((y, np.ones((1, y.shape[1]))))\n\n        K_inv = np.linalg.inv(K)\n        X = K_inv.dot(x)\n        Y = K_inv.dot(y)\n\n        # Depth must be positive\n        (R, t) = rotations.procrustes(X, Y, remove_mean=False) # X = R * Y + t\n        (v, theta) = rotations.rotation_matrix_to_axis_angle(R)\n        image_rotation_axes.append(v) # Save rotation axis\n        \n        # Check the quality via the mean reprojection error\n        mean_error = np.mean(np.sqrt(np.sum((X - R.dot(Y))**2, axis=0)))\n        MEAN_ERROR_LIMIT = 0.1 # Arbitrarily chosen limit (in meters)\n        logger.debug('Image sequence %d: Rotation axis %s, degrees %.2f, mean error %.3f',\n            i, v, np.rad2deg(theta), mean_error)\n        if mean_error > MEAN_ERROR_LIMIT: \n            logger.warning(\"Procrustes solution mean error %.3f > %.3f\", mean_error, MEAN_ERROR_LIMIT)\n\n    # ) Gyro principal rotation axis\n    gyro_rotation_axes = []\n    for i, gyro_seq in enumerate(imu_sequences):\n        assert gyro_seq.shape[0] == 3\n        v = principal_rotation_axis(gyro_seq)\n        logger.debug('Gyro sequence %d: Rotation axis %s', i, v)\n        gyro_rotation_axes.append(v)\n        \n    # ) Procrustes to get rotation between coordinate frames\n    X = np.vstack(image_rotation_axes).T\n    Y = np.vstack(gyro_rotation_axes).T\n    (R,t) = rotations.procrustes(X, Y, remove_mean=False)\n\n    return (R, t)\n\n#--------------------------------------------------------------------------\n\ndef pick_manual(image_sequence, imu_gyro, num_sequences=2):\n    \"\"\"Select N matching sequences and return data indices.\n    \n    Parameters\n    ---------------\n    image_sequence : list_like\n            A list, or generator, of image data\n    imu_gyro : (3, N) ndarray\n            Gyroscope data (angular velocities)\n    num_sequences : int\n            The number of matching sequences to pick\n    \n    Returns\n    ----------------\n    sync_sequences : list\n            List of (frame_pair, gyro_pair) tuples where each pair contains\n            (a, b) which are indices of the (inclusive) range [a, b] that was chosen\n    \"\"\"\n    assert num_sequences >= 2    \n    # Create optical flow for user to select parts in\n    logger.info(\"Calculating optical flow\")\n    flow = tracking.optical_flow_magnitude(image_sequence)\n    \n    # ) Prompt user for sync slices\n    logger.debug(\"Prompting user for %d sequences\" % num_sequences)\n    imu_fake_timestamps = np.linspace(0,1,num=imu_gyro.shape[1])\n    sync_sequences = [timesync.manual_sync_pick(flow, imu_fake_timestamps, imu_gyro) for i in range(num_sequences)]\n\n    return sync_sequences\n\n#--------------------------------------------------------------------------\n\ndef principal_rotation_axis(gyro_data):\n    \"\"\"Get the principal rotation axis of angular velocity measurements.    \n    \n    Parameters\n    -------------\n    gyro_data : (3, N) ndarray\n            Angular velocity measurements\n           \n    Returns\n    -------------\n    v : (3,1) ndarray\n            The principal rotation axis for the chosen sequence\n    \"\"\"\n    N = np.zeros((3,3))\n    for x in gyro_data.T: # Transpose because samples are stored as columns\n        y = x.reshape(3,1)\n        N += y.dot(y.T)\n        \n    (eig_val, eig_vec) = np.linalg.eig(N)\n    i = np.argmax(eig_val)\n    v = eig_vec[:,i]\n    \n    # Make sure v has correct sign\n    s = 0\n    for x in gyro_data.T: # Transpose because samples are stored as columns\n        s += v.T.dot(x.reshape(3,1))\n        \n    v *= np.sign(s)\n    \n    return v\n    \n#--------------------------------------------------------------------------\n\ndef _get_point_correspondences(image_list, max_corners=200, min_distance=5, quality_level=0.07):\n    max_retrack_distance = 0.5\n    initial_points = cv2.goodFeaturesToTrack(image_list[0], max_corners, quality_level, min_distance)\n    (tracks, status) = tracking.track_retrack(image_list, initial_points=initial_points, max_retrack_distance=max_retrack_distance) # Status is ignored\n    return tracks[:,(0,-1),:] # First and last frame only\n"
  },
  {
    "path": "crisp/ransac.py",
    "content": "from __future__ import division, print_function, absolute_import\n\nimport numpy as np\n\ndef RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False):\n    \"\"\"Apply RANSAC.\n\n    This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated using the points in the consensus set.\n\n    Parameters\n    ------------\n    model_func: Takes a data parameter of size DxK where K is the number of points needed to construct the model and returns the model (Mx1 vector)\n    eval_func: Takes a model parameter (Lx1) and one or more data points (DxC, C>=1) and calculates the score of the point(s) relative to the selected model\n    data : array (DxN) where D is dimensionality and N number of samples\n    \"\"\"\n    M = None\n    max_consensus = 0\n    all_idx = list(range(data.shape[1]))\n    final_consensus = []\n    for k in range(num_iter):\n        np.random.shuffle(all_idx)\n        model_set = all_idx[:num_points]\n        x = data[:, model_set]\n        m = model_func(x)\n\n        model_error = eval_func(m, data)\n        assert model_error.ndim == 1\n        assert model_error.size == data.shape[1]\n        consensus_idx = np.flatnonzero(model_error < threshold)\n\n        if len(consensus_idx) > max_consensus:\n            M = m\n            max_consensus = len(consensus_idx)\n            final_consensus = consensus_idx            \n\n    # Recalculate using current consensus set?\n    if recalculate and len(final_consensus) > 0:\n        final_consensus_set = data[:, final_consensus]\n        M = model_func(final_consensus_set)\n\n    return (M, final_consensus)\n"
  },
  {
    "path": "crisp/remove_slp.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nKinect NIR Structured Light Pattern removal\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\n# Adapted from MATLAB code written by Per-Erik Forssén (perfo@isy.liu.se)\n\n#--------------------------------------------------------------------------\n# Includes\n#--------------------------------------------------------------------------\n\nimport cv2\nimport numpy as np\n\n#--------------------------------------------------------------------------\n# Default parameters\n#--------------------------------------------------------------------------\n\nGSTD1 = 0.575\nGSTD2 = 2.3\nGSTD3 = 3.4\nW = 9.0\nKSIZE = 19 # MATLAB equivalent of -9:9\nEPS = 2.2204E-16\n\n#--------------------------------------------------------------------------\n# Public functions\n#--------------------------------------------------------------------------\ndef remove_slp(img, gstd1=GSTD1, gstd2=GSTD2, gstd3=GSTD3, ksize=KSIZE, w=W):\n    \"\"\"Remove the SLP from kinect IR image\n    \n    The input image should be a float32 numpy array, and should NOT be a square root image\n    Parameters\n    ------------------\n    img : (M, N) float ndarray\n            Kinect NIR image with SLP pattern\n    gstd1 : float\n            Standard deviation of gaussian kernel 1\n    gstd2 : float\n            Standard deviation of gaussian kernel 2\n    gstd3 : float\n            Standard deviation of gaussian kernel 3\n    ksize : int\n            Size of kernel (should be odd)\n    w   : float\n            Weighting factor\n\n    Returns\n    ------------------\n    img_noslp : (M,N) float ndarray\n            Input image with SLP removed\n    \"\"\"\n    gf1 = cv2.getGaussianKernel(ksize, gstd1)\n    gf2 = cv2.getGaussianKernel(ksize, gstd2)\n    gf3 = cv2.getGaussianKernel(ksize, gstd3)\n    sqrtimg = cv2.sqrt(img)\n    p1 = cv2.sepFilter2D(sqrtimg, -1, gf1, gf1)\n    p2 = cv2.sepFilter2D(sqrtimg, -1, gf2, gf2)\n    maxarr = np.maximum(0, (p1 - p2) / p2)\n    minarr = np.minimum(w * maxarr, 1)\n    p = 1 - minarr\n    nc = cv2.sepFilter2D(p, -1, gf3, gf3) + EPS\n    output = cv2.sepFilter2D(p*sqrtimg, -1, gf3, gf3)\n    output = (output / nc) ** 2 # Since input is sqrted\n    \n    return output\n"
  },
  {
    "path": "crisp/rotations.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nRotation handling module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport numpy as np\n\nfrom numpy.testing import assert_almost_equal\n\nfrom . import ransac\n\n#------------------------------------------------------------------------------\n\ndef procrustes(X, Y, remove_mean=False):\n    \"\"\"Orthogonal procrustes problem solver\n    \n    The procrustes problem  finds the best rotation R, and translation t\n    where\n        X = R*Y + t\n    \n    The number of points in X and Y must be at least 2.\n    For the minimal case of two points, a third point is temporarily created\n    and used for the estimation.\n    \n    Parameters\n    -----------------\n    X : (3, N) ndarray\n            First set of points\n    Y : (3, N) ndarray\n            Second set of points\n    remove_mean : bool\n            If true, the mean is removed from X and Y before solving the\n            procrustes problem. Can yield better results in some applications.\n            \n    Returns\n    -----------------\n    R : (3,3) ndarray\n            Rotation component\n    t : (3,) ndarray\n            Translation component (None if remove_mean is False)\n \"\"\"\n\n    assert X.shape == Y.shape\n    assert X.shape[0] > 1\n    \n    # Minimal case, create third point using cross product\n    if X.shape[0] == 2:\n        X3 = np.cross(X[:,0], X[:,1], axis=0)\n        X = np.hstack((X, X3 / np.linalg.norm(X3)))\n        Y3 = np.cross(Y[:,0], Y[:,1], axis=0)\n        Y = np.hstack((Y, Y3 / np.linalg.norm(Y3)))\n        \n    \n    D, N = X.shape[:2]\n    if remove_mean:\n        mx = np.mean(X, axis=1).reshape(D, 1)\n        my = np.mean(Y, axis=1).reshape(D, 1)\n        Xhat = X - mx\n        Yhat = Y - my\n    else:\n        Xhat = X\n        Yhat = Y\n\n\n    (U, S, V) = np.linalg.svd((Xhat).dot(Yhat.T))\n\n    Dtmp = np.eye(Xhat.shape[0])\n    Dtmp[-1,-1] = np.linalg.det(U.dot(V))\n\n    R_est = U.dot(Dtmp).dot(V)\n\n    # Now X=R_est*(Y-my)+mx=R_est*Y+t_est\n    if remove_mean:\n        t_est= mx - R_est.dot(my)\n    else:\n        t_est = None\n    return (R_est, t_est)\n\n#--------------------------------------------------------------------------\n\ndef rotation_matrix_to_axis_angle(R):\n    \"\"\"Convert a 3D rotation matrix to a 3D axis angle representation\n    \n    Parameters\n    ---------------\n    R : (3,3) array\n        Rotation matrix\n        \n    Returns\n    ----------------\n    v : (3,) array\n        (Unit-) rotation angle\n    theta : float\n        Angle of rotations, in radians\n    \n    Note\n    --------------\n    This uses the algorithm as described in Multiple View Geometry, p. 584\n    \"\"\"\n    assert R.shape == (3,3)\n    assert_almost_equal(np.linalg.det(R), 1.0, err_msg=\"Not a rotation matrix: determinant was not 1\")\n    S, V = np.linalg.eig(R)\n    k = np.argmin(np.abs(S - 1.))\n    s = S[k]\n    assert_almost_equal(s, 1.0, err_msg=\"Not a rotation matrix: No eigen value s=1\")\n    v = np.real(V[:, k]) # Result is generally complex\n    \n    vhat = np.array([R[2,1] - R[1,2], R[0,2] - R[2,0], R[1,0] - R[0,1]])\n    sintheta = 0.5 * np.dot(v, vhat)\n    costheta = 0.5 * (np.trace(R) - 1)\n    theta = np.arctan2(sintheta, costheta)\n    \n    return (v, theta)\n\n#--------------------------------------------------------------------------\n\ndef axis_angle_to_rotation_matrix(v, theta):\n    \"\"\"Convert rotation from axis-angle to rotation matrix\n    \n        Parameters\n    ---------------\n    v : (3,) ndarray\n            Rotation axis (normalized)\n    theta : float\n            Rotation angle (radians)\n\n    Returns\n    ----------------\n    R : (3,3) ndarray\n            Rotation matrix\n    \"\"\"\n    if np.abs(theta) < np.spacing(1):\n        return np.eye(3)\n    else:\n        v = v.reshape(3,1)\n        np.testing.assert_almost_equal(np.linalg.norm(v), 1.)\n        vx = np.array([[0, -v[2], v[1]],\n                       [v[2], 0, -v[0]],\n                       [-v[1], v[0], 0]])\n        vvt = np.dot(v, v.T)\n        R = np.eye(3)*np.cos(theta) + (1 - np.cos(theta))*vvt + vx * np.sin(theta)\n        return R\n\n#--------------------------------------------------------------------------\n\ndef quat_to_rotation_matrix(q):\n    \"\"\"Convert unit quaternion to rotation matrix\n    \n    Parameters\n    -------------\n    q : (4,) ndarray\n            Unit quaternion, scalar as first element\n\n    Returns\n    ----------------\n    R : (3,3) ndarray\n            Rotation matrix\n    \n    \"\"\"\n    q = q.flatten()\n    assert q.size == 4\n    assert_almost_equal(np.linalg.norm(q), 1.0, err_msg=\"Not a unit quaternion!\")\n    qq = q ** 2\n    R = np.array([[qq[0] + qq[1] - qq[2] - qq[3], 2*q[1]*q[2] -\n2*q[0]*q[3], 2*q[1]*q[3] + 2*q[0]*q[2]],\n                [2*q[1]*q[2] + 2*q[0]*q[3], qq[0] - qq[1] + qq[2] -\nqq[3], 2*q[2]*q[3] - 2*q[0]*q[1]],\n                [2*q[1]*q[3] - 2*q[0]*q[2], 2*q[2]*q[3] + 2*q[0]*q[1],\nqq[0] - qq[1] - qq[2] + qq[3]]])\n    return R\n\n#--------------------------------------------------------------------------\n\ndef integrate_gyro_quaternion(gyro_ts, gyro_data):\n    \"\"\"Integrate angular velocities to rotations\n    \n    Parameters\n    ---------------\n    gyro_ts : ndarray\n            Timestamps\n    gyro_data : (3, N) ndarray\n            Angular velocity measurements\n    \n    Returns\n    ---------------\n    rotations : (4, N) ndarray\n            Rotation sequence as unit quaternions (first element scalar)\n    \n    \"\"\"\n    #NB: Quaternion q = [a, n1, n2, n3], scalar first\n    q_list = np.zeros((gyro_ts.shape[0], 4)) # Nx4 quaternion list\n    q_list[0,:] = np.array([1, 0, 0, 0]) # Initial rotation (no rotation)\n    \n    # Iterate over all (except first)\n    for i in range(1, gyro_ts.size):\n        w = gyro_data[i]\n        dt = gyro_ts[i] - gyro_ts[i - 1]\n        qprev = q_list[i - 1]\n        \n        A = np.array([[0,    -w[0],  -w[1],  -w[2]],\n                     [w[0],  0,      w[2],  -w[1]],\n                     [w[1], -w[2],   0,      w[0]],\n                     [w[2],  w[1],  -w[0],   0]])\n        qnew = (np.eye(4) + (dt/2.0) * A).dot(qprev)\n        qnorm = np.sqrt(np.sum(qnew ** 2))\n        qnew /= qnorm\n        q_list[i] = qnew\n         \n    return q_list\n\n#--------------------------------------------------------------------------\n\ndef slerp(q1, q2, u):\n    \"\"\"SLERP: Spherical linear interpolation between two unit quaternions.\n    \n    Parameters\n    ------------\n    q1 : (4, ) ndarray\n            Unit quaternion (first element scalar)\n    q2 : (4, ) ndarray\n            Unit quaternion (first element scalar)\n    u : float\n            Interpolation factor in range [0,1] where 0 is first quaternion \n            and 1 is second quaternion.\n            \n    Returns\n    -----------\n    q : (4,) ndarray\n            The interpolated unit quaternion\n    \"\"\"\n    q1 = q1.flatten()\n    q2 = q2.flatten()\n    assert q1.shape == q2.shape\n    assert q1.size == 4\n    costheta = np.dot(q1, q2)\n\n    if np.isclose(u, 0.):\n        return q1\n    elif np.isclose(u, 1.):\n        return q2\n    elif u > 1 or u < 0:\n        raise ValueError(\"u must be in range [0, 1]\")\n\n    # Shortest path\n    if costheta < 0:\n        costheta = -costheta\n        q2 = -q2\n\n    # Almost the same, we can return any of them?\n    if np.isclose(costheta, 1.0):\n        return q1\n\n    theta = np.arccos(costheta)\n\n    f1 = np.sin((1.0 - u)*theta) / np.sin(theta)\n    f2 = np.sin(u*theta) / np.sin(theta)\n    q = f1*q1 + f2*q2\n    q = q / np.sqrt(np.sum(q**2)) # Normalize\n    return q\n\n#--------------------------------------------------------------------------\n\ndef estimate_rotation_procrustes_ransac(x, y, camera, threshold, inlier_ratio=0.75, do_translation=False):\n    \"\"\"Calculate rotation between two sets of image coordinates using ransac.\n    \n    Inlier criteria is the reprojection error of y into image 1.\n\n    Parameters\n    -------------------------\n    x : array 2xN image coordinates in image 1\n    y : array 2xN image coordinates in image 2\n    camera : Camera model\n    threshold : float pixel distance threshold to accept as inlier\n    do_translation : bool Try to estimate the translation as well\n\n    Returns\n    ------------------------\n    R : array 3x3 The rotation that best fulfills X = RY\n    t : array 3x1 translation if do_translation is False\n    residual : array pixel distances ||x - xhat|| where xhat ~ KRY (and lens distorsion)\n    inliers : array Indices of the points (in X and Y) that are RANSAC inliers\n    \"\"\"\n    assert x.shape == y.shape\n    assert x.shape[0] == 2\n    \n    X = camera.unproject(x)\n    Y = camera.unproject(y)\n    \n    data = np.vstack((X, Y, x))\n    assert data.shape[0] == 8\n    \n    model_func = lambda data: procrustes(data[:3], data[3:6], remove_mean=do_translation)\n    \n    def eval_func(model, data):\n        Y = data[3:6].reshape(3,-1)\n        x = data[6:].reshape(2,-1)\n        R, t = model\n\n        Xhat = np.dot(R, Y) if t is None else np.dot(R, Y) + t\n        xhat = camera.project(Xhat)\n        dist = np.sqrt(np.sum((x-xhat)**2, axis=0))\n\n        return dist\n    \n    inlier_selection_prob = 0.99999\n    model_points = 2\n    ransac_iterations = int(np.log(1 - inlier_selection_prob) / np.log(1-inlier_ratio**model_points))\n    \n    model_est, ransac_consensus_idx = ransac.RANSAC(model_func, eval_func, data, model_points, ransac_iterations, threshold, recalculate=True)    \n    if model_est is not None:\n        (R, t) = model_est\n        dist = eval_func((R, t), data)                \n    else:\n        dist = None\n        R, t = None, None\n        ransac_consensus_idx = []\n\n    return R, t, dist, ransac_consensus_idx\n"
  },
  {
    "path": "crisp/stream.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nInput streams module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2015, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport os\nimport collections\nimport logging\nlogger = logging.getLogger('crisp')\n\nimport cv2\nimport numpy as np\n\nfrom . import fastintegrate, tracking, rotations\n\n# Handle OpenCV 2.4.x -> 3.0\ntry:\n    CV_CAP_PROP_POS_MSEC = cv2.cv.CV_CAP_PROP_POS_MSEC\nexcept AttributeError:\n    CV_CAP_PROP_POS_MSEC = cv2.CAP_PROP_POS_MSEC\n\nclass GyroStream(object):\n    def __init__(self):\n        self.__last_dt = None\n        self.__last_q = None\n        self.data = None # Arranged as Nx3 where N is number of samples\n\n    @classmethod\n    def from_csv(cls, filename):\n        \"\"\"Create gyro stream from CSV data\n\n        Load data from a CSV file.\n        The data must be formatted with three values per line: (x, y, z)\n        where x, y, z is the measured angular velocity (in radians) of the specified axis.\n\n        Parameters\n        -------------------\n        filename : str\n            Path to the CSV file\n\n        Returns\n        ---------------------\n        GyroStream\n            A gyroscope stream\n        \"\"\"\n        instance = cls()\n        instance.data = np.loadtxt(filename, delimiter=',')\n        return instance\n\n    @classmethod\n    def from_data(cls, data):\n        \"\"\"Create gyroscope stream from data array\n\n        Parameters\n        -------------------\n        data : (N, 3) ndarray\n            Data array of angular velocities (rad/s)\n\n        Returns\n        -------------------\n        GyroStream\n            Stream object\n        \"\"\"\n        if not data.shape[1] == 3:\n            raise ValueError(\"Gyroscope data must have shape (N, 3)\")\n\n        instance = cls()\n        instance.data = data\n        return instance\n\n\n    @property\n    def num_samples(self):\n        return self.data.shape[0]\n\n    def integrate(self, dt):\n        \"\"\"Integrate gyro measurements to orientation using a uniform sample rate.\n\n        Parameters\n        -------------------\n        dt : float\n            Sample distance in seconds\n\n        Returns\n        ----------------\n        orientation : (4, N) ndarray\n                    Gyroscope orientation in quaternion form (s, q1, q2, q3)\n        \"\"\"\n        if not dt == self.__last_dt:\n            self.__last_q = fastintegrate.integrate_gyro_quaternion_uniform(self.data, dt)\n            self.__last_dt = dt\n        return self.__last_q\n\nclass VideoStream(object):\n    \"\"\"Video stream representation\n\n    This is the base class for all video streams, and should normally not be used directly.\n    Instead you should use a VideoStream subclass that can work on the data you have.\n\n    The concept of a video stream can be summarized as something that\n    \"provides frames of video data captured by a single camera\".\n\n    A VideoStream object is iterable to allow reading frames easily::\n\n        stream = VideoStreamSubClass(SOME_PARAMETER)\n        for frame in stream:\n            do_stuff(frame)\n\n    \"\"\"\n    def __init__(self, camera_model, flow_mode='optical'):\n        \"\"\"Create a VideoStream object\n\n        Parameters\n        ----------------\n        camera_model : CameraModel\n                     Camera model used by this stream\n        \"\"\"\n        self._flow = None\n        self.flow_mode = flow_mode\n        self.camera_model = camera_model\n\n    def __iter__(self):\n        return self._frames()\n\n    def _frames(self):\n        raise NotImplementedError(\"{} does not implement the _frames() method used to extract frames\".format(self.__class__.__name__))\n\n    @classmethod\n    def from_file(cls, camera_model, filename):\n        \"\"\"Create stream automatically from filename.\n\n        Note\n        --------------------\n        This currently only works with video files that are readable by OpenCV\n\n        Parameters\n        --------------------\n        camera_model : CameraModel\n            Camera model to use with this stream\n        filename : str\n            The filename to load the stream data from\n\n        Returns\n        --------------------\n        VideoStream\n            Video stream of a suitable sub class\n        \"\"\"\n        # TODO: Other subclasses\n        return OpenCvVideoStream(camera_model, filename)\n\n    def project(self, points):\n        \"\"\"Project 3D points to image coordinates.\n\n        This projects 3D points expressed in the camera coordinate system to image points.\n\n        Parameters\n        --------------------\n        points : (3, N) ndarray\n            3D points\n\n        Returns\n        --------------------\n        image_points : (2, N) ndarray\n            The world points projected to the image plane of the camera used by the stream\n        \"\"\"\n        return self.camera_model.project(points)\n\n    def unproject(self, image_points):\n        \"\"\"Find (up to scale) 3D coordinate of an image point\n\n        This is the inverse of the `project` function.\n        The resulting 3D points are only valid up to an unknown scale.\n\n        Parameters\n        ----------------------\n        image_points : (2, N) ndarray\n            Image points\n\n        Returns\n        ----------------------\n        points : (3, N) ndarray\n            3D coordinates (valid up to scale)\n        \"\"\"\n        return self.camera_model.unproject(image_points)\n\n    @property\n    def frame_rate(self):\n        return self.camera_model.frame_rate\n    \n    @property\n    def flow(self):\n        if self._flow is None:\n            logger.debug(\"Generating flow. This can take minutes depending on video length\")\n            if self.flow_mode == 'rotation':\n                self._generate_frame_to_frame_rotation()\n            elif self.flow_mode == 'optical':\n                self._flow = tracking.optical_flow_magnitude(self)\n            else:\n                raise ValueError(\"No such flow mode '{}'\".format(self.flow_mode))\n            #self.__generate_flow()\n        return self._flow\n\n    def _generate_frame_to_frame_rotation(self):\n        rotation = []\n        weights = []\n        step = 1\n        maxlen = step + 1\n        frame_queue = collections.deque([], maxlen)\n        for frame in self:\n            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n            frame_queue.append(frame)\n            if len(frame_queue) == maxlen:\n                max_corners = 500\n                quality_level = 0.07  # Why??\n                min_distance = 10\n                initial_pts = cv2.goodFeaturesToTrack(frame_queue[0], max_corners, quality_level, min_distance)\n                pts, status = tracking.track_retrack(list(frame_queue), initial_pts)\n                X = pts[:, 0, :].T\n                Y = pts[:, 1, :].T\n                threshold = 2.0\n                R, _, err, inliers = rotations.estimate_rotation_procrustes_ransac(X, Y, self.camera_model, threshold)\n                if R is None:\n                    weight = 0\n                    angle = 0\n                    r = np.zeros(3)\n                else:\n                    weight = (1.0 * len(inliers)) / len(pts)\n                    axis, angle = rotations.rotation_matrix_to_axis_angle(R)\n                    r = axis * angle\n                rotation.append(r.reshape(3, 1))\n                weights.append(weight)\n\n        rotation = np.hstack(rotation)\n        weights = np.array(weights)\n\n        # Scale from rad/frame to rad/s\n        rotation *= self.camera_model.frame_rate\n\n        # Remove and interpolate bad values\n        threshold = 0.2\n        mask = weights > threshold\n        x = np.arange(rotation.shape[1])\n        for i in range(3):\n            rotation[i, ~mask] = np.interp(x[~mask], x[mask], rotation[i, mask])\n\n        self._frame_rotations = rotation\n        self._flow = np.linalg.norm(rotation, axis=0)\n\nclass OpenCvVideoStream(VideoStream):\n    \"\"\"Video stream that uses OpenCV to extract image data.\n\n    This stream class uses the OpenCV VideoCapture class and can thus handle any\n    video type that is supported by the installed version of OpenCV.\n    It can only handle video files, and not live streams.\n    \"\"\"\n    def __init__(self, camera_model, filename, start_time=0.0, duration=None):\n        \"\"\"Create video stream\n\n        Parameters\n        ---------------\n        camera_model : CameraModel\n            Camera model\n        filename : str\n            Path to the video file\n        start_time : float\n            The time in seconds where to start capturing (USE WITH CAUTION)\n        duration : float\n            Duration in seconds to capture (USE WITH CAUTION)\n\n        Notes\n        -------------------\n        You can specify the start time and duration you want to use for the capture.\n        However, be advised that this may or may not work depending on the type of video data\n        and your installation of OpenCV. Use with caution!\n        \"\"\"\n        super(OpenCvVideoStream, self).__init__(camera_model)\n        self.filename = filename\n        self.start_time = start_time\n        self.duration = duration\n        self.step = 1\n\n    def _frames(self):\n        vc = cv2.VideoCapture(self.filename)\n        if not vc.isOpened():\n            raise IOError(\"Failed to open '{}'. Either there is something wrong with the file or OpenCV does not have the correct codec\".format(self.filename))\n        # OpenCV does something really stupid: to set the frame we need to set it twice and query in between\n        t = self.start_time * 1000. # turn to milliseconds\n        t2 = t + self.duration*1000.0 if self.duration is not None else None\n\n        for i in range(2): # Sometimes needed for setting to stick\n            vc.set(CV_CAP_PROP_POS_MSEC, t)\n            vc.read()\n        t = vc.get(CV_CAP_PROP_POS_MSEC)\n        counter = 0\n        retval = True\n        while retval and (t2 is None or (t2 is not None and t < t2)):\n            retval, im = vc.read()\n            if retval:\n                if np.mod(counter, self.step) == 0:\n                    yield im\n            elif t2 is not None:\n                raise IOError(\"Failed to get frame at time %.2f\" % t)\n            else:\n                pass # Loop will end normally\n            t = vc.get(CV_CAP_PROP_POS_MSEC)\n            counter += 1\n"
  },
  {
    "path": "crisp/timesync.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nTime synchronization module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\n#--------------------------------------------------------------------------\n# Includes\n#--------------------------------------------------------------------------\nimport logging\nlogger = logging.getLogger()\nimport time\n\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as ssig\nimport scipy.optimize\nfrom matplotlib.mlab import normpdf\n\nfrom . import tracking\nfrom .imu import IMU\nfrom . import rotations\nfrom . import znccpyr\n\n#--------------------------------------------------------------------------\n# Public functions\n#--------------------------------------------------------------------------\n\ndef sync_camera_gyro(image_sequence_or_flow, image_timestamps, gyro_data, gyro_timestamps, levels=6, full_output=False):\n    \"\"\"Get time offset that aligns image timestamps with gyro timestamps.\n    \n    Given an image sequence, and gyroscope data, with their respective timestamps,\n    calculate the offset that aligns the image data with the gyro data.\n    The timestamps must only differ by an offset, not a scale factor.\n\n    This function finds an approximation of the offset *d* that makes this transformation\n\n        t_gyro = t_camera + d\n        \n    i.e. your new image timestamps should be\n    \n        image_timestamps_aligned = image_timestamps + d\n        \n    The offset is calculated using zero-mean cross correlation of the gyroscope data magnitude\n    and the optical flow magnitude, calculated from the image sequence.\n    ZNCC is performed using pyramids to make it quick.\n    \n    The offset is accurate up to about +/- 2 frames, so you should run\n    *refine_time_offset* if you need better accuracy.\n    \n    Parameters\n    ---------------\n    image_sequence_or_flow : sequence of image data, or ndarray\n            This must be either a list or generator that provides a stream of \n            images that are used for optical flow calculations.\n    image_timestamps : ndarray\n            Timestamps of the images in image_sequence\n    gyro_data : (3, N) ndarray\n            Gyroscope measurements (angular velocity)\n    gyro_timestamps : ndarray\n            Timestamps of data in gyro_data\n    levels : int\n            Number of pyramid levels\n    full_output : bool\n            If False, only return the offset, otherwise return extra data\n            \n    Returns\n    --------------\n    time_offset  :  float\n            The time offset to add to image_timestamps to align the image data\n            with the gyroscope data\n    flow : ndarray\n            (Only if full_output=True)\n            The calculated optical flow magnitude\n    \"\"\"\n    \n    # If input is not flow, then create from iamge sequence\n    try:\n        assert image_sequence_or_flow.ndim == 1\n        flow_org = image_sequence_or_flow\n    except AssertionError:    \n        flow_org = tracking.optical_flow_magnitude(image_sequence_or_flow)\n    \n    # Gyro from gyro data\n    gyro_mag = np.sum(gyro_data**2, axis=0)\n    flow_timestamps = image_timestamps[:-2]\n\n    # Resample to match highest\n    rate = lambda ts: len(ts) / (ts[-1] - ts[0])\n    freq_gyro = rate(gyro_timestamps)\n    freq_image = rate(flow_timestamps)\n    \n    if freq_gyro > freq_image:\n        rel_rate = freq_gyro / freq_image\n        flow_mag = znccpyr.upsample(flow_org, rel_rate)\n    else:\n        flow_mag = flow_org\n        rel_rate = freq_image / freq_gyro\n        gyro_mag = znccpyr.upsample(gyro_mag, rel_rate)\n    \n    ishift = znccpyr.find_shift_pyr(flow_mag, gyro_mag, levels)\n    \n    if freq_gyro > freq_image:\n        flow_shift = int(-ishift / rel_rate)\n    else:\n        flow_shift = int(-ishift)\n    \n    time_offset = flow_timestamps[flow_shift]\n    \n    if full_output:\n        return time_offset, flow_org # Return the orginal flow, not the upsampled version\n    else:\n        return time_offset\n        \n#--------------------------------------------------------------------------\n\ndef sync_camera_gyro_manual(image_sequence, image_timestamps, gyro_data, gyro_timestamps, full_output=False):\n    \"\"\"Get time offset that aligns image timestamps with gyro timestamps.\n    \n    Given an image sequence, and gyroscope data, with their respective timestamps,\n    calculate the offset that aligns the image data with the gyro data.\n    The timestamps must only differ by an offset, not a scale factor.\n\n    This function finds an approximation of the offset *d* that makes this transformation\n\n        t_gyro = t_camera + d\n        \n    i.e. your new image timestamps should be\n    \n        image_timestamps_aligned = image_timestamps + d\n        \n    The offset is calculated using correlation. The parts of the signals to use are\n    chosen by the user by picking points in a plot window.\n\n    The offset is accurate up to about +/- 2 frames, so you should run\n    *refine_time_offset* if you need better accuracy.\n    \n    Parameters\n    ---------------\n    image_sequence : sequence of image data\n            This must be either a list or generator that provides a stream of \n            images that are used for optical flow calculations.\n    image_timestamps : ndarray\n            Timestamps of the images in image_sequence\n    gyro_data : (3, N) ndarray\n            Gyroscope measurements (angular velocity)\n    gyro_timestamps : ndarray\n            Timestamps of data in gyro_data\n    full_output : bool\n            If False, only return the offset, otherwise return extra data\n            \n    Returns\n    --------------\n    time_offset  :  float\n            The time offset to add to image_timestamps to align the image data\n            with the gyroscope data\n    flow : ndarray\n            (Only if full_output=True)\n            The calculated optical flow magnitude\n    frame_pair : (int, int)\n            The frame pair that was picked for synchronization\n    \"\"\"\n    \n    flow = tracking.optical_flow_magnitude(image_sequence)\n    flow_timestamps = image_timestamps[:-2]    \n    \n    # Let user select points in both pieces of data\n    (frame_pair, gyro_idx) = manual_sync_pick(flow, gyro_timestamps, gyro_data)\n    \n    # Normalize data\n    gyro_abs_max = np.max(np.abs(gyro_data), axis=0)\n    gyro_normalized = (gyro_abs_max / np.max(gyro_abs_max)).flatten()\n    flow_normalized = (flow / np.max(flow)).flatten()\n\n    rate = lambda ts: len(ts) / (ts[-1] - ts[0])\n\n    # Resample to match highest\n    freq_gyro = rate(gyro_timestamps)\n    freq_image = rate(flow_timestamps)\n    logger.debug(\"Gyro sampling frequency: %.2f Hz, Image sampling frequency: %.2f Hz\", freq_gyro, freq_image)\n    \n    gyro_part = gyro_normalized[gyro_idx[0]:gyro_idx[1]+1] # only largest\n    flow_part = flow_normalized[frame_pair[0]:frame_pair[1]+1]\n    \n    N = flow_part.size * freq_gyro / freq_image\n    flow_part_resampled = ssig.resample(flow_part, N).flatten()\n    \n    # ) Cross correlate the two signals and find time diff\n    corr = ssig.correlate(gyro_part, flow_part_resampled, 'full') # Find the flow in gyro data\n \n    i = np.argmax(corr)\n    \n    t_0_f = flow_timestamps[frame_pair[0]]\n    t_1_f = flow_timestamps[frame_pair[1]]\n    \n    t_off_g = gyro_timestamps[gyro_idx[0] + i]\n    t_off_f = t_1_f\n    time_offset = t_off_g - t_off_f\n    \n    if full_output:\n        return time_offset, flow, frame_pair\n    else:\n        return time_offset\n\n#--------------------------------------------------------------------------\n\ndef manual_sync_pick(flow, gyro_ts, gyro_data):\n    # First pick good points in flow\n    plt.clf()\n    plt.plot(flow)\n    plt.title('Select two points')\n    selected_frames = [int(round(x[0])) for x in plt.ginput(2)]\n\n    # Now pick good points in gyro\n    plt.clf()\n    plt.subplot(211)\n    plt.plot(flow)\n    plt.plot(selected_frames, flow[selected_frames], 'ro')\n    \n    plt.subplot(212)\n    plt.plot(gyro_ts, gyro_data.T)\n    plt.title('Select corresponding sequence in gyro data')\n    plt.draw()\n    selected = plt.ginput(2) #[int(round(x[0])) for x in plt.ginput(2)]\n    gyro_idxs = [(gyro_ts >= x[0]).nonzero()[0][0] for x in selected]\n    plt.plot(gyro_ts[gyro_idxs], gyro_data[:, gyro_idxs].T, 'ro')\n    plt.title('Ok, click to continue to next')\n    plt.draw()\n    plt.waitforbuttonpress(timeout=10.0)\n    plt.close()\n    \n    return (tuple(selected_frames), gyro_idxs)\n\n#--------------------------------------------------------------------------\n\ndef refine_time_offset(image_list, frame_timestamps, rotation_sequence, rotation_timestamps, camera_matrix, readout_time):\n    \"\"\"Refine a time offset between camera and IMU using rolling shutter aware optimization.\n    \n    To refine the time offset using this function, you must meet the following constraints\n    \n    1) The data must already be roughly aligned. Only a few image frames of error\n        is allowed.\n    2) The images *must* have been captured by a *rolling shutter* camera.\n    \n    This function finds a refined offset using optimization.\n    Points are first tracked from the start to the end of the provided images.\n    Then an optimization function looks at the reprojection error of the tracked points\n    given the IMU-data and the refined offset.\n    \n    The found offset *d* is such that you want to perform the following time update\n    \n        new_frame_timestamps = frame_timestamps + d\n    \n    Parameters\n    ------------\n    image_list : list of ndarray\n            A list of images to perform tracking on. High quality tracks are required,\n            so make sure the sequence you choose is easy to track in.\n    frame_timestamps : ndarray\n            Timestamps of image_list\n    rotation_sequence : (4, N) ndarray\n            Absolute rotations as a sequence of unit quaternions (first element is scalar).\n    rotation_timestamps : ndarray\n            Timestamps of rotation_sequence\n    camera_matrix : (3,3) ndarray\n            The internal camera calibration matrix of the camera.\n    readout_time : float\n            The readout time of the camera.\n            \n    Returns\n    ------------\n    offset : float\n            A refined offset that aligns the image data with the rotation data.\n    \"\"\"\n    # ) Track points\n    max_corners = 200\n    quality_level = 0.07\n    min_distance = 5\n    max_tracks = 20\n    initial_points = cv2.goodFeaturesToTrack(image_list[0], max_corners, quality_level, min_distance)\n    (points, status) = tracking.track_retrack(image_list, initial_points)\n\n    # Prune to at most max_tracks number of tracks, choose randomly    \n    track_id_list = np.random.permutation(points.shape[0])[:max_tracks]\n        \n    rows, cols = image_list[0].shape[:2]\n    row_delta_time = readout_time / rows            \n    num_tracks, num_frames, _ = points.shape\n    K = np.matrix(camera_matrix)\n    \n    def func_to_optimize(td, *args):\n        res = 0.0\n        N = 0\n        for frame_idx in range(num_frames-1):            \n            for track_id in track_id_list:                \n                p1 = points[track_id, frame_idx, :].reshape((-1,1))\n                p2 = points[track_id, frame_idx + 1, :].reshape((-1,1))\n                t1 = frame_timestamps[frame_idx] + (p1[1] - 1) * row_delta_time + td\n                t2 = frame_timestamps[frame_idx + 1] + (p2[1] - 1) * row_delta_time +td\n                t1 = float(t1)\n                t2 = float(t2)\n                q1 = IMU.rotation_at_time(t1, rotation_timestamps, rotation_sequence)\n                q2 = IMU.rotation_at_time(t2, rotation_timestamps, rotation_sequence)\n                R1 = rotations.quat_to_rotation_matrix(q1)\n                R2 = rotations.quat_to_rotation_matrix(q2)\n                p1_rec = K.dot(R1.T).dot(R2).dot(K.I).dot(np.vstack((p2, 1)))\n                if p1_rec[2] == 0:\n                    continue\n                else:\n                    p1_rec /= p1_rec[2]                    \n                res += np.sum((p1 - np.array(p1_rec[0:2]))**2)\n                N += 1\n        return res / N\n    \n    # Bounded Brent optimizer\n    t0 = time.time()\n    tolerance = 1e-4 # one tenth millisecond\n    (refined_offset, fval, ierr, numfunc) = scipy.optimize.fminbound(func_to_optimize, -0.12, 0.12, xtol=tolerance, full_output=True)\n    t1 = time.time()\n    if ierr == 0:\n        logger.info(\"Time offset found by brent optimizer: %.4f. Elapsed: %.2f seconds (%d function calls)\", refined_offset, t1-t0, numfunc)\n    else:\n        logger.error(\"Brent optimizer did not converge. Aborting!\")\n        raise Exception(\"Brent optimizer did not converge, when trying to refine offset.\")\n    \n    return refined_offset\n    \n    \ndef good_sequences_to_track(flow, motion_threshold=1.0):\n    \"\"\"Get list of good frames to do tracking in.\n\n    Looking at the optical flow, this function chooses a span of frames\n    that fulfill certain criteria.\n    These include\n        * not being too short or too long\n        * not too low or too high mean flow magnitude\n        * a low max value (avoids motion blur)\n    Currently, the cost function for a sequence is hard coded. Sorry about that.\n    \n    Parameters\n    -------------\n    flow : ndarray\n            The optical flow magnitude\n    motion_threshold : float\n            The maximum amount of motion to consider for sequence endpoints.\n            \n    Returns\n    ------------\n    sequences : list\n            Sorted list of (a, b, score) elements (highest scpre first) of sequences\n            where a sequence is frames with frame indices in the span [a, b].\n    \"\"\"\n    endpoints = []\n    in_low = False\n    for i, val in enumerate(flow):\n        if val < motion_threshold:\n            if not in_low:\n                endpoints.append(i)\n                in_low = True\n        else:\n            if in_low:\n                endpoints.append(i-1) # Previous was last in a low spot\n            in_low = False\n    \n    def mean_score_func(m):\n        mu = 15\n        sigma = 8\n        top_val = normpdf(mu, mu, sigma)\n        return normpdf(m, mu, sigma) / top_val\n    \n    def max_score_func(m):\n        mu = 40\n        sigma = 8\n        if m <= mu:\n            return 1.\n        else:\n            top_val = normpdf(mu, mu, sigma)\n            return normpdf(m, mu, sigma) / top_val\n    \n    def length_score_func(l):\n        mu = 30\n        sigma = 10\n        top_val = normpdf(mu, mu, sigma)\n        return normpdf(l, mu, sigma) / top_val\n    \n    min_length = 5 # frames\n    sequences = []\n    for k, i in enumerate(endpoints[:-1]):\n        for j in endpoints[k+1:]:\n            length = j - i\n            if length < min_length:\n                continue\n            seq = flow[i:j+1]\n            m_score = mean_score_func(np.mean(seq))\n            mx_score = max_score_func(np.max(seq))\n            l_score = length_score_func(length)\n            logger.debug(\"%d, %d scores: (mean=%.5f, max=%.5f, length=%.5f)\" % (i,j,m_score, mx_score, l_score))\n            if min(m_score, mx_score, l_score) < 0.2:\n                continue\n            \n            score = m_score + mx_score + l_score \n            sequences.append((i, j, score))\n\n    return sorted(sequences, key=lambda x: x[2], reverse=True)\n"
  },
  {
    "path": "crisp/tracking.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nTracking module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2013, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\n#--------------------------------------------------------------------------\n# Includes\n#--------------------------------------------------------------------------\n\nimport cv2\nimport numpy as np\n\n#--------------------------------------------------------------------------\n# Parameters\n#--------------------------------------------------------------------------\n\nGFTT_DEFAULTS = {'max_corners' : 40,\n                'quality_level' : 0.07,\n                'min_distance' : 10}    \n\n#--------------------------------------------------------------------------\n# Public functions\n#--------------------------------------------------------------------------\n\ndef track_points(img1, img2, initial_points=None, gftt_params={}):\n    \"\"\"Track points between two images\n    \n    Parameters\n    -----------------\n    img1 : (M, N) ndarray\n            First image\n    img2 : (M, N) ndarray\n            Second image\n    initial_points : ndarray\n            Initial points. If empty, initial points will be calculated from\n            img1 using goodFeaturesToTrack in OpenCV\n    gftt_params : dict\n            Keyword arguments for goodFeaturesToTrack\n    \n    Returns\n    -----------------\n    points : ndarray\n            Tracked points\n    initial_points : ndarray\n            Initial points used\n    \"\"\"\n    params = GFTT_DEFAULTS\n    if gftt_params:\n        params.update(gftt_params)\n\n    if initial_points is None:\n        initial_points = cv2.goodFeaturesToTrack(img1, params['max_corners'], params['quality_level'], params['min_distance'])\n    \n    [_points, status, err] = cv2.calcOpticalFlowPyrLK(img1, img2, initial_points, np.array([]))\n\n    # Filter out valid points only\n    points = _points[np.nonzero(status)]\n    initial_points = initial_points[np.nonzero(status)]\n\n    return (points, initial_points)\n\n#--------------------------------------------------------------------------\n\ndef optical_flow_magnitude(image_sequence, max_diff=60, gftt_options={}):\n    \"\"\"Return optical flow magnitude for the given image sequence\n    \n    The flow magnitude is the mean value of the total (sparse) optical flow\n    between two images.\n    Crude outlier detection using the max_diff parameter is used.\n    \n    Parameters\n    ----------------\n    image_sequence : sequence\n            Sequence of image data (ndarrays) to calculate flow magnitude from\n    max_diff : float\n            Distance threshold for outlier rejection\n    gftt_options : dict\n            Keyword arguments to the OpenCV goodFeaturesToTrack function\n            \n    Returns\n    ----------------\n    flow : ndarray\n            The optical flow magnitude\n    \"\"\"\n    flow = []\n    prev_img = None\n    for img in image_sequence:\n        if img.ndim == 3 and img.shape[2] == 3:\n            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n        if prev_img is None:\n            prev_img = img\n            continue\n        (next_points, prev_points) = track_points(prev_img, img, gftt_params=gftt_options)\n        distance = np.sqrt(np.sum((next_points - prev_points)**2, 1))\n        distance2 = distance[np.nonzero(distance < max_diff)] # Crude outlier rejection\n        dm = np.mean(distance2)\n        if np.isnan(dm):\n            dm = 0\n        flow.append(dm)\n        prev_img = img\n\n    return np.array(flow)\n\n#--------------------------------------------------------------------------\n\ndef track(image_list, initial_points, remove_bad=True):\n    \"\"\"Track points in image list\n    \n    Parameters\n    ----------------\n    image_list : list\n            List of images to track in\n    initial_points : ndarray\n            Initial points to use (in first image in image_list)\n    remove_bad : bool\n            If True, then the resulting list of tracks will only contain succesfully\n            tracked points. Else, it will contain all points present in initial_points.\n    \n    Returns\n    -----------------\n    tracks : (N, M, 2) ndarray\n            N tracks over M images with (x,y) coordinates of points\n    status : (N,) ndarray\n            The status of each track. 1 means ok, while 0 means tracking failure\n    \"\"\"\n    # Precreate track array\n    tracks = np.zeros((initial_points.shape[0], len(image_list), 2), dtype='float32') # NxMx2\n    tracks[:,0,:] = np.reshape(np.array(initial_points), [-1,2])\n    track_status = np.ones([np.size(initial_points,0),1]) # All initial points are OK\n    empty = np.array([])\n    window_size = (5,5)\n    for i in range(1, len(image_list)):\n        img1 = image_list[i-1]\n        img2 = image_list[i]\n        prev_ok_track = np.flatnonzero(track_status)\n        prev_points = tracks[prev_ok_track,i-1,:]\n        [points, status, err] = cv2.calcOpticalFlowPyrLK(img1, img2, prev_points, empty, empty, empty, window_size)\n        if status is None:\n            track_status[:] = 0 # All tracks are bad\n            break\n        valid_set = np.flatnonzero(status)\n        now_ok_tracks = prev_ok_track[valid_set] # Remap\n        tracks[now_ok_tracks,i,:] = points[valid_set]\n        track_status[prev_ok_track] = status\n\n    if remove_bad:\n        final_ok = np.flatnonzero(track_status)\n        tracks = tracks[final_ok] # Only rows/tracks with nonzero status\n        track_status = track_status[final_ok] \n\n    return (tracks, track_status)\n\n#--------------------------------------------------------------------------\n\ndef track_retrack(image_list, initial_points, max_retrack_distance=0.5, keep_bad=False):\n    \"\"\"Track-retracks points in image list\n    \n    Using track-retrack can help in only getting point tracks of high quality.    \n    \n    The point is tracked forward, and then backwards in the image sequence.\n    Points that end up further than max_retrack_distance from its starting point\n    are marked as bad.\n    \n    Parameters\n    ----------------\n    image_list : list\n            List of images to track in\n    initial_points : ndarray\n            Initial points to use (in first image in image_list)\n    max_retrack_distance : float\n            The maximum distance of the retracked point from its starting point to \n            still count as a succesful retrack.\n    remove_bad : bool\n            If True, then the resulting list of tracks will only contain succesfully\n            tracked points. Else, it will contain all points present in initial_points.\n    \n    Returns\n    -----------------\n    tracks : (N, M, 2) ndarray\n            N tracks over M images with (x,y) coordinates of points\n            Note that M is the number of image in the input, and is the track in\n            the forward tracking step.\n    status : (N,) ndarray\n            The status of each track. 1 means ok, while 0 means tracking failure\n    \"\"\"\n    (forward_track, forward_status) = track(image_list, initial_points, remove_bad=False)\n    # Reverse the order\n    (backward_track, backward_status) = track(image_list[::-1], forward_track[:,-1,:], remove_bad=False)\n\n    # Prune bad tracks\n    ok_track = np.flatnonzero(forward_status * backward_status) # Only good if good in both\n    forward_first = forward_track[ok_track,0,:]\n    backward_last = backward_track[ok_track,-1,:]\n\n    # Distance\n    retrack_distance = np.sqrt(np.sum((forward_first - backward_last)**2, 1))\n\n    # Allowed\n    retracked_ok = np.flatnonzero(retrack_distance <= max_retrack_distance)\n    final_ok = ok_track[retracked_ok]\n\n    if keep_bad: # Let caller check status\n        status = np.zeros(forward_status.shape)\n        status[final_ok] = 1\n        return (forward_track, status)\n    else: # Remove tracks with faulty retrack\n        return (forward_track[final_ok], forward_status[final_ok])\n"
  },
  {
    "path": "crisp/videoslice.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nVideo slice module\n\"\"\"\n\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2015, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport cv2\nimport numpy as np\n\nfrom . import rotations\nfrom . import tracking\n        \nclass Slice(object):\n    def __init__(self, start, end, points):\n        self.points = points\n        self.start = start\n        self.end = end\n        self.axis = None\n        self.angle = None\n        self.inliers = []\n        \n    def estimate_rotation(self, camera, ransac_threshold=7.0):\n        \"\"\"Estimate the rotation between first and last frame\n\n        It uses RANSAC where the error metric is the reprojection error of the points\n        from the last frame to the first frame.\n\n        Parameters\n        -----------------\n        camera : CameraModel\n            Camera model\n        ransac_threshold : float\n            Distance threshold (in pixels) for a reprojected point to count as an inlier\n        \"\"\"\n        if self.axis is None:\n            x = self.points[:, 0, :].T\n            y = self.points[:, -1, :].T\n            inlier_ratio = 0.5\n            R, t, dist, idx = rotations.estimate_rotation_procrustes_ransac(x, y,\n                                                                     camera, \n                                                                     ransac_threshold,\n                                                                     inlier_ratio=inlier_ratio,\n                                                                     do_translation=False)\n            \n            if R is not None:                                      \n                self.axis, self.angle = rotations.rotation_matrix_to_axis_angle(R)\n                if self.angle < 0: # Constrain to positive angles\n                    self.angle = -self.angle\n                    self.axis = -self.axis\n                self.inliers = idx\n                                                          \n        return self.axis is not None\n\n    @staticmethod\n    def from_stream_randomly(video_stream, step_bounds=(5, 15), length_bounds=(2, 15), max_start=None, min_distance=10, min_slice_points=10):\n        \"\"\"Create slices from a video stream using random sampling\n\n        Parameters\n        -----------------\n        video_stream : VideoStream\n            A video stream\n        step_bounds : tuple\n            Range bounds (inclusive) of possible step lengths\n        length_bounds : tuple\n            Range bounds (inclusive) of possible slice lengths\n        max_start : int\n            Maximum frame number to start from\n        min_distance : float\n            Minimum (initial) distance between tracked points\n        min_slice_points : int\n            Minimum number of points to keep a slice\n\n        Returns\n        -------------------\n        list of Slice\n            List of slices\n        \"\"\"\n        new_step = lambda: int(np.random.uniform(low=step_bounds[0], high=step_bounds[1]))\n        new_length = lambda: int(np.random.uniform(low=length_bounds[0], high=length_bounds[1]))\n        \n        seq_frames = []\n        slices = []\n        seq_start_points = None\n        next_seq_start = new_step() if max_start is None else min(new_step(), max_start)\n        next_seq_length = new_length()\n        for i, im in enumerate(video_stream):            \n            if next_seq_start <= i < next_seq_start + next_seq_length:\n                im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n                seq_frames.append(im)\n                \n                if len(seq_frames) == 1:\n                    max_corners = 400\n                    quality_level = 0.07\n                    seq_start_points = cv2.goodFeaturesToTrack(im, max_corners, quality_level, min_distance)\n                    \n                elif len(seq_frames) == next_seq_length:                               \n                    points, status = tracking.track_retrack(seq_frames, seq_start_points)\n                    if points.shape[0] >= min_slice_points:\n                        s = Slice(next_seq_start, i, points)\n                        slices.append(s)\n                        logger.debug('{0:4d} {1:3d} {2:5d} {3:>5d}-{4:<5d}'.format(len(slices)-1, points.shape[1], points.shape[0], next_seq_start, i))\n                    seq_frames = []\n                    next_seq_start = i + new_step()\n                    next_seq_length = new_length()\n        \n        return slices\n\ndef fill_sampling(slice_list, N):\n    \"\"\"Given a list of slices, draw N samples such that each slice contributes as much as possible\n\n    Parameters\n    --------------------------\n    slice_list : list of Slice\n        List of slices\n    N : int\n        Number of samples to draw\n    \"\"\"\n    A = [len(s.inliers) for s in slice_list]\n    N_max = np.sum(A)\n    if N > N_max:\n        raise ValueError(\"Tried to draw {:d} samples from a pool of only {:d} items\".format(N, N_max))\n    \n    samples_from = np.zeros((len(A),), dtype='int') # Number of samples to draw from each group\n\n    remaining = N\n    while remaining > 0:\n        remaining_groups = np.flatnonzero(samples_from - np.array(A))\n        \n        if remaining < len(remaining_groups):\n            np.random.shuffle(remaining_groups)\n            for g in remaining_groups[:remaining]:\n                samples_from[g] += 1\n        else:\n            # Give each group the allowed number of samples. Constrain to their max size.\n            to_each = max(1, int(remaining / len(remaining_groups)))\n            samples_from = np.min(np.vstack((samples_from + to_each, A)), axis=0)\n        \n        # Update remaining count\n        remaining = int(N - np.sum(samples_from))\n    if not remaining == 0:\n        raise ValueError(\"Still {:d} samples left! This is an error in the selection.\")\n\n    # Construct index list of selected samples\n    samples = []\n    for s, a, n in zip(slice_list, A, samples_from):\n        if a == n:\n            samples.append(np.array(s.inliers)) # all\n        elif a == 0:\n            samples.append(np.arange([]))\n        else:\n            chosen = np.random.choice(s.inliers, n, replace=False)\n            samples.append(np.array(chosen))\n    return samples\n"
  },
  {
    "path": "crisp/znccpyr.py",
    "content": "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\n\"\"\"\nZNCC using Pyramids\n\"\"\"\n\n__author__ = \"Per-Erik Forssén\"\n__copyright__ = \"Copyright 2013, Per-Erik Forssén\"\n__license__ = \"GPL\"\n__email__ = \"perfo@isy.liu.se\"\n\nimport logging\nlogger = logging.getLogger()\n\nimport numpy as np\n\ndef gaussian_kernel(gstd):\n    \"\"\"Generate odd sized truncated Gaussian\n\n    The generated filter kernel has a cutoff at $3\\sigma$\n    and is normalized to sum to 1\n\n    Parameters\n    -------------\n    gstd : float\n            Standard deviation of filter\n\n    Returns\n    -------------\n    g : ndarray\n            Array with kernel coefficients\n    \"\"\"\n    Nc = np.ceil(gstd*3)*2+1\n    x = np.linspace(-(Nc-1)/2,(Nc-1)/2,Nc,endpoint=True)\n    g = np.exp(-.5*((x/gstd)**2))\n    g = g/np.sum(g)\n\n    return g\n\ndef subsample(time_series, downsample_factor):\n    \"\"\"Subsample with Gaussian prefilter\n\n    The prefilter will have the filter size $\\sigma_g=.5*ssfactor$\n\n    Parameters\n    --------------\n    time_series : ndarray\n            Input signal\n    downsample_factor : float\n            Downsampling factor\n       \n    Returns\n    --------------\n       ts_out : ndarray\n            The downsampled signal\n    \"\"\"\n    Ns = np.int(np.floor(np.size(time_series)/downsample_factor))\n    g = gaussian_kernel(0.5*downsample_factor)\n    ts_blur = np.convolve(time_series,g,'same')\n    ts_out = np.zeros((Ns,1), dtype='float64')\n    for k in range(0,Ns):\n        cpos  = (k+.5)*downsample_factor-.5\n        cfrac = cpos-np.floor(cpos)\n        cind  = np.floor(cpos)\n        if cfrac>0:\n            ts_out[k]=ts_blur[cind]*(1-cfrac)+ts_blur[cind+1]*cfrac\n        else:\n            ts_out[k]=ts_blur[cind]\n            \n    return ts_out\n    \ndef upsample(time_series, scaling_factor):\n    \"\"\"Upsample using linear interpolation\n\n    The function uses replication of the value at edges\n\n    Parameters\n    --------------\n    time_series : ndarray\n            Input signal\n    scaling_factor : float\n            The factor to upsample with\n    \n    Returns\n    --------------\n    ts_out  : ndarray\n            The upsampled signal\n    \"\"\"\n    Ns0 = np.size(time_series)\n    Ns  = np.int(np.floor(np.size(time_series)*scaling_factor))\n    ts_out = np.zeros((Ns,1), dtype='float64')\n    for k in range(0,Ns):\n        cpos  = int(np.min([Ns0-1,np.max([0.,(k+0.5)/scaling_factor-0.5])]))\n        cfrac = cpos-np.floor(cpos)\n        cind  = int(np.floor(cpos))\n        #print \"cpos=%f cfrac=%f cind=%d\", (cpos,cfrac,cind)\n        if cfrac>0:\n            ts_out[k]=time_series[cind]*(1-cfrac)+time_series[cind+1]*cfrac\n        else:\n            ts_out[k]=time_series[cind]\n        \n    return ts_out\n\ndef do_binning(time_series,factor):\n    Ns = np.size(time_series) // factor    \n    ts_out = np.zeros((Ns,1), dtype='float64')\n    for k in range(0,Ns):\n        ts_out[k]=0\n        for l in range(0,factor):\n            ts_out[k] += time_series[k*factor+l]\n        ts_out[k] /= factor\n    \n    return ts_out\n\ndef create_pyramid(time_series,octaves):\n    pyr_out = [time_series ]\n    for k in range(0,octaves):\n        pyr_out.append(do_binning(pyr_out[-1],2))\n        \n    return pyr_out\n\ndef zncc(ts1,ts2):\n    \"\"\"Zero mean normalised cross-correlation (ZNCC)\n\n    This function does ZNCC of two signals, ts1 and ts2\n    Normalisation by very small values is avoided by doing\n    max(nmin,nvalue)\n\n    Parameters\n    --------------\n    ts1 : ndarray\n            Input signal 1 to be aligned with\n    ts2 : ndarray\n            Input signal 2\n\n    Returns\n    --------------\n    best_shift : float\n            The best shift of *ts1* to align it with *ts2*\n    ts_out : ndarray\n            The correlation result\n    \"\"\"\n    # Output is the same size as ts1\n    Ns1 = np.size(ts1)\n    Ns2 = np.size(ts2)\n    ts_out = np.zeros((Ns1,1), dtype='float64')\n\n    ishift = int(np.floor(Ns2/2)) # origin of ts2\n\n    t1m = np.mean(ts1)\n    t2m = np.mean(ts2)\n            \n    for k in range(0,Ns1):\n        lstart = np.int(ishift-k)\n        if lstart<0 :\n            lstart=0\n        lend = np.int(ishift-k+Ns2)\n        imax = np.int(np.min([Ns2,Ns1-k+ishift]))\n        if lend>imax :\n            lend=imax\n        csum = 0\n        ts1sum = 0\n        ts1sum2 = 0\n        ts2sum = 0\n        ts2sum2 = 0\n        \n        Nterms = lend-lstart        \n        for l in range(lstart,lend):\n            csum    += ts1[k+l-ishift]*ts2[l]\n            ts1sum  += ts1[k+l-ishift]\n            ts1sum2 += ts1[k+l-ishift]*ts1[k+l-ishift]\n            ts2sum  += ts2[l]\n            ts2sum2 += ts2[l]*ts2[l]\n        ts1sum2 = np.max([t1m*t1m*100,ts1sum2])-ts1sum*ts1sum/Nterms\n        ts2sum2 = np.max([t2m*t2m*100,ts2sum2])-ts2sum*ts2sum/Nterms\n        #ts_out[k]=csum/np.sqrt(ts1sum2*ts2sum2)\n        ts_out[k]=(csum-2.0*ts1sum*ts2sum/Nterms+ts1sum*ts2sum/Nterms/Nterms)/np.sqrt(ts1sum2*ts2sum2)\n    best_shift = np.argmax(ts_out)-ishift\n    return best_shift, ts_out\n\ndef refine_correlation(ts1,ts2,shift_guess):\n    \"\"\"Refine a rough guess of shift by evaluating ZNCC for similar values\n\n    Shifts of *ts1* are tested in the range [-2:2]\n    Refine a rough guess of shift, by trying neighbouring ZNCC values\n    in the range [-2:2]\n\n    Parameters\n    ----------------\n    ts1 : list_like\n            The first timeseries\n    ts2 : list_like\n            The seconds timeseries\n    shift_guess : float\n            The guess to start from\n\n    Returns\n    ---------------\n    best_shift : float\n            The best shift of those tested\n    ts_out : ndarray\n            Computed correlation values\n    \"\"\"    \n    Ns1 = np.size(ts1)\n    Ns2 = np.size(ts2)\n    ts_out = np.zeros((5,1))\n\n    ishift = int(np.floor(Ns2/2)) # origin of ts2\n    k_offset = shift_guess-2+ishift # Try shifts starting with this one\n\n    t1m = np.mean(ts1)\n    t2m = np.mean(ts2)\n\n    for k in range(0,5):\n        km = k+k_offset\n        lstart = np.int(ishift-km)\n        if lstart<0 :\n            lstart=0\n        lend = np.int(ishift-km+Ns2)\n        imax = np.int(np.min([Ns2,Ns1-km+ishift]))\n        if lend>imax :\n            lend=imax\n        csum = 0\n        ts1sum = 0\n        ts1sum2 = 0\n        ts2sum = 0\n        ts2sum2 = 0\n        \n        Nterms = lend-lstart        \n        for l in range(lstart,lend):\n            csum    += ts1[km+l-ishift]*ts2[l]\n            ts1sum  += ts1[km+l-ishift]\n            ts1sum2 += ts1[km+l-ishift]*ts1[km+l-ishift]\n            ts2sum  += ts2[l]\n            ts2sum2 += ts2[l]*ts2[l]\n        ts1sum2 = np.max([t1m*t1m*100,ts1sum2])-ts1sum*ts1sum/Nterms\n        ts2sum2 = np.max([t2m*t2m*100,ts2sum2])-ts2sum*ts2sum/Nterms\n        #ts_out[k]=csum/np.sqrt(ts1sum2*ts2sum2)\n        ts_out[k]=(csum-2.0*ts1sum*ts2sum/Nterms+ts1sum*ts2sum/Nterms/Nterms)/np.sqrt(ts1sum2*ts2sum2)\n\n    best_shift = np.argmax(ts_out)+k_offset-ishift    \n    return best_shift, ts_out    \n\ndef find_shift_pyr(ts1,ts2,nlevels):\n    \"\"\"\n    Find shift that best aligns two time series\n\n    The shift that aligns the timeseries ts1 with ts2.\n    This is sought using zero mean normalized cross correlation (ZNCC) in a coarse to fine search with an octave pyramid on nlevels levels.\n\n    Parameters\n    ----------------\n    ts1 : list_like\n            The first timeseries\n    ts2 : list_like\n            The seconds timeseries\n    nlevels : int\n            Number of levels in pyramid\n\n    Returns\n    ----------------\n       ts1_shift : float\n               How many samples to shift ts1 to align with ts2\n    \"\"\"\n    pyr1 = create_pyramid(ts1,nlevels)\n    pyr2 = create_pyramid(ts2,nlevels)\n    \n    logger.debug(\"pyramid size = %d\" % len(pyr1))\n    logger.debug(\"size of first element %d \" % np.size(pyr1[0]))\n    logger.debug(\"size of last element %d \" % np.size(pyr1[-1]))\n\n    ishift, corrfn = zncc(pyr1[-1],pyr2[-1])\n\n    for k in range(1,nlevels+1):\n        ishift, corrfn = refine_correlation(pyr1[-k-1],pyr2[-k-1],ishift*2)\n\n    return ishift\n"
  },
  {
    "path": "examples/gopro_dataset_example.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import\n\"\"\"\nThis is an example script that shows how to run the calibrator on our dataset.\nThe dataset can be found here:\n\n    http://www.cvl.isy.liu.se/research/datasets/gopro-gyro-dataset/\n\nTo run, simply point the script to one of the video files in the directory\n\n    $ python gopro_gyro_dataset_example.py /path/to/dataset/video.MP4\n\"\"\"\n__author__ = \"Hannes Ovrén\"\n__copyright__ = \"Copyright 2015, Hannes Ovrén\"\n__license__ = \"GPL\"\n__email__ = \"hannes.ovren@liu.se\"\n\nimport os\nimport sys\nimport argparse\n\nimport numpy as np\n\nimport crisp\nfrom crisp.l3g4200d import post_process_L3G4200D_data\nimport crisp.rotations\nfrom crisp.calibration import PARAM_ORDER\n\nCAMERA_MATRIX = np.array(\n    [[ 853.12703455,    0.        ,  988.06311256],\n     [   0.        ,  873.54956631,  525.71056312],\n     [   0.        ,    0.        ,    1.        ]]\n)\nCAMERA_DIST_CENTER = (0.00291108,  0.00041897)\nCAMERA_DIST_PARAM = 0.8894355\nCAMERA_FRAME_RATE = 30.0\nCAMERA_IMAGE_SIZE = (1920, 1080)\nCAMERA_READOUT = 0.0316734\nGYRO_RATE_GUESS = 853.86\n\ndef to_rot_matrix(r):\n    \"Convert combined axis angle vector to rotation matrix\"\n    theta = np.linalg.norm(r)\n    v = r/theta\n    R = crisp.rotations.axis_angle_to_rotation_matrix(v, theta)\n    return R\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument('video')\n    args = parser.parse_args()\n\n    gyro_file = os.path.splitext(args.video)[0] + '_gyro.csv'\n    reference_file = os.path.splitext(args.video)[0] + '_reference.csv'\n\n    camera = crisp.AtanCameraModel(CAMERA_IMAGE_SIZE, CAMERA_FRAME_RATE, CAMERA_READOUT, CAMERA_MATRIX,\n                                   CAMERA_DIST_CENTER, CAMERA_DIST_PARAM)\n\n    print('Creating video stream from {}'.format(args.video))\n    video = crisp.VideoStream.from_file(camera, args.video)\n\n\n    print('Creating gyro stream from {}'.format(gyro_file))\n    gyro = crisp.GyroStream.from_csv(gyro_file)\n\n    print('Post processing L3G4200D gyroscope data to remove frequency spike noise')\n    gyro.data = post_process_L3G4200D_data(gyro.data.T).T\n\n    print('Creating calibrator')\n    calibrator = crisp.AutoCalibrator(video, gyro)\n\n    print('Estimating time offset and camera to gyroscope rotation. Guessing gyro rate = {:.2f}'.format(GYRO_RATE_GUESS))\n    try:\n        calibrator.initialize(gyro_rate=GYRO_RATE_GUESS)\n    except crisp.InitializationError as e:\n        print('Initialization failed. Reason \"{}\"'.format(e.message))\n        sys.exit(-1)\n\n    print('Running calibration. This can take a few minutes.')\n    try:\n        calibrator.calibrate()\n        calibrator.print_params()\n    except crisp.CalibrationError as e:\n        print('Calibration failed. Reason \"{}\"'.format(e.message))\n        sys.exit(-2)\n\n    # Compare with reference data\n    reference_data = np.loadtxt(reference_file, delimiter=',')\n    reference_data[[2,3,4,5,6,7]] = reference_data[[5,6,7,2,3,4]] # Swap order of bias and rot\n    param_data = np.array([calibrator.parameter[p] for p in PARAM_ORDER])\n    print('\\nCompare with reference data')\n    print()\n    print('{:^15s} {:^12s} {:^12s} {:^12s}'.format('Parameter', 'Reference', 'Optimized', 'Difference'))\n    for param, ref, data in zip(PARAM_ORDER, reference_data, param_data):\n        print(\"{:>15s}  {:E}  {:E}  {:E}\".format(param, ref, data, ref-data))\n\n    R_ref = to_rot_matrix(reference_data[5:])\n    R_data = to_rot_matrix(param_data[5:])\n    dR = np.dot(R_ref.T, R_data)\n    v, theta = crisp.rotations.rotation_matrix_to_axis_angle(dR)\n    print('Reference rotation')\n    print(R_ref)\n    print('Optimized rotation')\n    print(R_data)\n    print(\"Angle difference: {:.4f} degrees\".format(np.rad2deg(theta)))\n"
  },
  {
    "path": "setup.cfg",
    "content": "[[metadata]\ndescription-file = README.md\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function\n\n#from distutils.core import setup\n#from distutils.extension import Extension\n#from setuptools.command.sdist import sdist as _sdist\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext as _build_ext\nimport sys\nimport codecs\n\ntry:\n    import numpy as np\nexcept ImportError:\n    print(\"Please install numpy before building this package\")\n    raise\n\ntry:\n    #from Cython.Distutils import build_ext\n    from Cython.Build import cythonize\n    USE_CYTHON = True\nexcept ImportError:\n    USE_CYTHON = False\n\ntry:\n    from pypandoc import convert\n    read_md = lambda f: convert(f, 'rst')\nexcept ImportError:\n    print(\"warning: pypandoc module not found, could not convert Markdown to RST\")\n    read_md = lambda f: codecs.open(f, encoding='utf-8').read()\n\n# Fast quaternion integration module\nfile_ext = 'pyx' if USE_CYTHON else 'c'\nfastint_sources = [\"crisp/fastintegrate/fastintegrate.{}\".format(file_ext),]\n\next_modules = [Extension(\"crisp.fastintegrate\", fastint_sources, include_dirs=[np.get_include()]),]\n\nif USE_CYTHON:\n    ext_modules = cythonize(ext_modules)\n\nclassifiers = [\n    'Development Status :: 4 - Beta',\n\n    # Indicate who your project is intended for\n    'Intended Audience :: Science/Research',\n    'Topic :: Scientific/Engineering',\n\n    # Pick your license as you wish (should match \"license\" above)\n     'License :: OSI Approved :: GNU General Public License (GPL)',\n\n    # Specify the Python versions you support here. In particular, ensure\n    # that you indicate whether you support Python 2, Python 3 or both.\n    'Programming Language :: Python :: 2.7',\n    'Programming Language :: Python :: 3.4'\n]\n\nkeywords = 'gyroscope gyro camera imu calibration synchronization'\n\nrequires = [ 'numpy',\n             'scipy',\n             'matplotlib'\n]\n\n\nsetup(name='crisp',\n      version='2.2.1',\n      author=\"Hannes Ovrén\",\n      author_email=\"hannes.ovren@liu.se\",\n      url=\"https://github.com/hovren/crisp\",\n      description=\"Camera-to-IMU calibration and synchronization toolkit\",\n      long_description=read_md('README.md'),\n      license=\"GPL\",\n      packages=['crisp'],\n      ext_modules=ext_modules,\n#      cmdclass={'build_ext' : build_ext},\n      classifiers=classifiers,\n      install_requires=requires,\n      requires=requires,\n      keywords=keywords,\n#      cmdclass={'build_ext' : build_ext}\n      )\n"
  }
]