Contents

  1. COPYING
  2. COPYING.LIB
  3. README
  4. colors.txt
  5. include/capture.h
  6. include/cmvision.h
  7. src/capture.cc
  8. src/cmvision.cc
  9. utils/COPYING
  10. utils/HELP.TXT
  11. utils/cmv_thresh/Makefile
  12. utils/cmv_thresh/colors.txt
  13. utils/cmv_thresh/thresh.cc
  14. utils/cmv_thresh/thresh.h
  15. utils/cmv_thresh/win.cc
  16. utils/grab/Makefile
  17. utils/grab/grab.cc
  18. utils/mtest/Makefile
  19. utils/mtest/colors.txt
  20. utils/mtest/mtest.cc
  21. utils/mtest/win.cc
  22. utils/mtest/win.h

COPYING 1/22

[
top][prev][next]
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 19yy  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) 19yy name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

COPYING.LIB 2/22

[
top][prev][next]
		  GNU LESSER GENERAL PUBLIC LICENSE
		       Version 2.1, February 1999

 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.

  This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it.  You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.

  When we speak of free software, we are referring to freedom of use,
not price.  Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.

  To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights.  These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.

  For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you.  You must make sure that they, too, receive or can get the source
code.  If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it.  And you must show them these terms so they know their rights.

  We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.

  To protect each distributor, we want to make it very clear that
there is no warranty for the free library.  Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.

  Finally, software patents pose a constant threat to the existence of
any free program.  We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder.  Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.

  Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License.  This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License.  We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.

  When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library.  The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom.  The Lesser General
Public License permits more lax criteria for linking other code with
the library.

  We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License.  It also provides other free software developers Less
of an advantage over competing non-free programs.  These disadvantages
are the reason we use the ordinary General Public License for many
libraries.  However, the Lesser license provides advantages in certain
special circumstances.

  For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard.  To achieve this, non-free programs must be
allowed to use the library.  A more frequent case is that a free
library does the same job as widely used non-free libraries.  In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.

  In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software.  For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.

  Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.

  The precise terms and conditions for copying, distribution and
modification follow.  Pay close attention to the difference between a
"work based on the library" and a "work that uses the library".  The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.

		  GNU LESSER GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".

  A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.

  The "Library", below, refers to any such software library or work
which has been distributed under these terms.  A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language.  (Hereinafter, translation is
included without limitation in the term "modification".)

  "Source code" for a work means the preferred form of the work for
making modifications to it.  For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.

  Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it).  Whether that is true depends on what the Library does
and what the program that uses the Library does.
  
  1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.

  You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.

  2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) The modified work must itself be a software library.

    b) You must cause the files modified to carry prominent notices
    stating that you changed the files and the date of any change.

    c) You must cause the whole of the work to be licensed at no
    charge to all third parties under the terms of this License.

    d) If a facility in the modified Library refers to a function or a
    table of data to be supplied by an application program that uses
    the facility, other than as an argument passed when the facility
    is invoked, then you must make a good faith effort to ensure that,
    in the event an application does not supply such function or
    table, the facility still operates, and performs whatever part of
    its purpose remains meaningful.

    (For example, a function in a library to compute square roots has
    a purpose that is entirely well-defined independent of the
    application.  Therefore, Subsection 2d requires that any
    application-supplied function or table used by this function must
    be optional: if the application does not supply it, the square
    root function must still compute square roots.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.

In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library.  To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License.  (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.)  Do not make any other change in
these notices.

  Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.

  This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.

  4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.

  If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.

  5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library".  Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.

  However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library".  The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.

  When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library.  The
threshold for this to be true is not precisely defined by law.

  If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work.  (Executables containing this object code plus portions of the
Library will still fall under Section 6.)

  Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.

  6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.

  You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License.  You must supply a copy of this License.  If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License.  Also, you must do one
of these things:

    a) Accompany the work with the complete corresponding
    machine-readable source code for the Library including whatever
    changes were used in the work (which must be distributed under
    Sections 1 and 2 above); and, if the work is an executable linked
    with the Library, with the complete machine-readable "work that
    uses the Library", as object code and/or source code, so that the
    user can modify the Library and then relink to produce a modified
    executable containing the modified Library.  (It is understood
    that the user who changes the contents of definitions files in the
    Library will not necessarily be able to recompile the application
    to use the modified definitions.)

    b) Use a suitable shared library mechanism for linking with the
    Library.  A suitable mechanism is one that (1) uses at run time a
    copy of the library already present on the user's computer system,
    rather than copying library functions into the executable, and (2)
    will operate properly with a modified version of the library, if
    the user installs one, as long as the modified version is
    interface-compatible with the version that the work was made with.

    c) Accompany the work with a written offer, valid for at
    least three years, to give the same user the materials
    specified in Subsection 6a, above, for a charge no more
    than the cost of performing this distribution.

    d) If distribution of the work is made by offering access to copy
    from a designated place, offer equivalent access to copy the above
    specified materials from the same place.

    e) Verify that the user has already received a copy of these
    materials or that you have already sent this user a copy.

  For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it.  However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.

  It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system.  Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.

  7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:

    a) Accompany the combined library with a copy of the same work
    based on the Library, uncombined with any other library
    facilities.  This must be distributed under the terms of the
    Sections above.

    b) Give prominent notice with the combined library of the fact
    that part of it is a work based on the Library, and explaining
    where to find the accompanying uncombined form of the same work.

  8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License.  Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License.  However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.

  9. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Library or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.

  10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.

  11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all.  For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded.  In such case, this License incorporates the limitation as if
written in the body of this License.

  13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number.  If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation.  If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.

  14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission.  For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this.  Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.

			    NO WARRANTY

  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

		     END OF TERMS AND CONDITIONS

           How to Apply These Terms to Your New Libraries

  If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change.  You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).

  To apply these terms, attach the following notices to the library.  It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

    <one line to give the library's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the
  library `Frob' (a library for tweaking knobs) written by James Random Hacker.

  <signature of Ty Coon>, 1 April 1990
  Ty Coon, President of Vice

That's all there is to it!

README 3/22

[
top][prev][next]
================
 PROJECT GOALS
----------------
To create a simple, robust vision system suitable for real time
robotics applications. The system aims to perform global low
level color vision at video rates without the use of special
purpose harware.

================
 STATUS
----------------
This is version 1.2 of the library, with additional enhancements, and
a few more bug fixes since the 1.0-1.1 releases.

The library proper is now under the LGPL, although newer major
versions will fall under the GPL until they mature.  The example
programs still fall under the GPL, since many contributors make this
difficult to change, and the fact they are not necessary for linking
for third party programs using CMVision.

CMVision's performance allows it to track up to 32 colors at
approximately 4,000,000 pixels/sec on a 200MHz machine.  If you try
CMVision and see an improvement in your project, send me the
performance data!

CMVision is the fastest freely available library of its type.

================
  CONTACT INFO
----------------
The project web page:
  www.coral.cs.cmu.edu/cmvision
Contact:
  jbruce<at>cs,cmu,edu

================
  CONTRIBUTORS
----------------
  James Bruce
  Zia Khan
  Petter Reinholdtsen
  Tucker Balch
  Anna Costa
  Manuela Veloso

colors.txt 4/22

[
top][prev][next]
[Colors]
(255,128,  0) 0.000000 Ball
(255,255,  0) 0.000000 Yellow_Team
(  0,  0,255) 0.000000 Blue_Team
(255,255,255) 0.000000 White
(255,  0,255) 0.000000 Marker_1_(Pink)
(160,  0,160) 0.000000 Marker_2_(Purple)

[Thresholds]
( 12:153, 99:127,143:168)
(101:196, 60:115,114:148)
( 64:157,144:164, 85:129)
(105:192, 68:187,120:131)
( 85:190, 82:189,141:269)
( 30: 85,130:145,135:145)

include/capture.h 5/22

[
top][prev][next]
/*=========================================================================
    capture.cc
  -------------------------------------------------------------------------
    Example code for video capture under Video4Linux II
  -------------------------------------------------------------------------
    Copyright 1999, 2000
    Anna Helena Reali Costa, James R. Bruce
    School of Computer Science
    Carnegie Mellon University
  -------------------------------------------------------------------------
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  =========================================================================*/

#ifndef __CAPTURE_H__
#define __CAPTURE_H__

#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <fcntl.h>

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/videodev.h>

#define DEFAULT_VIDEO_DEVICE  "/dev/video"
#define VIDEO_STANDARD        "NTSC"

#ifdef USE_METEOR
#define DEFAULT_VIDEO_FORMAT  V4L2_PIX_FMT_UYVY
#else
#define DEFAULT_VIDEO_FORMAT  V4L2_PIX_FMT_YUYV
#endif

#define DEFAULT_IMAGE_WIDTH   320
#define DEFAULT_IMAGE_HEIGHT  240
// if you get a message like "DQBUF returned error", "DQBUF error: invalid"
// then you need to use a higher value for STREAMBUFS or process frames faster
#define STREAMBUFS            8

class capture{
  struct vimage_t{
    v4l2_buffer vidbuf;
    char *data;
  };

  int vid_fd;                    // video device
  vimage_t vimage[STREAMBUFS];   // buffers for images
  struct v4l2_format fmt;        // video format request

  unsigned char *current; // most recently captured frame
  stamp_t timestamp;      // frame time stamp
  int width,height;       // dimensions of video frame
  struct v4l2_buffer tempbuf;
  bool captured_frame;
public:
  capture() {vid_fd = 0; current=NULL; captured_frame = false;}
  ~capture() {close();}

  bool initialize(char *device,int nwidth,int nheight,int nfmt);
  bool initialize(int nwidth,int nheight)
    {return(initialize(NULL,nwidth,nheight,0));}
  bool initialize()
    {return(initialize(NULL,0,0,0));}

  void close();

  unsigned char *captureFrame(int &index);
  unsigned char *captureFrame();
  void releaseFrame(unsigned char* frame, int index);

  unsigned char *getFrame() {return(current);}
  stamp_t getFrameTime() {return(timestamp);}
  int getWidth() {return(width);}
  int getHeight() {return(height);}
};

#endif // __CAPTURE_H__

include/cmvision.h 6/22

[
top][prev][next]
/*=========================================================================
    CMVision.h
  -------------------------------------------------------------------------
    API definition for the CMVision real time Color Machine Vision library
  -------------------------------------------------------------------------
    Copyright 1999, 2000         #### ### ### ## ## ## #### ##  ###  ##  ##
    James R. Bruce              ##    ####### ## ## ## ##   ## ## ## ######
    School of Computer Science  ##    ## # ## ## ## ##  ### ## ## ## ## ###
    Carnegie Mellon University   #### ##   ##  ###  ## #### ##  ###  ##  ##
  -------------------------------------------------------------------------
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  =========================================================================*/

#ifndef __CMVISION_H__
#define __CMVISION_H__

// uncomment if your compiler supports the "restrict" keyword
// #define restrict __restrict__
#define restrict

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

/*
Ultra-fast intro to processing steps:
 - Color segmentation
   - load / save
   - set new values
   - process frame
 - Connected Regions
   - RLE
   - merge
   - extract blobs
   - separate blobs
   - sort blobs
   - merge blobs
 - Blob merging (not currently in release)
   - merge by area occupied

Options File Format: (RGB merge name)
[Colors]
(00,00,00) 0.95 'Orange'
(00,00,00) 0.00 'Pink'
(00,00,00) 0.00 'Red'
(00,00,00) 0.00 'DarkBlue'
(00,00,00) 0.00 'Blue'

[Thresholds]
(<lo>:<hi>,<lo>:<hi>,<lo>:<hi>)
(<lo>:<hi>,<lo>:<hi>,<lo>:<hi>)
(<lo>:<hi>,<lo>:<hi>,<lo>:<hi>)
*/

#define CMV_COLOR_LEVELS  256
#define CMV_MAX_COLORS     32

// sets tweaked optimal values for image size
#define CMV_DEFAULT_WIDTH  320
#define CMV_DEFAULT_HEIGHT 240

// values may need tweaked, although these seem to work usually
#define CMV_MAX_RUNS     (CMV_DEFAULT_WIDTH * CMV_DEFAULT_HEIGHT) / 4
#define CMV_MAX_REGIONS  CMV_MAX_RUNS / 4
#define CMV_MIN_AREA     4

#define CMV_NONE ((unsigned)(-1))

#ifndef NULL
#define NULL (0)
#endif

struct yuv{
  unsigned char y,u,v;
};

struct yuv422{
  unsigned char y1,u,y2,v;
};

struct uyvy{
  unsigned char u,y1,v,y2;
};

#ifdef USE_METEOR
  typedef struct uyvy image_pixel;
#else
  typedef struct yuv422 image_pixel;
#endif

#ifndef RGB_STRUCT
#define RGB_STRUCT
struct rgb{
  unsigned char red,green,blue;
};
#endif

// Options for level of processing
//   use enable()/disable() to change 
#define CMV_THRESHOLD      0x01
#define CMV_COLOR_AVERAGES 0x02
#define CMV_DUAL_THRESHOLD 0x04
#define CMV_DENSITY_MERGE  0x08

#define CMV_VALID_OPTIONS  0x0F


class CMVision{
public:
  struct region{
    int color;          // id of the color
    int area;           // occupied area in pixels
    int x1,y1,x2,y2;    // bounding box (x1,y1) - (x2,y2)
    float cen_x,cen_y;  // centroid
    yuv average;        // average color (if CMV_COLOR_AVERAGES enabled)

    int sum_x,sum_y,sum_z; // temporaries for centroid and avg color
    // int area_check; // DEBUG ONLY

    region *next;       // next region in list

    // int number; // DEBUG ONLY
  };

  struct rle{
    unsigned color;     // which color(s) this run represents
    int length;         // the length of the run (in pixels)
    int parent;         // run's parent in the connected components tree
  };

  struct color_info{
    rgb color;          // example color (such as used in test output)
    char *name;         // color's meaninful name (e.g. ball, goal)
    double merge;       // merge density threshold
    int expected_num;   // expected number of regions (used for merge)
    int y_low,y_high;   // Y,U,V component thresholds
    int u_low,u_high;
    int v_low,v_high;
  };

  struct point{
    double x,y;
  };

  struct line{
    point a,b;
  };

  struct rectangle{
    int x,y,w,h;
  };

protected:
  unsigned y_class[CMV_COLOR_LEVELS];
  unsigned u_class[CMV_COLOR_LEVELS];
  unsigned v_class[CMV_COLOR_LEVELS];

  region region_table[CMV_MAX_REGIONS];
  region *region_list[CMV_MAX_COLORS];
  int region_count[CMV_MAX_COLORS];

  rle rmap[CMV_MAX_RUNS];

  color_info colors[CMV_MAX_COLORS];
  int width,height;
  unsigned *map;

  unsigned options;

protected:
// Private functions
  void classifyFrame(image_pixel * restrict img,unsigned * restrict map);
  int  encodeRuns(rle * restrict out,unsigned * restrict map);
  void connectComponents(rle * restrict map,int num);
  int  extractRegions(region * restrict reg,rle * restrict rmap,int num);
  void calcAverageColors(region * restrict reg,int num_reg,
                         image_pixel * restrict img,
                         rle * restrict rmap,int num_runs);
  int  separateRegions(region * restrict reg,int num);
  region *sortRegionListByArea(region * restrict list,int passes);
  void sortRegions(int max_area);

  // density based merging support
  int mergeRegions(region *p,int num,double density_thresh);
  int mergeRegions();

  void clear();

public:
  CMVision()  {clear();}
  ~CMVision() {close();}

  bool initialize(int nwidth,int nheight);
  bool loadOptions(char *filename);
  bool saveOptions(char *filename);
  bool enable(unsigned opt);
  bool disable(unsigned opt);
  void close();

  bool testClassify(rgb * restrict out,image_pixel * restrict image);
  bool getThreshold(int color,
         int &y_low,int &y_high,
	 int &u_low,int &u_high,
         int &v_low,int &v_high);
  bool setThreshold(int color,
         int y_low,int y_high,
	 int u_low,int u_high,
         int v_low,int v_high);

  unsigned *getMap()
    {return(map);}

  char *getColorName(int color)
    {return(colors[color].name);}
  rgb getColorVisual(int color)
    {return(colors[color].color);}

  color_info *getColorInfo(int color)
    {return(&colors[color]);}
  void getColorInfo(int color,color_info &info)
    {info = colors[color];}
  void setColorInfo(int color,color_info &info)
    {colors[color] = info;}

  bool processFrame(image_pixel *image);
  bool processFrame(unsigned *map);
  int numRegions(int color_id);
  region *getRegions(int color_id);
};

#endif

src/capture.cc 7/22

[
top][prev][next]
/*=========================================================================
    capture.cc
  -------------------------------------------------------------------------
    Example code for video capture under Video4Linux II
  -------------------------------------------------------------------------
    Copyright 1999, 2000
    Anna Helena Reali Costa, James R. Bruce
    School of Computer Science
    Carnegie Mellon University
  -------------------------------------------------------------------------
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  -------------------------------------------------------------------------
    Revision History:
      2000-02-05:  Ported to work with V4L2 API
      1999-11-23:  Quick C++ port to simplify & wrap in an object (jbruce) 
      1999-05-01:  Initial version (annar)
  =========================================================================*/

#include "capture.h"


//==== Capture Class Implementation =======================================//

void grabSetFps(int fd, int fps)
{
  struct v4l2_streamparm params;

  //printf("called v4l2_set_fps with fps=%d\n",fps);
  params.type = V4L2_BUF_TYPE_CAPTURE;
  ioctl(fd, VIDIOC_G_PARM, &params);
  //printf("time per frame is: %ld\n", params.parm.capture.timeperframe);
  params.parm.capture.capturemode |= V4L2_CAP_TIMEPERFRAME;
  params.parm.capture.timeperframe = 10000000 / fps;
  if (fps == 30)
    params.parm.capture.timeperframe = 333667;
  // printf("time per frame is: %ld\n", params.parm.capture.timeperframe);
  ioctl(fd, VIDIOC_S_PARM, &params);
  
  params.parm.capture.timeperframe = 0;
  ioctl(fd, VIDIOC_G_PARM, &params);
  // printf("time per frame is: %ld\n", params.parm.capture.timeperframe);  
}

bool capture::initialize(char *device,int nwidth,int nheight,int nfmt)
{
  struct v4l2_requestbuffers req;
  int err;
  int i;

  // Set defaults if not given
  if(!device) device = DEFAULT_VIDEO_DEVICE;
  if(!nfmt) nfmt = DEFAULT_VIDEO_FORMAT;
  if(!nwidth || !nheight){
    nwidth  = DEFAULT_IMAGE_WIDTH;
    nheight = DEFAULT_IMAGE_HEIGHT;
  }

  // Open the video device
  vid_fd = open(device, O_RDONLY);
  if(vid_fd == -1){
    printf("Could not open video device [%s]\n",device);
    return(false);
  }

  fmt.type = V4L2_BUF_TYPE_CAPTURE;
  err = ioctl(vid_fd, VIDIOC_G_FMT, &fmt);
  if(err){
    printf("G_FMT returned error %d\n",errno);
    return(false);
  }

  // Set video format
  fmt.fmt.pix.width = nwidth;
  fmt.fmt.pix.height = nheight;
  fmt.fmt.pix.pixelformat = nfmt;

  // Set the capture format
  err = ioctl(vid_fd, VIDIOC_S_FMT, &fmt);
  if(err){
    printf("S_FMT returned error %d\n",errno);
    perror("S_FMT:");
    return(false);
  }

  // grabSetFps(vid_fd, 30);

  // Request mmap-able capture buffers
  req.count = STREAMBUFS;
  req.type  = V4L2_BUF_TYPE_CAPTURE;
  err = ioctl(vid_fd, VIDIOC_REQBUFS, &req);
  if(err < 0 || req.count < 1){
    printf("REQBUFS returned error %d, count %d\n",
	   errno,req.count);
    return(false);
  }

  for(i=0; i<req.count; i++){
    vimage[i].vidbuf.index = i;
    vimage[i].vidbuf.type = V4L2_BUF_TYPE_CAPTURE;
    err = ioctl(vid_fd, VIDIOC_QUERYBUF, &vimage[i].vidbuf);
    if(err < 0){
      printf("QUERYBUF returned error %d\n",errno);
      return(false);
    }

    vimage[i].data = (char*)mmap(0, vimage[i].vidbuf.length, PROT_READ,
			  MAP_SHARED, vid_fd, 
			  vimage[i].vidbuf.offset);
    if((int)vimage[i].data == -1){
      printf("mmap() returned error %d\n", errno);
      return(false);
    }
  }

  for(i=0; i<req.count; i++){
    if((err = ioctl(vid_fd, VIDIOC_QBUF, &vimage[i].vidbuf))){
      printf("1QBUF returned error %d\n",errno);
      perror("QBUF error");
      return(false);
    }
  }

  // Turn on streaming capture
  err = ioctl(vid_fd, VIDIOC_STREAMON, &vimage[0].vidbuf.type);
  if(err){
    printf("STREAMON returned error %d\n",errno);
    return(false);
  }

  width   = nwidth;
  height  = nheight;
  current = NULL;

  return(true);
}

void capture::close()
{
  int i,t;

  if(vid_fd >= 0){
    t = V4L2_BUF_TYPE_CAPTURE;
    ioctl(vid_fd, VIDIOC_STREAMOFF, &t);

    for(i=0; i<STREAMBUFS; i++){
      if(vimage[i].data){
        munmap(vimage[i].data,vimage[i].vidbuf.length);
      }
    }
  }
}


unsigned char *capture::captureFrame(int &index)
{
  //if(captured_frame){
  //  printf("there may be a problem capturing frame w/o releasing previous frame");
  //}
  // struct v4l2_buffer tempbuf;
  int err;

  fd_set          rdset;
  struct timeval  timeout;
  int		  n;
  struct v4l2_buffer tempbuf;

  FD_ZERO(&rdset);
  FD_SET(vid_fd, &rdset);
  timeout.tv_sec = 1;
  timeout.tv_usec = 0;
  n = select(vid_fd + 1, &rdset, NULL, NULL, &timeout);
  err = -1;
  if (n == -1) {
    fprintf(stderr, "select error.\n");
    perror("select msg:");
  }
  else if (n == 0)
    fprintf(stderr, "select timeout\n");
  else if (FD_ISSET(vid_fd, &rdset))
    err = 0;
  if(err) return(NULL);

  // Grab last frame
  do {
    //printf("D");
    tempbuf.type = vimage[0].vidbuf.type;
    err = ioctl(vid_fd, VIDIOC_DQBUF, &tempbuf);
    if(err) {
      printf("4DQBUF returned error %d\n",errno);
      perror("DQBUF error:");
    }
    
    //printf("S");
    FD_ZERO(&rdset);
    FD_SET(vid_fd, &rdset);
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;
    n = select(vid_fd + 1, &rdset, NULL, NULL, &timeout);
    // Uncomment this next line to see how many frames are being skipped.
    // 1=frame skipped, 0=frame used
    //printf("n%d",n);
    if(n==-1) {
      fprintf(stderr, "select error.\n");
      perror("2select msg:");
    }
    else if(n==0)
      break;
    if (!FD_ISSET(vid_fd, &rdset))
      printf("huh\n");
    
    //printf("Q");
    err = ioctl(vid_fd, VIDIOC_QBUF, &tempbuf);
    if(err) {
      printf("3QBUF returned error %d\n",errno);
      perror("QBUF error:");
    }
    
  } while(true);
    

  // Set current to point to captured frame data
  current = (unsigned char *)vimage[tempbuf.index].data;
  timestamp = tempbuf.timestamp;
  index = tempbuf.index;

  // Initiate the next capture
  //tempbuf.index = (++index - 1) % STREAMBUFS;
  //err = ioctl(vid_fd, VIDIOC_QBUF, &tempbuf);
  //if(err) printf("QBUF returned error %d\n",errno);  

  captured_frame = true;
  return(current);
}

void capture::releaseFrame(unsigned char* frame, int index)
{
  int err;
  struct v4l2_buffer tempbuf;
  //if(frame != current){
  //  printf("frame != current, possibly releasing the wrong frame.");
  //}
  captured_frame = false;
  // Initiate the next capture
  tempbuf.type = vimage[0].vidbuf.type;
  tempbuf.index=index;
  //printf("%lx %d\n",tempbuf.type,tempbuf.index);
  err = ioctl(vid_fd, VIDIOC_QBUF, &tempbuf);
  if(err) {
    printf("2QBUF returned error %d\n",errno);
    perror("QBUF error:");
  }
}

struct v4l2_buffer tempbuf;

unsigned char *capture::captureFrame()
{
  // struct v4l2_buffer tempbuf;
  int err;

  fd_set          rdset;
  struct timeval  timeout;
  int		  n;

  FD_ZERO(&rdset);
  FD_SET(vid_fd, &rdset);
  timeout.tv_sec = 1;
  timeout.tv_usec = 0;
  n = select(vid_fd + 1, &rdset, NULL, NULL, &timeout);
  err = -1;
  if (n == -1)
    fprintf(stderr, "select error.\n");
  else if (n == 0)
    fprintf(stderr, "select timeout\n");
  else if (FD_ISSET(vid_fd, &rdset))
    err = 0;
  if(err) return(NULL);

  // Grab last frame
  tempbuf.type = vimage[0].vidbuf.type;
  err = ioctl(vid_fd, VIDIOC_DQBUF, &tempbuf);
  if(err) printf("DQBUF returned error %d\n",errno);

  // Set current to point to captured frame data
  current = (unsigned char *)vimage[tempbuf.index].data;
  timestamp = tempbuf.timestamp;

  // Initiate the next capture
  err = ioctl(vid_fd, VIDIOC_QBUF, &tempbuf);
  if(err) printf("QBUF returned error %d\n",errno);

  return(current);
}

src/cmvision.cc 8/22

[
top][prev][next]
/*=========================================================================
    CMVision.cc
  -------------------------------------------------------------------------
    Implementation of the CMVision real time Color Machine Vision library
  -------------------------------------------------------------------------
    Copyright 1999, 2000         #### ### ### ## ## ## #### ##  ###  ##  ##
    James R. Bruce              ##    ####### ## ## ## ##   ## ## ## ######
    School of Computer Science  ##    ## # ## ## ## ##  ### ## ## ## ## ###
    Carnegie Mellon University   #### ##   ##  ###  ## #### ##  ###  ##  ##
  -------------------------------------------------------------------------
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  -------------------------------------------------------------------------
    Revision History:
      1999-11-18:  Initial release version (JRB)
      2000-05-20:  Added Bugfixes from Peter,
                   fixed bounding box bug (JRB)
      2000-06-04:  Some other minor fixes (JRB)
      2000-07-02:  Added average color and density merging (JRB)
      2000-07-20:  Added dual threshold capability (JRB)
  =========================================================================*/

#include "cmvision.h"

//==== Utility Functions ===========================================//
// These could be coded as macros, but the inline versions seem to
// optimize better, and tend to have cleaner definitions

// sum of integers over range [x,x+w)
inline int range_sum(int x,int w)
{
  return(w*(2*x + w-1) / 2);
}

// returns maximal value of two parameters
template <class num>
inline num max(num a,num b)
{
  return((a > b)? a : b);
}

// returns minimal value of two parameters
template <class num>
inline num min(num a,num b)
{
  return((a < b)? a : b);
}

// returns index of least significant set bit
int log2modp[37] = {
  0, 1, 2,27, 3,24,28, 0, 4,17,25,31,29,12, 0,14, 5, 8,18,
  0,26,23,32,16,30,11,13, 7, 0,22,15,10, 6,21, 9,20,19
};

template <class num>
inline int bottom_bit(num n)
{
  return(log2modp[(n & -n) % 37]);
}

/* Marginally slower naive version of above function
template <class num>
inline num bottom_bit(num n)
{
  int i = 0;
  if(!n) return(0);
  while(!(n&(1<<i))) i++;
  return(i + 1);
}
*/

// returns index of most significant set bit
template <class num>
inline num top_bit(num n)
{
  int i = 1;
  if(!n) return(0);
  while(n>>i) i++;
  return(i);
}


//==== Class Implementation ========================================//

void CMVision::classifyFrame(image_pixel * restrict img,unsigned * restrict map)
// Classifies an image passed in as img, saving bits in the entries
// of map representing which thresholds that pixel satisfies.
{
  int i,m,s;
  int m1,m2;
  image_pixel p;

  unsigned *uclas = u_class; // Ahh, the joys of a compiler that
  unsigned *vclas = v_class; //   has to consider pointer aliasing
  unsigned *yclas = y_class;

  s = width * height;

  if(options & CMV_DUAL_THRESHOLD){
    for(i=0; i<s; i+=2){
      p = img[i/2];
      m = uclas[p.u] & vclas[p.v];
      m1 = m & yclas[p.y1];
      m2 = m & yclas[p.y2];
      map[i + 0] = m1 | (m1 >> 16);
      map[i + 1] = m2 | (m2 >> 16);
    }
  }else{
    for(i=0; i<s; i+=2){
      p = img[i/2];
      m = uclas[p.u] & vclas[p.v];
      map[i + 0] = m & yclas[p.y1];
      map[i + 1] = m & yclas[p.y2];
    }
  }
}

int CMVision::encodeRuns(rle * restrict out,unsigned * restrict map)
// Changes the flat array version of the threshold satisfaction map
// into a run length encoded version, which speeds up later processing
// since we only have to look at the points where values change.
{
  int x,y,j,l;
  unsigned m,save;
  int size;
  unsigned *row;
  rle r;

  size = width * height;

  // initialize terminator restore
  save = map[0];

  j = 0;
  for(y=0; y<height; y++){
    row = &map[y * width];

    // restore previous terminator and store next
    // one in the first pixel on the next row
    row[0] = save;
    save = row[width];
    row[width] = CMV_NONE;

    x = 0;
    while(x < width){
      m = row[x];
      // m = m & (~m + 1); // get last bit
      l = x;
      while(row[x] == m) x++;
      // x += (row[x] == CMV_NONE); //  && (last & m);

      r.color  = m;
      r.length = x - l;
      r.parent = j;
      out[j++] = r;
      if(j >= CMV_MAX_RUNS) return(0);
    }
  }

  return(j);
}

void CMVision::connectComponents(rle * restrict map,int num)
// Connect components using four-connecteness so that the runs each
// identify the global parent of the connected region they are a part
// of.  It does this by scanning adjacent rows and merging where similar
// colors overlap.  Used to be union by rank w/ path compression, but now
// is just uses path compression as the global parent index seems to be
// a simpler fast approximation of rank in practice.
// WARNING: This code is *extremely* complicated and twitchy.  It appears
//   to be a correct implementation, but minor changes can easily cause
//   big problems.  Read the papers on this library and have a good
//   understanding of tree-based union find before you touch it
{
  int x1,x2;
  int l1,l2;
  rle r1,r2;
  int i,p,s,n;

  l1 = l2 = 0;
  x1 = x2 = 0;

  // Lower scan begins on second line, so skip over first
  while(x1 < width){
    x1 += map[l1++].length;
  }
  x1 = 0;

  // Do rest in lock step
  r1 = map[l1];
  r2 = map[l2];
  s = l1;
  while(l1 < num){
    if(r1.color==r2.color && r1.color){
      if((x1>=x2 && x1<x2+r2.length) || (x2>=x1 && x2<x1+r1.length)){
        if(s != l1){
          map[l1].parent = r1.parent = r2.parent;
          s = l1;
        }else{
          // find terminal roots of each path
          n = r1.parent;
          while(n != map[n].parent) n = map[n].parent;
          p = r2.parent;
          while(p != map[p].parent) p = map[p].parent;

          // must use smaller of two to preserve DAGness!
          if(n < p){
            map[p].parent = n;
          }else{
            map[n].parent = p;
          }
        }
      }
    }

    // Move to next point where values may change
    if(x1+r1.length < x2+r2.length){
      x1 += r1.length;
      r1 = map[++l1];
    }else{
      x2 += r2.length;
      r2 = map[++l2];
    }
  }

  // Now we need to compress all parent paths
  for(i=0; i<num; i++){
    p = map[i].parent;
    if(p > i){
      while(p != map[p].parent) p = map[p].parent;
      map[i].parent = p;
    }else{
      map[i].parent = map[p].parent;
    }
  }

  // Ouch, my brain hurts.
}

int CMVision::extractRegions(region * restrict reg,rle * restrict rmap,int num)
// Takes the list of runs and formats them into a region table,
// gathering the various statistics we want along the way.
// num is the number of runs in the rmap array, and the number of
// unique regions in reg[] (< CMV_MAX_REGIONS) is returned.
// Implemented as a single pass over the array of runs.
{
  int x,y,i;
  int b,n,a;
  rle r;
  yuv black = {0,0,0};

  x = y = n = 0;
  for(i=0; i<num; i++){
    r = rmap[i];

    if(r.color){
      if(r.parent == i){
        // Add new region if this run is a root (i.e. self parented)
        rmap[i].parent = b = n;  // renumber to point to region id
        reg[b].color = bottom_bit(r.color) - 1;
        reg[b].area = r.length;
        reg[b].x1 = x;
        reg[b].y1 = y;
        reg[b].x2 = x + r.length;
        reg[b].y2 = y;
        reg[b].sum_x = range_sum(x,r.length);
        reg[b].sum_y = y * r.length;
        reg[b].average = black;
        // reg[b].area_check = 0; // DEBUG ONLY
        n++;
        if(n >= CMV_MAX_REGIONS) return(CMV_MAX_REGIONS);
      }else{
        // Otherwise update region stats incrementally
        b = rmap[r.parent].parent;
        rmap[i].parent = b; // update to point to region id
        reg[b].area += r.length;
        reg[b].x2 = max(x + r.length,reg[b].x2);
        reg[b].x1 = min(x,reg[b].x1);
        reg[b].y2 = y; // last set by lowest run
        reg[b].sum_x += range_sum(x,r.length);
        reg[b].sum_y += y * r.length;
      }
      /* DEBUG
      if(r.color == 1){
        printf("{%d,%d,%d} ",i,rmap[i].parent,b);
      }
      */
    }

    // step to next location
    x = (x + r.length) % width;
    y += (x == 0);
  }

  // printf("\n");

  // calculate centroids from stored temporaries
  for(i=0; i<n; i++){
    a = reg[i].area;
    reg[i].cen_x = (float)reg[i].sum_x / a;
    reg[i].cen_y = (float)reg[i].sum_y / a;
  }

  return(n);
}

void CMVision::calcAverageColors(region * restrict reg,int num_reg,
                                 image_pixel * restrict img,
                                 rle * restrict rmap,int num_runs)
// calculates the average color for each region.
// num is the number of runs in the rmap array, and the number of
// unique regions in reg[] (< CMV_MAX_REGIONS) is returned.
// Implemented as a single pass over the image, and a second pass over
// the regions.
{
  int i,j,x,l;
  image_pixel p;
  rle r;
  int sum_y,sum_u,sum_v;
  int b,xs;

  yuv avg;
  int area;

  // clear out temporaries
  for(i=0; i<num_reg; i++){
    reg[i].sum_x = 0;
    reg[i].sum_y = 0;
    reg[i].sum_z = 0;
  }

  x = 0;

  // printf("FRAME_START\n");

  // sum up color components for each region, by traversing image and runs
  for(i=0; i<num_runs; i++){
    r = rmap[i];
    l = r.length;

    if(!r.color){
      x += l;
    }else{
      xs = x;
      p = img[x / 2];

      if(x & 1){
        sum_y = p.y2;
        sum_u = p.u;
        sum_v = p.v;
        // area = 1;
        x++;
        l--;
      }else{
        sum_y = sum_u = sum_v = 0;
        area = 0;
      }

      for(j=0; j<l/2; j++){
        p = img[x / 2];
        sum_y += p.y1 + p.y2;
        sum_u += 2 * p.u;
        sum_v += 2 * p.v;
        x+=2;
        // area += 2;
      }

      if(l & 1){
        x++;
        p = img[x / 2];
        sum_y += p.y1;
        sum_u += p.u;
        sum_v += p.v;
        // area++;
      }

      // add sums to region
      b = r.parent;
      reg[b].sum_x += sum_y;
      reg[b].sum_y += sum_u;
      reg[b].sum_z += sum_v;
      // reg[b].area_check += area;

      /*
      if((r.color & (1 << reg[b].color)) != (1 << reg[b].color)){
        printf("(%d,%d)",r.color,reg[b].color);
      }

      if(x != xs + r.length){
	printf("Length mismatch %d:%d\n",x,xs + r.length);
      }
      */

      x = xs + r.length;
    }
  }

  // Divide sums by area to calculate average colors
  for(i=0; i<num_reg; i++){
    area = reg[i].area;
    avg.y = reg[i].sum_x / area;
    avg.u = reg[i].sum_y / area;
    avg.v = reg[i].sum_z / area;

    /*
    if(reg[i].area != reg[i].area_check){
      printf("Area Mismatch: %d %d\n",reg[i].area,reg[i].area_check);
    }

    x = (y_class[avg.y] & u_class[avg.u] & v_class[avg.v]);
    j = reg[i].color;
    l = (1 << j);
    if((x & l) != l){
      printf("Error: c=%d a=%d (%d,%d) (%d,%d,%d)\n",
	     reg[i].color,area,
	     (int)reg[i].cen_x,(int)reg[i].cen_y,
             avg.y,avg.u,avg.v);
    }
    */

    reg[i].average = avg;
  }
}

int CMVision::separateRegions(region * restrict reg,int num)
// Splits the various regions in the region table a separate list
// for each color.  The lists are threaded through the table using
// the region's 'next' field.  Returns the maximal area of the
// regions, which we use below to speed up sorting.
{
  region *p;
  int i,l;
  int area,max_area;

  // clear out the region table
  for(i=0; i<CMV_MAX_COLORS; i++){
    region_count[i] = 0;
    region_list[i] = NULL;
  }

  // step over the table, adding successive
  // regions to the front of each list
  max_area = 0;
  for(i=0; i<num; i++){
    p = &reg[i];
    area = p->area;
    if(area >= CMV_MIN_AREA){
      if(area > max_area) max_area = area;
      l = p->color;
      region_count[l]++;
      p->next = region_list[l];
      region_list[l] = p;
    }
  }

  return(max_area);
}

// These are the tweaking values for the radix sort given below
// Feel free to change them, though these values seemed to work well
// in testing.  Don't worry about extra passes to get all 32 bits of
// the area; the implementation only does as many passes as needed to
// touch the most significant set bit (MSB of biggest region's area)
#define CMV_RBITS 6
#define CMV_RADIX (1 << CMV_RBITS)
#define CMV_RMASK (CMV_RADIX-1)

CMVision::region *CMVision::sortRegionListByArea(region * restrict list,int passes)
// Sorts a list of regions by their area field.
// Uses a linked list based radix sort to process the list.
{
  region *tbl[CMV_RADIX],*p,*pn;
  int slot,shift;
  int i,j;

  // Handle trivial cases
  if(!list || !list->next) return(list);

  // Initialize table
  for(j=0; j<CMV_RADIX; j++) tbl[j] = NULL;

  for(i=0; i<passes; i++){
    // split list into buckets
    shift = CMV_RBITS * i;
    p = list;
    while(p){
      pn = p->next;
      slot = ((p->area) >> shift) & CMV_RMASK;
      p->next = tbl[slot];
      tbl[slot] = p;
      p = pn;
    }

    // integrate back into partially ordered list
    list = NULL;
    for(j=0; j<CMV_RADIX; j++){
      p = tbl[j];
      tbl[j] = NULL;  // clear out table for next pass
      while(p){
        pn = p->next;
        p->next = list;
        list = p;
        p = pn;
      }
    }
  }

  return(list);
}

void CMVision::sortRegions(int max_area)
// Sorts entire region table by area, using the above
// function to sort each threaded region list.
{
  int i,p;

  // do minimal number of passes sufficient to touch all set bits
  p = top_bit((max_area + CMV_RBITS-1) / CMV_RBITS);

  // sort each list
  for(i=0; i<CMV_MAX_COLORS; i++){
    region_list[i] = sortRegionListByArea(region_list[i],p);
  }
}

int CMVision::mergeRegions(region *p,int num,double density_thresh)
// Looks through regions and merges pairs of the same color that would
// have a high density after combining them (where density is the area
// in pixels of the region divided by the bounding box area).  This
// implementation sucks, and I promise real spatial data structures in
// the future so n^2 ugliness like this is not necessary.
{
  region *q,*s;
  int l,r,t,b;
  int a;
  int merged;

  double tmp;

  merged = 0;

  while(p && merged<num){
    q = p->next;
    s = p;

    while(q){
      // find union box and get its total area
      l = min(p->x1,q->x1);
      r = max(p->x2,q->x2);
      t = min(p->y1,q->y1);
      b = max(p->y2,q->y2);
      a = (r-l) * (b-t);

      // if density of merged region is still above threshold
      if((double)(p->area + q->area) / a > density_thresh){
	// merge them to create a new region
	a = p->area + q->area;
	p->x1 = l;
	p->x2 = r;
	p->y1 = t;
	p->y2 = b;
	p->cen_x = ((p->cen_x * p->area) + (q->cen_x * q->area)) / a;
	p->cen_y = ((p->cen_y * p->area) + (q->cen_y * q->area)) / a;
	p->area = a;

	// remove q from list (old smaller region)
	q = q->next;
	s->next = q;
	merged++;
      }else{
	s = q;
	q = q->next;
      }
    }
    p = p->next;
  }

  return(merged);
}

int CMVision::mergeRegions()
// Apply merge operation to all regions using the above function.
{
  int i,m;
  int num;

  num = 0;

  for(i=0; i<CMV_MAX_COLORS; i++){
    m = mergeRegions(region_list[i],colors[i].expected_num,colors[i].merge);
    region_count[i] -= m;
    num += m;
  }

  return(num);
}

//==== Interface/Public Functions ==================================//

#define ZERO(x) memset(x,0,sizeof(x))

void CMVision::clear()
{
  ZERO(y_class);
  ZERO(u_class);
  ZERO(v_class);

  ZERO(region_list);
  ZERO(region_count);

  ZERO(colors);

  map = NULL;
}

bool CMVision::initialize(int nwidth,int nheight)
// Initializes library to work with images of specified size
{
  width = nwidth;
  height = nheight;

  if(map) delete(map);

  map = new unsigned[width * height + 1];
  // Need 1 extra element to store terminator value in encodeRuns()

  options = CMV_THRESHOLD;

  return(map != NULL);
}

// sets bits in k in array arr[l..r]
template <class num>
void set_bits(num *arr,int len,int l,int r,num k)
{
  int i;

  l = max(l,0);
  r = min(r+1,len);

  for(i=l; i<r; i++) arr[i] |= k;
}

template <class num>
void clear_bits(num *arr,int len,int l,int r,num k)
{
  int i;

  l = max(l,0);
  r = min(r+1,len);

  k = ~k;
  for(i=l; i<r; i++) arr[i] &= k;
}

#define CMV_STATE_SCAN   0
#define CMV_STATE_COLORS 1
#define CMV_STATE_THRESH 2
#define CMV_MAX_BUF 256

bool CMVision::loadOptions(char *filename)
// Loads in options file specifying color names and representative
// rgb triplets.  Also loads in color class threshold values.
{
  char buf[CMV_MAX_BUF],str[CMV_MAX_BUF];
  FILE *in;
  int state,i,n;

  int r,g,b;
  int exp_num;
  double merge;
  color_info *c;

  int y1,y2,u1,u2,v1,v2;
  unsigned k;

  // Open options file
  in = fopen(filename,"rt");
  if(!in) return(false);

  // Clear out previously set options
  for(i=0; i<CMV_COLOR_LEVELS; i++){
    y_class[i] = u_class[i] = v_class[i] = 0;
  }
  for(i=0; i<CMV_MAX_COLORS; i++){
    if(colors[i].name){
      delete(colors[i].name);
      colors[i].name = NULL;
    }
  }

  // Loop ever lines, processing via a simple parser
  state = 0;
  while(fgets(buf,CMV_MAX_BUF,in)){
    switch(state){
      case CMV_STATE_SCAN:
        n = sscanf(buf,"[%s",str);
        if(n == 1){
          if(!strncasecmp(str,"colors]",CMV_MAX_BUF)){
            state = CMV_STATE_COLORS;
            i = 0;
	  }else if(!strncasecmp(str,"thresholds]",CMV_MAX_BUF)){
	    state = CMV_STATE_THRESH;
            i = 0;
	  }else{
            printf("CMVision: Ignoring unknown option header '%s'.\n",str);
          }
	}
        break;
      case CMV_STATE_COLORS:
        n = sscanf(buf,"(%d,%d,%d) %lf %d %s",&r,&g,&b,&merge,&exp_num,str);
        if(n == 6){
          // printf("(%d,%d,%d) %lf %d '%s'\n",
	  //        r,g,b,merge,exp_num,str); fflush(stdout);
          if(i < CMV_MAX_COLORS){
            c = &colors[i];
            c->color.red   = r;
            c->color.green = g;
            c->color.blue  = b;
            c->name  = strdup(str);
            c->merge = merge;
	    c->expected_num = exp_num;
            i++;
	  }else{
	    printf("CMVision: Too many colors, ignoring '%s'.\n",str);
	  }
	}else if(n == 0){
          state = CMV_STATE_SCAN;
        }
        break;
      case CMV_STATE_THRESH:
        n = sscanf(buf,"(%d:%d,%d:%d,%d:%d)",&y1,&y2,&u1,&u2,&v1,&v2);
        if(n == 6){
          // printf("(%d:%d,%d:%d,%d:%d)\n",y1,y2,u1,u2,v1,v2);
          if(i < CMV_MAX_COLORS){
            c = &colors[i];
            c->y_low = y1;  c->y_high = y2;
            c->u_low = u1;  c->u_high = u2;
            c->v_low = v1;  c->v_high = v2;

            k = (1 << i);
            set_bits(y_class,CMV_COLOR_LEVELS,y1,y2,k);
            set_bits(u_class,CMV_COLOR_LEVELS,u1,u2,k);
            set_bits(v_class,CMV_COLOR_LEVELS,v1,v2,k);
            i++;
	  }else{
	    printf("CMVision: Too many thresholds.\n");
	  }
	}else if(n == 0){
          state = CMV_STATE_SCAN;
        }
        break;
    }
  }

  /*
  for(i=0; i<CMV_COLOR_LEVELS; i++){
    printf("%08X %08X %08X\n",y_class[i],u_class[i],v_class[i]);
  }
  */

  fclose(in);

  return(true);
}

bool CMVision::saveOptions(char *filename)
{
  color_info *c;
  FILE *out;
  int i;

  out = fopen(filename,"wt");
  if(!out) return(false);

  fprintf(out,"[Colors]\n");
  i = 0;
  while(colors[i].name){
    c = &colors[i];
    fprintf(out,"(%3d,%3d,%3d) %6.4lf %d %s\n",
      c->color.red,c->color.green,c->color.blue,
      c->merge,c->expected_num,c->name);
    i++;
  }

  fprintf(out,"\n[Thresholds]\n");
  i = 0;
  while(colors[i].name){
    c = &colors[i];
    fprintf(out,"(%3d:%3d,%3d:%3d,%3d:%3d)\n",
      c->y_low,c->y_high,
      c->u_low,c->u_high,
      c->v_low,c->v_high);
    i++;
  }

  fclose(out);

  return(true);
}

bool CMVision::enable(unsigned opt)
{
  int valid;

  valid = opt & CMV_VALID_OPTIONS;
  options |= valid;

  return(opt == valid);
}

bool CMVision::disable(unsigned opt)
{
  int valid;

  valid = opt & CMV_VALID_OPTIONS;
  options &= ~valid;

  return(opt == valid);
}

void CMVision::close()
{
  if(map) delete(map);
  map = NULL;
}


//==== Vision Testing Functions ====================================//

bool CMVision::testClassify(rgb * restrict out,image_pixel * restrict image)
{
  int i,s;
  rgb black = {0,0,0};

  if(!image || !out) return(false);

  classifyFrame(image,map);

  s = width * height;

  i = 0;
  while(i < s){
    while(i<s && !map[i]){
      out[i] = black;
      i++;
    }
    while(i<s && map[i]){
      out[i] = colors[bottom_bit(map[i])-1].color;
      i++;
    }
  }

  return(true);
}

bool CMVision::getThreshold(int color,
       int &y_low,int &y_high,
       int &u_low,int &u_high,
       int &v_low,int &v_high)
{
  color_info *c;

  if(color<0 || color>=CMV_MAX_COLORS) return(false);

  c = &colors[color];
  y_low = c->y_low;  y_high = c->y_high;
  u_low = c->u_low;  u_high = c->u_high;
  v_low = c->v_low;  v_high = c->v_high;

  return(true);
}

bool CMVision::setThreshold(int color,
       int y_low,int y_high,
       int u_low,int u_high,
       int v_low,int v_high)
{
  color_info *c;
  unsigned k;

  if(color<0 || color>=CMV_MAX_COLORS) return(false);

  c = &colors[color];
  k = 1 << color;

  clear_bits(y_class,CMV_COLOR_LEVELS,c->y_low,c->y_high,k);
  clear_bits(u_class,CMV_COLOR_LEVELS,c->u_low,c->u_high,k);
  clear_bits(v_class,CMV_COLOR_LEVELS,c->v_low,c->v_high,k);

  c->y_low = y_low;  c->y_high = y_high;
  c->u_low = u_low;  c->u_high = u_high;
  c->v_low = v_low;  c->v_high = v_high;

  set_bits(y_class,CMV_COLOR_LEVELS,y_low,y_high,k);
  set_bits(u_class,CMV_COLOR_LEVELS,u_low,u_high,k);
  set_bits(v_class,CMV_COLOR_LEVELS,v_low,v_high,k);

  return(true);
}

//==== Main Vision Functions =======================================//

bool CMVision::processFrame(image_pixel *image)
{
  int runs;
  int regions;
  int max_area;

  if(!image) return(false);

  if(options & CMV_THRESHOLD){

    classifyFrame(image,map);
    runs = encodeRuns(rmap,map);
    connectComponents(rmap,runs);

    regions = extractRegions(region_table,rmap,runs);

    if(options & CMV_COLOR_AVERAGES){
      calcAverageColors(region_table,regions,image,rmap,runs);
    }

    max_area = separateRegions(region_table,regions);
    sortRegions(max_area);

    if(options & CMV_DENSITY_MERGE){
      mergeRegions();
    }
  }

  return(true);
}

bool CMVision::processFrame(unsigned *map)
{
  int runs;
  int regions;
  int max_area;

  if(!map) return(false);

  runs = encodeRuns(rmap,map);
  connectComponents(rmap,runs);

  regions = extractRegions(region_table,rmap,runs);

  // if(options & CMV_COLOR_AVERAGES){
  //   calcAverageColors(region_table,regions,image,rmap,runs);
  // }

  max_area = separateRegions(region_table,regions);
  sortRegions(max_area);

  if(options & CMV_DENSITY_MERGE){
    mergeRegions();
  }

  return(true);
}

int CMVision::numRegions(int color_id)
{
  if(color_id<0 || color_id>=CMV_MAX_COLORS) return(CMV_NONE);
  return(region_count[color_id]);
}

CMVision::region *CMVision::getRegions(int color_id)
{
  if(color_id<0 || color_id>=CMV_MAX_COLORS) return(NULL);
  return(region_list[color_id]);
}

utils/COPYING 9/22

[
top][prev][next]
All these examples fall under the GPL unless otherwise specified.

See the parent of this directory for details.

utils/HELP.TXT 10/22

[
top][prev][next]
Got any examples to contribute?
Donate it and we will put it here!

utils/cmv_thresh/Makefile 11/22

[
top][prev][next]
# location of CMVision
CMVDIR = ../..

# libraries to use
GTKLIBS  = `gtk-config --libs`
GTKINC   = `gtk-config --cflags`

LIB = -L/usr/lib $(GTKLIBS) -lm -lpthread
INCLUDE = $(GTKINC) -I$(CMVDIR)/include

# compiler and settings to use
CC = g++
CFLAGS = -O3 $(INCLUDE) -DUSE_METEOR
# -g -pg -O2 -ffast-math 

# project settings
TARGET = thresh

SOURCES = $(wildcard *.cc) $(wildcard $(CMVDIR)/src/*.cc)
OBJ = $(SOURCES:%.cc=%.o)

# rules and other cruft
all: $(TARGET)

dep: depend

.SUFFIXES: .cc
%.o: %.cc
	$(CC) $(CFLAGS) -c $< -o $@

$(TARGET): $(OBJ)
	$(CC) $(CFLAGS) -o $@ $(OBJ) $(LIB) $(INCLUDE)

clean:
	-rm -rf core *.o *~ "#"*"#" $(CMVDIR)/src/*.o Makefile.bak

depend:
	makedepend -fMakefile $(INCLUDE) $(SOURCES)

# autogenerated dependencies:

utils/cmv_thresh/colors.txt 12/22

[
top][prev][next]
[Colors]
(255,128,  0) 0.0000 0 Ball
(255,255,  0) 0.0000 0 Yellow_Team
(  0,  0,255) 0.0000 0 Blue_Team
(255,255,255) 0.0000 0 White
(255,  0,255) 0.0000 0 Marker_Pink
(160,  0,160) 0.0000 0 Marker_Purple
(  0,160,  0) 0.0000 0 Marker_Green
(  0,  0,  0) 0.0000 0 C08
(  0,  0,  0) 0.0000 0 C09
(  0,  0,  0) 0.0000 0 C10
(  0,  0,  0) 0.0000 0 C11
(  0,  0,  0) 0.0000 0 C12
(  0,  0,  0) 0.0000 0 C13
(  0,  0,  0) 0.0000 0 C14
(  0,  0,  0) 0.0000 0 C15
(  0,  0,  0) 0.0000 0 C16
(255,128,  0) 0.0000 0 Ball_2
(255,255,  0) 0.0000 0 Yellow_Team_2
(  0,  0,255) 0.0000 0 Blue_Team_2
(255,255,255) 0.0000 0 White_2
(255,  0,255) 0.0000 0 Marker_Pink_2
(160,  0,160) 0.0000 0 Marker_Purple_2
(  0,160,  0) 0.0000 0 Marker_Green_2

[Thresholds]
( 32:168, 71:135,164:228)
( 71:246, 30:107,136:168)
( 76:122,205:221, 67:128)
(172:255,104:169, 93:156)
( 64:172,133:181,153:206)
(103: 96,118:140,144:166)
( 12:145, 89:157, 85:119)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
( 86:221, 35: 79,102:150)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)

utils/cmv_thresh/thresh.cc 13/22

[
top][prev][next]
#include "thresh.h"

inline int min(int a,int b)
{
  return((a < b)? a : b);
}

inline int max(int a,int b)
{
  return((a > b)? a : b);
}

int bound(int low,int high,int n)
{
  if(n < low ) n = low;
  if(n > high) n = high;
  return(n);
}

/*====================================================================
    Main program
  ====================================================================*/

windows win;
appstate app;
bool capture_frame;
bool captured_image = false;
bool white_background; 
extern bool button_press;
extern int mouse_x;
extern int mouse_y;

typedef void*(*pthread_start_routine)(void *);
bool run_frame_daemon;

class capture cap;
class CMVision vision;
int frame = 0;
int uframe = 0;

int permute[HIST_SIZE];
int rx,ry;
image_pixel *c_img;

void vision_draw_crosshairs(int color, int val);

rgb yuv_to_rgb(int y,int u,int v)
{
  rgb c;

  u = 2*u - 256;
  v = 2*v - 256;

  c.red   = bound(0,255,y + v);
  c.green = bound(0,255,(int)(y - 0.51*v - 0.19*u));
  c.blue  = bound(0,255,y + u);
  //c.alpha = 0;

  return(c);
}

#define SET_HIST_X(A,I,J,Y,U,V) \
  A[(I)*256 + (J)] = A[(I)*256 + (J) + 1] = yuv_to_rgb(Y,U,V)
#define SET_HIST_Y(A,I,J,Y,U,V) \
  A[(I)*256 + (J)] = A[((I)+1)*256 + (J)] = yuv_to_rgb(Y,U,V)

void init_histograms()
{
  int i,t,r;

  /*memset(app.uv_hist,0,HIST_SIZE*HIST_SIZE*4);
  memset(app.uy_hist,0,HIST_SIZE*HIST_SIZE*4);
  memset(app.yv_hist,0,HIST_SIZE*HIST_SIZE*4);*/

  memset(app.uv_hist,0,HIST_SIZE*HIST_SIZE*3); // set background color of histograms here
  memset(app.uy_hist,0,HIST_SIZE*HIST_SIZE*3); 
  memset(app.yv_hist,0,HIST_SIZE*HIST_SIZE*3);

  for(i=1; i<HIST_SIZE-1; i++){
    SET_HIST_Y(app.uv_hist, 1,i, 128,0,i);
    SET_HIST_X(app.uv_hist, i,1, 128,i,0);
    SET_HIST_Y(app.uv_hist, 253,i, 128,255,i);
    SET_HIST_X(app.uv_hist, i,253, 128,i,255);

    SET_HIST_Y(app.uy_hist, 1,i, i,0,128);
    SET_HIST_X(app.uy_hist, i,1, 0,i,128);
    SET_HIST_Y(app.uy_hist, 253,i, i,255,128);
    SET_HIST_X(app.uy_hist, i,253, 255,i,128);

    SET_HIST_Y(app.yv_hist, 1,i, 0,128,i);
    SET_HIST_X(app.yv_hist, i,1, i,128,0);
    SET_HIST_Y(app.yv_hist, 253,i, 255,128,i);
    SET_HIST_X(app.yv_hist, i,253, i,128,255);
  }

  // Generate randomly ordered index array
  for(i=0; i<HIST_SIZE-6; i++) permute[i] = i;

  for(i=0; i<HIST_SIZE-7; i++){
    r = rand() % (HIST_SIZE - 6 - i);
    t = permute[r];
    permute[r] = permute[i];
    permute[i] = t;
  }
}

void add_to_hist(image_pixel *src,int w,int h)
{
  int i,j;
  int l,x  ;
  int y,u,v;
  rgb c;
  image_pixel p;

  //c.alpha = 0;

  for(i=0; i<w*h/2; i++){
    p = src[i];

    y = (p.y1 + p.y2) / 2;
    v = 2*p.u - 256;
    u = 2*p.v - 256;

    c.red   = bound(0,255,y + u);
    c.green = bound(0,255,(int)(y - 0.51*u - 0.19*v));
    c.blue  = bound(0,255,y + v);
    // c.alpha = 0;

    app.uv_hist[256*p.u + p.v] = c;
    app.uy_hist[256*p.u +   y] = c;
    app.yv_hist[256*  y + p.v] = c;
  }

  // set background pixels here
  if(white_background) // make background white if user requests it
    c.red = c.green = c.blue = 255;
  else
    c.red = c.green = c.blue = 0;

  // erase a pseudo-random set of pixels.
  for(i=0; i<4; i++){
    for(j=0; j<HIST_SIZE-6; j++){
      rx = (rx + 1) % (HIST_SIZE - 6);
      ry = (ry + HIST_SIZE - 7) % (HIST_SIZE - 6);

      x = permute[rx] + 3;
      y = permute[ry] + 3;

      l = y*HIST_SIZE + x;
      app.uv_hist[l] = c;
      app.uy_hist[l] = c;
      app.yv_hist[l] = c;
    }
    ry++; // skip to next row sequence
  }

  // prevent threshold boxes from erasure
  if(white_background){
    vision_draw_thresholds(app.color,0);
  }else{
    vision_draw_thresholds(app.color,255);
  }
}

void draw_hist_rect(rgb *img,int x1,int y1,int x2,int y2,rgb c)
{
  int x,y;

  x1 = bound(4,HIST_SIZE-4,x1);
  y1 = bound(4,HIST_SIZE-4,y1);
  x2 = bound(4,HIST_SIZE-4,x2);
  y2 = bound(4,HIST_SIZE-4,y2);

  for(x=x1; x<x2; x++){
    img[HIST_SIZE*y1 + x] = c;
    img[HIST_SIZE*y2 + x] = c;
  }

  for(y=y1; y<y2; y++){
    img[HIST_SIZE*y + x1] = c;
    img[HIST_SIZE*y + x2] = c;
  }
}

rgb yuv_to_rgb(image_pixel p)
{
  int y,u,v;
  rgb c;

  y = (p.y1 + p.y2) / 2;
  v = 2*p.u - 256;
  u = 2*p.v - 256;

  c.red   = bound(0,255,y + u);
  c.green = bound(0,255,(int)(y - 0.51*u - 0.19*v));
  c.blue  = bound(0,255,y + v);

  return(c);
}


unsigned int matrix_coefficients = 6;
const signed int Inverse_Table_6_9[8][4] =
{
    {117504, 138453, 13954, 34903}, /* no sequence_display_extension */
    {117504, 138453, 13954, 34903}, /* ITU-R Rec. 709 (1990) */
    {104597, 132201, 25675, 53279}, /* unspecified */
    {104597, 132201, 25675, 53279}, /* reserved */
    {104448, 132798, 24759, 53109}, /* FCC */
    {104597, 132201, 25675, 53279}, /* ITU-R Rec. 624-4 System B, G */
    {104597, 132201, 25675, 53279}, /* SMPTE 170M */
    {117579, 136230, 16907, 35559}  /* SMPTE 240M (1987) */
};


unsigned char * table_rV[256];
unsigned char * table_gU[256];
int table_gV[256];
unsigned char * table_bU[256];

static int div_round (int dividend, int divisor){
  if (dividend > 0)
    return (dividend + (divisor>>1)) / divisor;
  else
    return -((-dividend + (divisor>>1)) / divisor);
}

static void yuv_to_rgb_init()
{
  int i;
  unsigned char table_Y[1024];
  unsigned char  *table_8 = 0;
  unsigned int entry_size = 0;
  unsigned char  *table_r = 0, *table_g = 0, *table_b = 0;

  int crv = Inverse_Table_6_9[matrix_coefficients][0];
  int cbu = Inverse_Table_6_9[matrix_coefficients][1];
  int cgu = -Inverse_Table_6_9[matrix_coefficients][2];
  int cgv = -Inverse_Table_6_9[matrix_coefficients][3];

  for (i = 0; i < 1024; i++){
    int j;
    j = (76309 * (i - 384 - 16) + 32768) >> 16;
    j = (j < 0) ? 0 : ((j > 255) ? 255 : j);
    table_Y[i] = j;
  }

  table_8 = (unsigned char*) malloc ((256 + 2*232) * sizeof (unsigned char));

  entry_size = sizeof (unsigned char);
  table_r = table_g = table_b = table_8 + 232;

  for (i = -232; i < 256+232; i++)
    ((unsigned char * )table_b)[i] = table_Y[i+384];

  for (i = 0; i < 256; i++){
    table_rV[i] = table_r + entry_size * div_round (crv * (i-128), 76309);
    table_gU[i] = table_g + entry_size * div_round (cgu * (i-128), 76309);
    table_gV[i] = entry_size * div_round (cgv * (i-128), 76309);
    table_bU[i] = table_b + entry_size * div_round (cbu * (i-128), 76309);
  }
}


void yuv_to_rgb(rgb *dest , image_pixel *src, int w,int h)
{
  int i,s;
  int U, V, Y;
  image_pixel p;
  rgb c;
  unsigned char * r, * g, * b;
  s = w * h;
  for(i=0; i<s; i++){
    p = src[i / 2];

    U = p.u;				
    V = p.v;

    r = table_rV[V];
    g = table_gU[U] + table_gV[V];
    b = table_bU[U];

    Y = p.y1;
    c.red = r[Y];
    c.green = g[Y];
    c.blue = b[Y];
    dest[i] = c;

    Y = p.y2;
    c.red = r[Y];
    c.green = g[Y];
    c.blue = b[Y];
    dest[i+1] = c;
  }
}


void frame_daemon(void *data)
{
  while(run_frame_daemon){
    if(capture_frame){
      c_img = (image_pixel*)cap.captureFrame();
      captured_image = true;
      frame++;
    }

    if(app.show_hist /* && sem_trywait(&app.hist_lock)!=EAGAIN*/){
    	sem_wait(&app.hist_lock);
      add_to_hist(c_img,VIEW_WIDTH,VIEW_HEIGHT);
  		sem_post(&app.hist_lock);
    }

    yuv_to_rgb((rgb*)app.video_buf,c_img,VIEW_WIDTH,VIEW_HEIGHT);
    vision.testClassify((rgb*)app.output_buf,c_img);

    //memcpy(app.video_buf,img,320*240*4);

    /*
    printf(".");
    if(frame%30 == 0) printf("\n");
    fflush(stdout);
    */

    // update_windows(win);
  }
}

int update_daemon(void *data)
{
  uframe++;
  update_windows(win,uframe);
  return(run_frame_daemon);
}

bool vision_load(char *filename)
{
  return(vision.loadOptions(filename));
}

bool vision_save(char *filename)
{
  return(vision.saveOptions(filename));
}

#define THRESH_VAL(T) \
  (int)(GTK_ADJUSTMENT(win.control.T.adj)->value)
#define THRESH_SLIDER(T) \
  gtk_adjustment_set_value(GTK_ADJUSTMENT(win.control.T.adj),T)


void vision_draw_thresholds(int color,int val)
{
  rgb c;

  int y_min,y_max;
  int u_min,u_max;
  int v_min,v_max;

  vision.getThreshold(app.color,
    y_min,y_max,
    u_min,u_max,
    v_min,v_max);

  c.red = c.green = c.blue = val; //c.alpha = val;
  draw_hist_rect(app.uv_hist,v_min,u_min,v_max,u_max,c);
  draw_hist_rect(app.uy_hist,y_min,u_min,y_max,u_max,c);
  draw_hist_rect(app.yv_hist,v_min,y_min,v_max,y_max,c);
}

void vision_set_thresholds(int color)
{
  int y_min,y_max;
  int u_min,u_max;
  int v_min,v_max;

  // erase old thresholds
  if(white_background){
    vision_draw_thresholds(app.color,255);
  }else{
    vision_draw_thresholds(app.color,0);
  }

  // set new thresholds
  y_min = THRESH_VAL(y_min); y_max = THRESH_VAL(y_max);
  u_min = THRESH_VAL(u_min); u_max = THRESH_VAL(u_max);
  v_min = THRESH_VAL(v_min); v_max = THRESH_VAL(v_max);

  vision.setThreshold(color,
    y_min,y_max,
    u_min,u_max,
    v_min,v_max);

  // draw new thresholds
  if(white_background){
    vision_draw_thresholds(color,0);
  }else{
    vision_draw_thresholds(color,255);
  }
}

void vision_get_thresholds(int color)
{
  int y_min,y_max;
  int u_min,u_max;
  int v_min,v_max;

  vision.getThreshold(app.color,
    y_min,y_max,
    u_min,u_max,
    v_min,v_max);

  THRESH_SLIDER(y_min);  THRESH_SLIDER(y_max);
  THRESH_SLIDER(u_min);  THRESH_SLIDER(u_max);
  THRESH_SLIDER(v_min);  THRESH_SLIDER(v_max);

  // draw new thresholds
  if(white_background)
    vision_draw_thresholds(app.color,0);
  else
    vision_draw_thresholds(app.color,255);

}

char *vision_color_name(int color)
{
  return(vision.getColorName(color));
}

int main(int argc,char **argv)
{
  pthread_t thr;
  guint timer;

  app.video_buf = new unsigned char[VIEW_WIDTH * VIEW_HEIGHT * 4];
  app.output_buf = new unsigned char[VIEW_WIDTH * VIEW_HEIGHT * 4];

  app.uv_hist = new rgb[256 * 256];
  app.uy_hist = new rgb[256 * 256];
  app.yv_hist = new rgb[256 * 256];

  app.cross_x = 5;
  app.cross_y = 5;
  strcpy(app.filename,"colors.txt");

  // initialize capture
  if(!cap.initialize("/dev/video",VIEW_WIDTH,VIEW_HEIGHT,
		     DEFAULT_VIDEO_FORMAT)){
    printf("Capture initialization failed!\n");
    exit(1);
  }
  if(!vision.initialize(VIEW_WIDTH,VIEW_HEIGHT)
     || !vision.loadOptions(app.filename)){
    printf("Vision initialization failed!\n");
    exit(2);
  }

  init_histograms();

  // initialize gtk
  //g_thread_init(NULL);

  gtk_init(&argc,&argv);
  gdk_rgb_init();
  create_windows(win);

  // initialize partial look yuv to rgb routine
  yuv_to_rgb_init();

  // spawn refresh thread
  run_frame_daemon = true;
  capture_frame = true;
  sem_init(&app.hist_lock,0,1);
  pthread_create(&thr,NULL,(pthread_start_routine)frame_daemon,NULL);
  timer = gtk_timeout_add(1000/5,(GtkFunction)update_daemon,NULL);

  // black threshold background by default
  white_background = false;
  app.show_hist = true;

  // Main Function
  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  // shutwown
  run_frame_daemon = false;
  pthread_join(thr,NULL);
  sem_destroy(&app.hist_lock);

  cap.close();
  vision.close();

  return(0);
}

utils/cmv_thresh/thresh.h 14/22

[
top][prev][next]
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

#include <math.h>
#include <string.h>

#include <gtk/gtk.h>

// CMVision headers
#include <capture.h>
#include <cmvision.h>



/*====================================================================
    Windowing definitions
  ====================================================================*/

#define VIEW_WIDTH  640
#define VIEW_HEIGHT 480

#define HIST_SIZE 256

struct file_window{
  GtkWidget *file_selector;
};

struct slider{
  GtkWidget *label;
  GtkWidget *scale;
  GtkObject *adj;
};

struct control_window{
  GtkWidget *window;
  GtkWidget *vbox;
  GtkWidget *table;
  // GtkWidget *hbox;

  GtkWidget *toolbar;
  GtkWidget *new_button;
  GtkWidget *open_button;
  GtkWidget *reload_button;
  GtkWidget *save_button;
  GtkWidget *saveas_button;

  GtkWidget *color;
  GtkWidget *color_menu;

  slider y_min,y_max;
  slider u_min,u_max;
  slider v_min,v_max;
};

struct vid_window{
  bool can_update;

  GtkWidget *window;

  //GtkWidget *vbox;
  GtkWidget *video;
};

struct output_window{
  bool can_update;
  GtkWidget *window;
  GtkWidget *output; // drawing area
};

struct hist_window{
  bool can_update;

  GtkWidget *window;

  GtkWidget *table;
  GtkWidget *uv_hist;
  GtkWidget *uy_hist;
  GtkWidget *yv_hist;
};

struct windows{
  struct file_window    file;
  struct control_window control;
  struct vid_window     video;
  struct hist_window    hist;
  struct output_window  output;
};

void create_windows(windows &w);
void destroy_windows(windows &w);

/*====================================================================
    File IO definitions
  ====================================================================*/

// bool save_screen(char *filename);

/*====================================================================
    Global data definitions
  ====================================================================*/

#define FILE_MODE_OPEN 1
#define FILE_MODE_SAVE 2

struct appstate{
  int file_mode;
  char filename[256];

  int color;

  unsigned char *video_buf;
  unsigned char *output_buf;

  sem_t hist_lock;
  rgb *uv_hist,*uy_hist,*yv_hist;

  int frame;

  int cross_x;
  int cross_y;

  int framerate;
  bool show_hist;
};

/*====================================================================
    Main functions
  ====================================================================*/

void update_windows(windows &w,int frame);
bool vision_load(char *filename);
bool vision_save(char *filename);
void vision_set_thresholds(int color);
void vision_get_thresholds(int color);
char *vision_color_name(int color);
void vision_draw_thresholds(int color,int val);

utils/cmv_thresh/win.cc 15/22

[
top][prev][next]
#include "thresh.h"

extern appstate app;
extern windows win;
extern bool capture_frame;
extern bool white_background;
extern image_pixel *c_img;
extern bool captured_image;
bool crosshair_mode = false;

int mouse_x = 0;
int mouse_y = 0;
bool button_press = false;

void destroy_windows(windows &w);

void delete_event()
{
  destroy_windows(win);

  gtk_main_quit();
}

//==== File Selection Dialog =========================================//

void file_done(GtkWidget *selector,gpointer data)
{
  // call load_spline_file() / save_current_view()
  char *s;

  s = gtk_file_selection_get_filename(GTK_FILE_SELECTION(selector));
  strncpy(app.filename,s,256);
  printf("Got filename:[%s]\n",app.filename);

  gtk_widget_hide(selector);

  switch(app.file_mode){
    case FILE_MODE_OPEN:
      vision_load(app.filename);
      break;
    case FILE_MODE_SAVE:
      vision_save(app.filename);
      break;
  }
}

void file_cancel(GtkWidget *selector,gpointer data)
{
  gtk_widget_destroy(selector);
}

/*
void file_show(GtkWidget *selector)
{
  gtk_widget_show(selector);
}
*/

void create_file_window(file_window &w,char *label)
{    
  w.file_selector = gtk_file_selection_new(label);

  gtk_signal_connect_object(GTK_OBJECT(GTK_FILE_SELECTION(w.file_selector)->
				       ok_button),
			    "clicked", GTK_SIGNAL_FUNC(file_done),
			    GTK_OBJECT(w.file_selector));
  gtk_signal_connect_object(GTK_OBJECT(GTK_FILE_SELECTION(w.file_selector)->
				       cancel_button),
			    "clicked", GTK_SIGNAL_FUNC(file_cancel),
			    GTK_OBJECT(w.file_selector));

  gtk_widget_show(w.file_selector);
}

//==== Toolbar Events ================================================//

// quit aplication
void toolbar_crosshair_event(GtkWidget *widget, gpointer data)
{
  // switch crosshair mode on and off
  printf("crosshair mode event\n");

  crosshair_mode = !crosshair_mode;
}

void toolbar_quit_event(GtkWidget *widget, gpointer data){
  printf("quit event\n");
  destroy_windows(win);
  gtk_main_quit();  
}

void toolbar_background_event(GtkWidget *widget, gpointer data){
  printf("toggle background event\n");
  if(white_background){
    // set background color of histograms here
    memset(app.uv_hist,0,HIST_SIZE*HIST_SIZE*3);
    memset(app.uy_hist,0,HIST_SIZE*HIST_SIZE*3);
    memset(app.yv_hist,0,HIST_SIZE*HIST_SIZE*3);
    white_background = false;
  }else{
    // set background color of histograms here
    memset(app.uv_hist,255,HIST_SIZE*HIST_SIZE*3); 
    memset(app.uy_hist,255,HIST_SIZE*HIST_SIZE*3);
    memset(app.yv_hist,255,HIST_SIZE*HIST_SIZE*3);
    white_background = true;
  }
}

void toolbar_pause_event(GtkWidget *widget, gpointer data)
{
  printf("pause event\n");
  if(capture_frame){
    capture_frame = false;
  }else{
    capture_frame = true;
  }
}

void toolbar_new_event(GtkWidget *widget,gpointer data)
{
  printf("new event.\n");
  // clear_image();
}

void toolbar_open_event(GtkWidget *widget,gpointer data)
{
  printf("open event.\n");
  app.file_mode = FILE_MODE_OPEN;
  create_file_window(win.file,"Choose a threshold file to open.");
}

void toolbar_reload_event(GtkWidget *widget,gpointer data)
{
  printf("reload event.\n");
  vision_load(app.filename);
}

void toolbar_save_event(GtkWidget *widget,gpointer data)
{
  printf("save event.\n");
  vision_save(app.filename);
}

void toolbar_saveas_event(GtkWidget *widget,gpointer data)
{
  printf("saveas event.\n");
  app.file_mode = FILE_MODE_SAVE;
  create_file_window(win.file,"Choose a file to save thresholds.");
}

//==== Control Window ================================================//

void control_thresh_set_event(GtkWidget *widget,GtkAdjustment *adj)
{
  //printf("set threhold %d.\n",(int)(adj->value));
  vision_set_thresholds(app.color);

  //update_view();
}

void control_select_color_event(GtkWidget *widget,int id)
{
  char *str;
  int i;

  if(id<0 || id>=CMV_MAX_COLORS) return;

  /*
  if(!str) return;

  i = 0;
  while(i<32 && strcmp(str,vision_color_name(i))) i++;
  if(i >= 32) return;
  */

  str = vision_color_name(id);
  printf("set color [%s]:%d.\n",str,id);

  vision_draw_thresholds(app.color,0);
  app.color = id;
  vision_get_thresholds(i);
}

void control_add_hseparator(GtkWidget *table,int &y)
{
  GtkWidget *sep;

  sep = gtk_hseparator_new();

  GtkAttachOptions opfe = (GtkAttachOptions)(GTK_FILL|GTK_EXPAND);
  int pad = 4;
  gtk_table_attach(GTK_TABLE(table),sep,0,2,y,y+1,opfe,opfe,pad,pad);
  y++;

  gtk_widget_show(sep);
}

void control_add_hslider(GtkWidget *table,int &y,slider &s,char *label,double val)
{
  // create widgets
  s.label = gtk_label_new(label);
  s.adj   = gtk_adjustment_new(val,0,256,1,16,1);
  s.scale = gtk_hscale_new(GTK_ADJUSTMENT(s.adj));

  gtk_scale_set_digits(GTK_SCALE(s.scale),0);
  gtk_scale_set_value_pos(GTK_SCALE(s.scale),GTK_POS_TOP);
  // gtk_range_set_update_policy(GTK_RANGE(s.scale),GTK_UPDATE_DELAYED);

  // attach to table
  GtkAttachOptions opfe = (GtkAttachOptions)(GTK_FILL|GTK_EXPAND);
  GtkAttachOptions opf  = (GtkAttachOptions)(GTK_FILL);
  int pad = 4;
  gtk_table_attach(GTK_TABLE(table),s.label,0,1,y,y+1,opf ,opfe,pad,pad);
  gtk_table_attach(GTK_TABLE(table),s.scale,1,2,y,y+1,opfe,opfe,pad,pad);
  y++;

  // Set up signal
  gtk_signal_connect(GTK_OBJECT(s.adj),"value_changed",
      GTK_SIGNAL_FUNC(control_thresh_set_event),(gpointer)s.adj);

  // Show widgets
  gtk_widget_show(s.label);
  gtk_widget_show(s.scale);
}

GtkWidget *control_add_menu(GtkWidget *table,int &y,char *label)
{
  // create widgets
  GtkWidget *lab,*menu,*option_menu;

  lab = gtk_label_new(label);
  option_menu = gtk_option_menu_new();

  // attach to table
  GtkAttachOptions opfe = (GtkAttachOptions)(GTK_FILL|GTK_EXPAND);
  GtkAttachOptions opf  = (GtkAttachOptions)(GTK_FILL);
  int pad = 4;
  gtk_table_attach(GTK_TABLE(table),lab ,0,1,y,y+1,opf ,opfe,pad,pad);
  gtk_table_attach(GTK_TABLE(table),option_menu,1,2,y,y+1,opfe,opfe,pad,pad);
  y++;

  // Show widgets
  gtk_widget_show(lab);
  gtk_widget_show(option_menu);

  return(option_menu);
}

#define LOAD_ICON(str) \
  gdk_pixmap_colormap_create_from_xpm(w.window->window, \
      colormap,&mask,NULL,str)

void create_control_window(control_window &w)
{
  GdkPixmap *icon;
  GdkBitmap *mask;
  GtkWidget *iconw;
  GdkColormap *colormap;

  // Create widgets
  w.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(w.window),"CMV Threshold Editor");
  gtk_container_set_border_width(GTK_CONTAINER(w.window),4);

  w.vbox = gtk_vbox_new(FALSE,0);
  w.table = gtk_table_new(11,2,FALSE);

  // Create toolbar and add icons
  w.toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,GTK_TOOLBAR_BOTH);
  gtk_box_pack_start(GTK_BOX(w.vbox),w.toolbar,TRUE,TRUE,0);

  colormap = gdk_colormap_get_system();
  icon = LOAD_ICON("img/new.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.new_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "New","Initialize new threshold file",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_new_event),NULL);

  icon = LOAD_ICON("img/open.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.open_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Open","Opens existing threshold file",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_open_event),NULL);

  icon = LOAD_ICON("img/reload.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.reload_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Reload","Reloads current threshold file",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_reload_event),NULL);

  icon = LOAD_ICON("img/save.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.save_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Save","Saves thresholds to current file",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_save_event),NULL);

  icon = LOAD_ICON("img/saveas.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.saveas_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Save As","Saves thresholds to a new file",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_saveas_event),NULL);

  icon = LOAD_ICON("img/pause.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.saveas_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Pause","Pauses CMVision",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_pause_event),NULL);

  icon = LOAD_ICON("img/background.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.saveas_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Background","Toggle Background Color",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_background_event),NULL);

  icon = LOAD_ICON("img/crosshair.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.saveas_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Crosshair","Toggle into crosshair mode",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_crosshair_event),NULL);

  icon = LOAD_ICON("img/quit.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.saveas_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Quit","Quit program",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_quit_event),NULL);

  /*
  gtk_toolbar_append_space(GTK_TOOLBAR(w.toolbar));

  icon = LOAD_ICON("img/paint.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.paint_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Paint","Sets current mode to paint",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_paint_event),NULL);

  icon = LOAD_ICON("img/blur.xpm");
  iconw = gtk_pixmap_new(icon,mask);
  w.blur_button = gtk_toolbar_append_item(GTK_TOOLBAR(w.toolbar),
      "Blur","Sets current mode to blur",NULL,
      iconw,GTK_SIGNAL_FUNC(toolbar_blur_event),NULL);
  */

  GtkWidget *l;
  char *str;
  int i,y;

  w.color_menu = gtk_menu_new();

  for(i=0; i<32; i++){
    str = vision_color_name(i);
    if(str){
      l = gtk_menu_item_new_with_label(str);
      gtk_signal_connect(GTK_OBJECT(l),"activate",
        GTK_SIGNAL_FUNC(control_select_color_event),(gpointer)i);
      gtk_widget_show(l);
      // printf("Added [%s]\n",vision_color_name(i));
      gtk_menu_append(GTK_MENU(w.color_menu),l);
    }
  }

  /*
  // Add color dropdown
  GList *l = w.colors;
  l = g_list_append(l,(void*)"First Item");
  l = g_list_append(l,(void*)"Second Item");
  l = g_list_append(l,(void*)"Third Item");
  l = g_list_append(l,(void*)"Fourth Item");
  l = g_list_append(l,(void*)"Fifth Item");
  w.colors = l;


  w.color = control_add_hslider(w.table,y,"Color:");
  gtk_combo_set_popdown_strings(GTK_COMBO(w.color),w.colors);
  control_add_hseparator(w.table,y);
  */

  y = 0;

  w.color = control_add_menu(w.table,y,"Color:");
  gtk_option_menu_set_menu(GTK_OPTION_MENU(w.color),w.color_menu);
  control_add_hseparator(w.table,y);

  // Add sliders
  control_add_hslider(w.table,y,w.y_min,"Y Min",0);
  control_add_hslider(w.table,y,w.y_max,"Y Max",255);
  control_add_hseparator(w.table,y);

  control_add_hslider(w.table,y,w.u_min,"U Min",0);
  control_add_hslider(w.table,y,w.u_max,"U Max",255);
  control_add_hseparator(w.table,y);

  control_add_hslider(w.table,y,w.v_min,"V Min",0);
  control_add_hslider(w.table,y,w.v_max,"V Max",255);
  control_add_hseparator(w.table,y);

  // set initial values
  control_select_color_event(NULL,0);

  // Pack widgets
  gtk_container_add(GTK_CONTAINER(w.window),w.vbox);
  gtk_box_pack_start(GTK_BOX(w.vbox),w.table,FALSE,FALSE,0);

  // Add destroy-on-close behavior
  gtk_signal_connect(GTK_OBJECT(w.window), "delete_event",
		     GTK_SIGNAL_FUNC(delete_event), NULL);
  gtk_quit_add_destroy(1, GTK_OBJECT(w.window));

  // Set up signals

  // Show widgets
  gtk_widget_show(w.toolbar);

  gtk_widget_show(w.table);
  //gtk_widget_show(w.hbox);
  gtk_widget_show(w.vbox);
  gtk_widget_show(w.window);
}


//==== Video Window ==================================================//

int cal_id = 0;

double cal[13][3] = {
  -137.00,  76.25,   0.00,
     0.00,  76.25,   0.00,
   137.00,  76.25,   0.00,

  -114.50,  50.00,   0.00,
   114.50,  50.00,   0.00,

  -137.00,   0.00,   0.00,
     0.00,   0.00,   0.00,
   137.00,   0.00,   0.00,

  -114.50, -50.00,   0.00,
   114.50, -50.00,   0.00,

  -137.00, -76.25,   0.00,
     0.00, -76.25,   0.00,
   137.00, -76.25,   0.00
};

gboolean crosshair_button_press(GtkWidget *widget,GdkEventButton *event,
				gpointer user_data)
{
  //printf("crosshair button press event (%f, %f)\n", event->x, event->y);
  printf("(%8.2f,%8.2f,%8.2f) (%8.2f,%8.2f)\n",
    cal[cal_id][0],cal[cal_id][1],cal[cal_id][2],
    event->x, event->y);
  cal_id++;

  app.cross_x = (int)event->x;
  app.cross_y = (int)event->y;
  button_press = true;

  return(TRUE);
}

void draw_crosshair(GdkDrawable *output, int x, int y)
{
  GdkGC *gc_output = gdk_gc_new(output);
  GdkColor color;
  //b | (g << 8) | (r << 16);
  color.pixel = 0 | ( 255 << 8) | (0 << 16);
  color.red = 0;
  color.blue = 0;
  color.green = 255;
  gdk_gc_set_foreground(gc_output, &color);
  gdk_gc_set_line_attributes(gc_output, 2, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_BEVEL);
  gdk_draw_line(output,gc_output,x - 2, y, x+2, y);
  gdk_draw_line(output,gc_output,x, y - 2, x, y+2);
  gdk_gc_unref(gc_output);
}

gboolean video_video_expose(GtkWidget *widget,GdkEventExpose *event)
{
  // widget = win.video.video;
  //gdk_gc_set_clip_rectangle(widget->style->fg_gc[widget->state],
  // NULL);
  gdk_draw_rgb_image(widget->window,widget->style->fg_gc[GTK_STATE_NORMAL],
			0,0,VIEW_WIDTH,VIEW_HEIGHT,GDK_RGB_DITHER_NONE,
			(guchar*)app.video_buf,VIEW_WIDTH*3);
  if(crosshair_mode)
    draw_crosshair(widget->window, app.cross_x, app.cross_y);

  return(TRUE);
}

gboolean video_output_expose(GtkWidget *widget,GdkEventExpose *event)
{
  // gdk_gc_set_clip_rectangle(widget->style->fg_gc[widget->state],
  // NULL);
  gdk_draw_rgb_image(widget->window,widget->style->fg_gc[GTK_STATE_NORMAL],
			0,0,VIEW_WIDTH,VIEW_HEIGHT,GDK_RGB_DITHER_NONE,
			(guchar*)app.output_buf,VIEW_WIDTH*3);
  return(TRUE);
}

gboolean video_button_press_event       (GtkWidget       *widget,
                                        GdkEventButton  *event,
                                        gpointer         user_data)
{
  printf("video_button_press\n");
  if(!capture_frame){
    mouse_x = (int)event->x;
    mouse_y = (int)event->y;
    if(mouse_x < VIEW_WIDTH && mouse_y < VIEW_HEIGHT){
        button_press = true;
    }
  }
}


// void create_output_window()
// create a output window and store information in output_window
void create_output_window(output_window &w){
  // create the window
  w.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(w.window),"CMV Threshold Editor: Output");  
  gtk_widget_set_usize (w.window, VIEW_WIDTH, VIEW_HEIGHT); 
  gtk_window_set_policy (GTK_WINDOW (w.window), FALSE, FALSE, FALSE); // not resizable

  // contstruct output drawing area
  w.output = gtk_drawing_area_new();
  gtk_drawing_area_size(GTK_DRAWING_AREA(w.output),VIEW_WIDTH,VIEW_HEIGHT);
  gtk_container_add(GTK_CONTAINER(w.window),w.output);
  gtk_signal_connect(GTK_OBJECT(w.window), "delete_event",
		     GTK_SIGNAL_FUNC(delete_event), NULL);

  // don't know
  gtk_quit_add_destroy(1, GTK_OBJECT(w.window));

  // Show widgets
  gtk_widget_show(w.output);

  // show output window
  gtk_widget_show(w.window);

  w.can_update = true;
  gtk_signal_connect(GTK_OBJECT(w.output), "expose_event",
  	     GTK_SIGNAL_FUNC(video_output_expose),NULL);

}

void create_video_window(vid_window &w)
{
  // Create widgets
  w.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_widget_set_events (w.window, GDK_BUTTON_PRESS_MASK | GDK_EXPOSURE_MASK);
  gtk_window_set_title(GTK_WINDOW(w.window),"CMV Threshold Editor: Video");
  gtk_widget_set_usize (w.window, VIEW_WIDTH, VIEW_HEIGHT); 
  gtk_window_set_policy (GTK_WINDOW (w.window), FALSE, FALSE, FALSE); // not resizable

  //gtk_widget_set_uposition (window1, 0, 0);



  // gtk_container_set_border_width(GTK_CONTAINER(w.window),4); don't need this

  //w.vbox = gtk_vbox_new(FALSE,4);

  w.video = gtk_drawing_area_new();
  gtk_drawing_area_size(GTK_DRAWING_AREA(w.video),VIEW_WIDTH,VIEW_HEIGHT);
  //gtk_widget_set_events (w.video, GDK_BUTTON_PRESS_MASK);

  //w.output = gtk_drawing_area_new();
  //gtk_drawing_area_size(GTK_DRAWING_AREA(w.output),VIEW_WIDTH,VIEW_HEIGHT);

  // Pack widgets
  //gtk_container_add(GTK_CONTAINER(w.window),w.vbox);
  gtk_container_add(GTK_CONTAINER(w.window),w.video);

  gtk_signal_connect(GTK_OBJECT(w.video), "expose_event",
  	     GTK_SIGNAL_FUNC(video_video_expose),NULL);

  //gtk_box_pack_start(GTK_BOX(w.vbox),w.video,FALSE,FALSE,0);
  //gtk_box_pack_start(GTK_BOX(w.vbox),w.output,FALSE,FALSE,0);

  // Set up signals



  // Add destroy-on-close behavior
  gtk_signal_connect(GTK_OBJECT(w.window), "delete_event",
		     GTK_SIGNAL_FUNC(delete_event), NULL);

  /*gtk_signal_connect (GTK_OBJECT (w.window), "button_press_event",
                      GTK_SIGNAL_FUNC (video_button_press_event),
                      NULL);*/

  gtk_quit_add_destroy(1, GTK_OBJECT(w.window));

  // Show widgets
  gtk_widget_show(w.video);
  //gtk_widget_show(w.output);

  //gtk_widget_show(w.vbox);
  gtk_widget_show(w.window);

  w.can_update = true;
  gtk_signal_connect (GTK_OBJECT (w.window), "button_press_event",
                      GTK_SIGNAL_FUNC (crosshair_button_press),
                      NULL);
  // gtk_widget_set_events(w.video, GDK_BUTTON_PRESS_MASK);
}


//==== Histogram Window ==============================================//

gboolean hist_uv_expose(GtkWidget *widget,GdkEventExpose *event)
{
  gdk_draw_rgb_image(widget->window,widget->style->fg_gc[GTK_STATE_NORMAL],
		     0,0,HIST_SIZE,HIST_SIZE,GDK_RGB_DITHER_NONE,
		     (guchar*)app.uv_hist,HIST_SIZE*3);
  if(captured_image && crosshair_mode){
    image_pixel here = c_img[(app.cross_y * VIEW_WIDTH + app.cross_x)/2];

    draw_crosshair(widget->window, here.v, here.u);
  }
  return(TRUE);
}

gboolean hist_uy_expose(GtkWidget *widget,GdkEventExpose *event)
{
  gdk_draw_rgb_image(widget->window,widget->style->fg_gc[GTK_STATE_NORMAL],
			0,0,HIST_SIZE,HIST_SIZE,GDK_RGB_DITHER_NONE,
			(guchar*)app.uy_hist,HIST_SIZE*3);
  if(captured_image && crosshair_mode){
    image_pixel here = c_img[(app.cross_y * VIEW_WIDTH + app.cross_x)/2];
    int y = (here.y1 + here.y2)/2;
    //printf("y=%d, u=%d, v=%d\n", here.y1, here.u, here.v);
    draw_crosshair(widget->window, y, here.u);
  }
  return(TRUE);
}

gboolean hist_yv_expose(GtkWidget *widget,GdkEventExpose *event)
{
  gdk_draw_rgb_image(widget->window,widget->style->fg_gc[GTK_STATE_NORMAL],
			0,0,HIST_SIZE,HIST_SIZE,GDK_RGB_DITHER_NONE,
			(guchar*)app.yv_hist,HIST_SIZE*3);
  if(captured_image && crosshair_mode){
    image_pixel here = c_img[(app.cross_y * VIEW_WIDTH + app.cross_x)/2];
    int y = (here.y1 + here.y2)/2;
    draw_crosshair(widget->window, here.v, y);
  }
  return(TRUE);
}

void create_hist_window(hist_window &w)
{
  // Create widgets
  w.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(w.window),"CMV Threshold Editor");
  gtk_container_set_border_width(GTK_CONTAINER(w.window),2);

  w.table = gtk_table_new(2,2,FALSE);

  w.uv_hist = gtk_drawing_area_new();
  gtk_drawing_area_size(GTK_DRAWING_AREA(w.uv_hist),HIST_SIZE,HIST_SIZE);

  w.uy_hist = gtk_drawing_area_new();
  gtk_drawing_area_size(GTK_DRAWING_AREA(w.uy_hist),HIST_SIZE,HIST_SIZE);

  w.yv_hist = gtk_drawing_area_new();
  gtk_drawing_area_size(GTK_DRAWING_AREA(w.yv_hist),HIST_SIZE,HIST_SIZE);


  // Pack widgets
  gtk_container_add(GTK_CONTAINER(w.window),w.table);

  //GtkAttachOptions opfe = (GtkAttachOptions)(GTK_FILL|GTK_EXPAND);
  GtkAttachOptions opf  = (GtkAttachOptions)(GTK_FILL);
  int pad = 2;
  gtk_table_attach(GTK_TABLE(w.table),w.uv_hist,0,1,0,1,opf,opf,pad,pad);
  gtk_table_attach(GTK_TABLE(w.table),w.uy_hist,1,2,0,1,opf,opf,pad,pad);
  gtk_table_attach(GTK_TABLE(w.table),w.yv_hist,0,1,1,2,opf,opf,pad,pad);

  // Set up signals
  gtk_signal_connect(GTK_OBJECT(w.uv_hist), "expose_event",
		     GTK_SIGNAL_FUNC(hist_uv_expose),NULL);
  gtk_signal_connect(GTK_OBJECT(w.uy_hist), "expose_event",
		     GTK_SIGNAL_FUNC(hist_uy_expose),NULL);
  gtk_signal_connect(GTK_OBJECT(w.yv_hist), "expose_event",
		     GTK_SIGNAL_FUNC(hist_yv_expose),NULL);

  // Add destroy-on-close behavior
  gtk_signal_connect(GTK_OBJECT(w.window), "delete_event",
		     GTK_SIGNAL_FUNC(delete_event), NULL);
  gtk_quit_add_destroy(1, GTK_OBJECT(w.window));

  // Show widgets
  gtk_widget_show(w.uv_hist);
  gtk_widget_show(w.uy_hist);
  gtk_widget_show(w.yv_hist);

  gtk_widget_show(w.table);
  gtk_widget_show(w.window);

  w.can_update = true;
}


//==== Main Window Functions =========================================//

void create_windows(windows &w)
{
  // create_file_window(w.file,"");
  create_control_window(w.control);
  create_video_window(w.video);
  create_output_window(w.output);
  create_hist_window(w.hist);
}

void update_windows(windows &w,int frame)
{
  // expose video, blob, and hist windows
  if(!w.video.can_update && !w.output.can_update) return; // maybe check can_update for output, don't know, ZK

  if(frame % 2){
  	if(app.show_hist){
  		sem_wait(&app.hist_lock);
      hist_uv_expose(w.hist.uv_hist,NULL);
      hist_uy_expose(w.hist.uy_hist,NULL);
      hist_yv_expose(w.hist.yv_hist,NULL);
  		sem_post(&app.hist_lock);
    }
  }else{
    video_video_expose(w.video.video,NULL);
    video_output_expose(w.output.output,NULL);
  }
}

void destroy_windows(windows &w)
{
  // printf("DESTROY!\n");
  w.video.can_update = false;
  w.output.can_update = false;
  w.hist.can_update = false;
  // add any garbage collection needed
}

utils/grab/Makefile 16/22

[
top][prev][next]
# location of CMVision
CMVDIR = ../..

CC = g++
CFLAGS = -O3
TARGET = grab
SRC = $(wildcard *.cc) $(wildcard $(CMVDIR)/src/*.cc)
OBJ = $(SRC:%.cc=%.o)
LIB =
INC = -I$(CMVDIR)/include


all: $(TARGET)

.SUFFIXES: .cc
%.o: %.cc
	$(CC) $(CFLAGS) $(INC) -c $< -o $@

$(TARGET): $(OBJ)
	$(CC) $(CFLAGS) -o $@ $(OBJ) $(LIB)

clean:
	rm -f *.o $(TARGET) core

utils/grab/grab.cc 17/22

[
top][prev][next]
/*=========================================================================
    Copyright 2000 James Bruce
    Example program to capture and save images using the capture library
  -------------------------------------------------------------------------
    REVISION HISTORY:
      2000-05-20:  Initial release version - ugly, adapted from
                   something I needed really quickly at some point (JRB)
  =========================================================================*/

// NOTE: this file is messy and requires modification to be useful,
// though hopefully it can serve as example code for using the capture
// library.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// CMVision capture library
#include <capture.h>

// The printf format string for output filenames
#define FILE_NAME_STYLE "images/image%03d.ppm"


struct rgb{
  unsigned char red,green,blue;
};

struct uyvy{
  unsigned char u,y1,v,y2;
};

rgb black = {0,0,0};


// These should really be parameters, but aren't yet.
int width  = 320;
int height = 240;
int fmt = V4L2_PIX_FMT_UYVY;
// int fmt = V4L2_PIX_FMT_BGR24;
// int fmt = V4L2_PIX_FMT_YUYV;
int num = 120;

rgb *img;
uyvy *buf,*cur;
char file[32];


int bound(int low,int high,int n)
{
  if(n < low ) n = low;
  if(n > high) n = high;
  return(n);
}

rgb yuv_to_rgb(int y,int u,int v)
{
  rgb c;

  u = 2*u - 256;
  v = 2*v - 256;

  c.red   = bound(0,255,y + v);
  c.green = bound(0,255,(int)(y - 0.51*v - 0.19*u));
  c.blue  = bound(0,255,y + u);
  //c.alpha = 0;

  return(c);
}

void swap_rgb(rgb *buf,int len)
{
  int i;
  rgb r;

  for(i=0; i<len; i++){
    r = buf[i];
    buf[i].red  = r.blue;
    buf[i].blue = r.red;
  }
}

void convert(rgb *dest,uyvy *src,int size)
{
  int i;
  uyvy p;

  for(i=0; i<size; i++){
    p = src[i];
    dest[2*i + 0] = yuv_to_rgb(p.y1,p.u,p.v);
    dest[2*i + 1] = yuv_to_rgb(p.y2,p.u,p.v);
  }
}

int main()
{
  capture cap;
  int i,size;

  char filename[32];
  FILE *file;

  timeval t1,t2;
  double sec;
  bool ok;

  ok = cap.initialize("/dev/video",width,height,fmt);
  if(!ok) printf("Capture init failed.\n");

  size = width*height/2;
  img = new rgb[size*2];
  buf = new uyvy[size*num];

  if(!img || !buf){
    printf("Not enough memory");
    exit(1);
  }

  // Initialize mem to bring into core memory
  // Could use mlock, but its the simple 1-thread method for now
  memset(buf,0,size*num*sizeof(uyvy));

  /*
  // Wait a bit
  printf("Waiting four seconds"); fflush(stdout);
  for(i=0; i<4; i++){
    sleep(1);
    printf("."); fflush(stdout);
  }
  printf("\n");
  */

  // Capture some initial frames
  for(i=0; i<10; i++){
    cur = (uyvy*)cap.captureFrame();
  }

  // Capture the frames
  printf("Capturing\n");
  gettimeofday(&t1,NULL);

  for(i=0; i<num; i++){
    cur = (uyvy*)cap.captureFrame();
    memcpy(buf + size*i,cur,size*sizeof(uyvy));
    // memset(buf + size*i,i*4,size*sizeof(rgb));

    printf("."); fflush(stdout);
    if(i % 30 == 0) printf("\n");
  }

  gettimeofday(&t2,NULL);
  printf("done.\n");

  sec = (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1E6;
  printf("Elapsed time: %4.3fs (%ffps)\n",sec,num / sec);

  // Most capture cards are BGR for some reason
  // swap_rgb(buf,size*num);

  // Save files to image dir as raw PPMs
  printf("Writing\n");
  for(i=0; i<num; i++){
    convert(img,buf + size*i,size);

    sprintf(filename,FILE_NAME_STYLE,i);
    if(file = fopen(filename,"w")){
      fprintf(file,"P6\n%d %d\n255\n",width,height);
      fwrite(img,sizeof(rgb),size*2,file);
      fclose(file);
      printf("."); fflush(stdout);
    }
  }
  printf("done.\n");

  return(0);
}

utils/mtest/Makefile 18/22

[
top][prev][next]
# location of CMVision
CMVDIR = ../..

CC = g++
CFLAGS = -O3 -DUSE_METEOR
TARGET = mtest
SRC = $(wildcard *.cc) $(wildcard $(CMVDIR)/src/*.cc)
OBJ = $(SRC:%.cc=%.o)
LIB = -L/usr/X11/lib -lX11
INC = -I$(CMVDIR)/include -I/usr/include/X11


all: $(TARGET)

.SUFFIXES: .cc
%.o: %.cc
	$(CC) $(CFLAGS) $(INC) -c $< -o $@

$(TARGET): $(OBJ)
	$(CC) $(CFLAGS) -o $@ $(OBJ) $(LIB)

clean:
	rm -f *.o $(TARGET) $(CMVDIR)/src/*.o core

utils/mtest/colors.txt 19/22

[
top][prev][next]
[Colors]
(255,128,  0) 0.5000 2 Ball
(255,255,  0) 0.6000 3 Yellow_Team
(  0,  0,255) 0.6000 3 Blue_Team
(255,255,255) 0.0000 0 White
(255,  0,255) 0.0000 0 Marker_Pink
(160,  0,160) 0.0000 0 Marker_Purple
(  0,160,  0) 0.0000 0 Marker_Green
(  0,  0,  0) 0.0000 0 C08
(  0,  0,  0) 0.0000 0 C09
(  0,  0,  0) 0.0000 0 C10
(  0,  0,  0) 0.0000 0 C11
(  0,  0,  0) 0.0000 0 C12
(  0,  0,  0) 0.0000 0 C13
(  0,  0,  0) 0.0000 0 C14
(  0,  0,  0) 0.0000 0 C15
(  0,  0,  0) 0.0000 0 C16
(255,128,  0) 0.0000 0 Ball_2
(255,255,  0) 0.0000 0 Yellow_Team_2
(  0,  0,255) 0.0000 0 Blue_Team_2
(255,255,255) 0.0000 0 White_2
(255,  0,255) 0.0000 0 Marker_Pink_2
(160,  0,160) 0.0000 0 Marker_Purple_2
(  0,160,  0) 0.0000 0 Marker_Green_2

[Thresholds]
(  7:175, 50: 97,168:219)
( 87:251,  4: 84,170:209)
( 76:122,205:221, 67:128)
(130:255, 81:131,125:178)
( 50:181,102:135,190:222)
(103: 96,118:140,144:166)
( 67:134, 96:129, 85:124)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
( 86:221, 35: 79,102:150)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)
(  0:  0,  0:  0,  0:  0)

utils/mtest/mtest.cc 20/22

[
top][prev][next]
// A simple program demonstrating X output and use of density merging.

#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <math.h>

#include "cmvision.h"
#include "capture.h"
#include "win.h"

#define WIDTH  160
#define HEIGHT 120

int main()
{
  xwindows xw;
  xwin win;
  xpixmap back;

  XEvent xev;
  KeySym key;

  capture cap;
  CMVision vision;
  image_pixel *img;

  CMVision::region *reg;
  CMVision::rectangle rect;
  CMVision::line line;

  int c;
  bool run;

  xw.initialize();
  win = xw.createWindow(WIDTH,HEIGHT,"Density Merging Test");
  back = win.createPixmap(WIDTH,HEIGHT);

  if(!cap.initialize(WIDTH,HEIGHT) ||
     !vision.initialize(WIDTH,HEIGHT)){
    printf("Vision init failed.\n");
  }

  vision.loadOptions("colors.txt");
  vision.enable(CMV_DENSITY_MERGE);

  run = true;

  while(run){
    img = (image_pixel*)cap.captureFrame();
    vision.processFrame(img);

    back.setGray(0);
    back.fillRectangle(0,0,WIDTH,HEIGHT);

    for(c=0; c<4; c++){
      reg = vision.getRegions(c);
      back.setColor(vision.getColorVisual(c));

      while(reg && reg->area>16){
	rect.x = reg->x1;
	rect.y = reg->y1;
	rect.w = reg->x2 - reg->x1 + 1;
	rect.h = reg->y2 - reg->y1 + 1;

	back.drawRectangle(rect.x,rect.y,rect.w,rect.h);

	reg = reg->next;
      }
    }

    // copy back buffer to front
    win.copyArea(back,0,0,WIDTH,HEIGHT,0,0);

    while(xw.checkEvent(xev)){
      switch(xev.type){
        case KeyPress:
	  key = XLookupKeysym(&xev.xkey,0);

	  switch(key){
            case XK_space: break;

            case(XK_Left):  break;
            case(XK_Up):    break;
            case(XK_Right): break;
            case(XK_Down):  break;

            case(XK_Escape):
	      run = false;
	      break;
	  }
	  break;
      }
    }
  }

  cap.close();
  vision.close();

  win.close();
  xw.close();
}

utils/mtest/win.cc 21/22

[
top][prev][next]
/*=========================================================================
    Win.h
  -------------------------------------------------------------------------
    Simple C++ wrapper interface for XLib
  -------------------------------------------------------------------------
    Copyright 1999, 2000 James R. Bruce
    School of Computer Science, Carnegie Mellon University
  -------------------------------------------------------------------------
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  =========================================================================*/

#include "win.h"

int LeastSetBitNum(int n)
{
  int i = 1;

  if(!n) return(0);

  while(!(n&1)){
    n >>= 1;
    i++;
  }
  return(i);
}

//==== XWindows Class Implementation =================================//

bool xwindows::initialize()
{
  // General initialization of X
  disp = XOpenDisplay(NULL);
  if(!disp){
    printf("Cannot open display.\n");
    return(false);
  }

  screen = DefaultScreen(disp);
  depth = DefaultDepth(disp,screen);
  root = RootWindow(disp,screen);

  XVisualInfo xvi;
  if(!XMatchVisualInfo(disp,screen,24,TrueColor,&xvi) &&
     !XMatchVisualInfo(disp,screen,32,TrueColor,&xvi)){
    printf("This program requires 24 bit color (%d).\n",depth);
    exit(0);
  }
  red_shift   = LeastSetBitNum(xvi.red_mask  ) - 1;
  green_shift = LeastSetBitNum(xvi.green_mask) - 1;
  blue_shift  = LeastSetBitNum(xvi.blue_mask ) - 1;
  vis = xvi.visual;
  // printf("Shift: %d %d %d\n",red_shift,green_shift,blue_shift);

  return(true);
}

void xwindows::close()
{
  if(disp) XCloseDisplay(disp);
  disp = NULL;
}

xwin xwindows::createWindow(int width,int height,char *title)
{
  xwin xw;
  xw.initialize(this,width,height,title);
  return(xw);
}

/*
xpixmap xwindows::createPixmap(int width,int height)
{
  xpixmap xp;
  xp.initialize(this,width,height);
  return(xp);
}
*/

bool xwindows::checkEvent(XEvent &xev)
{
  bool r = (XPending(disp) != 0);
  if(r) XNextEvent(disp,&xev);
  return(r);
}

void xwindows::getEvent(XEvent &xev)
{
  XNextEvent(disp,&xev);
}

void xwindows::flush()
{
  XFlush(disp);
}

//==== XDrawable Class Implementation ================================//

void xdrawable::setColor(int red,int green,int blue)
{
  int id;

  id = (red   << xw->red_shift  ) |
       (green << xw->green_shift) |
       (blue  << xw->blue_shift );

  XSetForeground(xw->disp,gc,id);
}

void xdrawable::setColor(rgb color)
{
  int id;

  id = (color.red   << xw->red_shift  ) |
       (color.green << xw->green_shift) |
       (color.blue  << xw->blue_shift );

  XSetForeground(xw->disp,gc,id);
}

void xdrawable::setGray(int intensity)
{
  int id;

  id = (intensity << xw->red_shift  ) |
       (intensity << xw->green_shift) |
       (intensity << xw->blue_shift );

  XSetForeground(xw->disp,gc,id);
}

void xdrawable::fillRectangle(int x,int y,int w,int h)
{
  XFillRectangle(xw->disp,draw,gc,x,y,w,h);
}

void xdrawable::fillCircle(int x,int y,int r)
{
  XFillArc(xw->disp,draw,gc,x-r,y-r,2*r+1,2*r+1,0,360*64);
}

void xdrawable::fillPolygon(XPoint *pts,int num)
{
  XFillPolygon(xw->disp,draw,gc,pts,num,Convex,CoordModeOrigin);
}


void xdrawable::drawRectangle(int x,int y,int w,int h)
{
  XDrawRectangle(xw->disp,draw,gc,x,y,w,h);
}

void xdrawable::drawCircle(int x,int y,int r)
{
  XDrawArc(xw->disp,draw,gc,x-r,y-r,2*r+1,2*r+1,0,360*64);
}

void xdrawable::drawLine(int x1,int y1,int x2,int y2)
{
  XDrawLine(xw->disp,draw,gc,x1,y1,x2,y2);
}

void xdrawable::drawLines(XPoint *pts,int num)
{
  XDrawLines(xw->disp,draw,gc,pts,num,CoordModeOrigin);      
}

void xdrawable::copyArea(xdrawable &src,int src_x,int src_y,
			int w,int h,int dest_x,int dest_y)
{
  XCopyArea(xw->disp,src.draw,draw,gc,src_x,src_y,w,h,dest_x,dest_y);
}

void xdrawable::print(int x,int y,char *str)
{
  XTextItem t;
  int i;

  t.chars  = str;
  t.nchars = strlen(str);
  t.delta  = 0;
  t.font   = None;

  XDrawText(xw->disp,draw,gc,x,y,&t,1);
}

bool xdrawable::loadImage(char *filename)
{
  FILE *in;
  int w,h,m,x,y;
  rgb c;

  in = fopen(filename,"rb");
  if(!in) return(false);

  w = h = 0;
  fscanf(in,"P6\n%d %d\n%d\n",&w,&h,&m);
  // printf("w=%d h=%d max=%d\n",w,h,m);

  for(y=0; y<h; y++){
    printf("\rloading '%s' %2d%%",filename,(y*100)/h);
    fflush(stdout);
    for(x=0; x<w; x++){
      fread(&c,sizeof(rgb),1,in);
      setColor(c);
      XDrawPoint(xw->disp,draw,gc,x,y);
    }
  }
  fclose(in);
  printf("\rloading '%s' done.\n",filename);

  return(true);
}

/*
void printXImage(XImage *i)
{
  printf("width: %d\n",i->width);
  printf("height: %d\n",i->height);
  printf("xoffset: %d\n",i->xoffset);
  printf("format: %d\n",i->format);
  printf("data: 0x%X\n",i->data);
  printf("byte_order: %d\n",i->byte_order);
  printf("bitmap_unit: %d\n",i->bitmap_unit);
  printf("bitmap_bit_order: %d\n",i->bitmap_bit_order);
  printf("bitmap_pad: %d\n",i->bitmap_pad);
  printf("depth: %d\n",i->depth);
  printf("bytes_per_line: %d\n",i->bytes_per_line);
  printf("bits_per_pixel: %d\n",i->bits_per_pixel);
  printf("red_mask: 0x%08X\n",i->red_mask);
  printf("green_mask: 0x%08X\n",i->green_mask);
  printf("blue_mask: 0x%08X\n",i->blue_mask);
}

XImage *xdrawable::newImage(int w,int h)
{
  XImage *img;
  char *data;

  data = new char[w * h * 3];
  if(!data) return(NULL);

  img = new XImage;
  if(!img){
    delete(data);
    return(NULL);
  }

  img->width  = w;
  img->height = h;
  img->xoffset = 0;
  img->format = ZPixmap;
  img->data = data;
  img->byte_order = MSBFirst;
  img->bitmap_unit = 8;
  img->bitmap_bit_order = LSBFirst;
  img->bitmap_pad = 8;
  img->depth = 24;
  img->bytes_per_line = w * (24/8);
  img->bits_per_pixel = 24;
  img->red_mask   = 0xFF <<  0;
  img->green_mask = 0xFF <<  8;
  img->blue_mask  = 0xFF << 16;
  // there, wasn't that easy?
  XInitImage(img);

  // printf("Status = %d\n",XInitImage(img));
  // img = XGetImage(disp,root,0,0,width,height,AllPlanes,ZPixmap);
  // img = XCreateImage(disp,vis,24,ZPixmap,0,data,w,h,8,0);

  return(img);
}
*/

//==== XPixmap Class Implementation ==================================//

void xpixmap::initialize(xwin *nxw,int w,int h)
{
  xw = nxw->xw;

  // Create and initialize pixmap
  unsigned valuemask = 0;
  XGCValues values;

  pix = XCreatePixmap(xw->disp,xw->root,w,h,24);

  cmap = nxw->cmap; // XCreateColormap(xw->disp,win,xw->vis,AllocNone);
  gc = XCreateGC(xw->disp,nxw->win,valuemask,&values);
  // XCopyGC(xw->disp, src, valuemask, dest)nxw->gc);
}

void xpixmap::close()
{
  XFreePixmap(xw->disp,pix);
}

//==== XWin Class Implementation =====================================//

void xwin::initialize(xwindows *nxw,int width,int height,const char *title)
{
  xw = nxw;

  // Create and initialize window
  XSizeHints size_hints;
  unsigned valuemask = 0;
  XGCValues values;
  XEvent xev;

  win = XCreateSimpleWindow(xw->disp,xw->root,0,0,width,height,0,
    WhitePixel(xw->disp,xw->screen), BlackPixel(xw->disp,xw->screen));

  cmap = XCreateColormap(xw->disp,win,xw->vis,AllocNone);
  gc = XCreateGC(xw->disp,win,valuemask,&values);

  size_hints.flags = PSize | PMinSize | PMaxSize;
  size_hints.min_width = width;
  size_hints.max_width = width;
  size_hints.min_height = height;
  size_hints.max_height = height;
  XSetStandardProperties(xw->disp,win,title,title,None,0,0,&size_hints);

  XSelectInput(xw->disp,win,
    ButtonPressMask |
    ButtonMotionMask |
    Button1MotionMask | Button2MotionMask | Button3MotionMask |
    PointerMotionMask |
    KeyPressMask | KeyReleaseMask |
    ExposureMask);
  XMapWindow(xw->disp,win);

  // Block until window is mapped
  do{
    xw->getEvent(xev);
  }while(xev.type != Expose);
}

void xwin::close()
{
  XDestroyWindow(xw->disp,win);
}

xpixmap xwin::createPixmap(int width,int height)
{
  xpixmap xp;
  xp.initialize(this,width,height);
  return(xp);
}

void xwin::setBackground(xpixmap &p)
{
  XSetWindowBackgroundPixmap(xw->disp,win,p.pix);
}

//==== Event Handling ====//

/*
bool xwin::checkEvent(XEvent &xev)
{
  bool r = (XPending(disp) != 0);
  if(r) XNextEvent(disp,&xev);
  return(r);
}

void xwin::getEvent(XEvent &xev)
{
  XNextEvent(disp,&xev);
}

void xwin::flush()
{
  XFlush(disp);
}
*/

utils/mtest/win.h 22/22

[
top][prev][next]
/*=========================================================================
    Win.h
  -------------------------------------------------------------------------
    Simple C++ wrapper interface for XLib
  -------------------------------------------------------------------------
    Copyright 1999, 2000 James R. Bruce
    School of Computer Science, Carnegie Mellon University
  -------------------------------------------------------------------------
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  =========================================================================*/

#ifndef __WIN_H__
#define __WIN_H__

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>

#include <stdio.h>

#ifndef RGB_STRUCT
#define RGB_STRUCT
struct rgb{
  unsigned char red,green,blue;
};
#endif

//==== Graphics/Display Routines =====================================//

class xwindows{
  friend class xdrawable;
  friend class xpixmap;
  friend class xwin;

  Display *disp;
  int screen;
  int depth;
  Window root;
  Visual *vis;

  Window win;
  GC gc;

  int red_shift,green_shift,blue_shift;

public:
  bool initialize();
  void close();
  xwin createWindow(int width,int height,char *title);
  // xpixmap createPixmap(int width,int height);

  bool checkEvent(XEvent &xev);
  void getEvent(XEvent &xev);
  void flush();
};

class xdrawable{
protected:
  xwindows *xw;
  union{
    Drawable draw;
    Window win;
    Pixmap pix;
  };
  Colormap cmap;
  GC gc;
public:
  void setColor(rgb color);
  void setColor(int red,int green,int blue);
  void setGray(int gray);

  void fillRectangle(int x,int y,int w,int h);
  void fillRectangle(XRectangle r);
  void fillCircle(int x,int y,int r);
  void fillPolygon(XPoint *pts,int num);

  void drawRectangle(int x,int y,int w,int h);
  void drawRectangle(XRectangle r);
  void drawCircle(int x,int y,int r);
  void drawLine(int x1,int y1,int x2,int y2);
  void drawLines(XPoint *pts,int num);

  void copyArea(xdrawable &src,int src_x,int src_y,
		int w,int h,int dest_x,int dest_y);
  void print(int x,int y,char *str);

  bool loadImage(char *filename);

  void flush()
    {xw->flush();}
};

class xpixmap : public xdrawable{
  friend class xwin;
public:
  void initialize(xwin *nxw,int width,int height);
  void close();
};

class xwin : public xdrawable{
  friend class xpixmap;
public:
  void initialize(xwindows *nxw,int width,int height,const char *title);
  void close();

  void setName(const char *name)
    {XStoreName(xw->disp,win,name);}
  void clearArea(int x,int y,int w,int h,bool exposures)
    {XClearArea(xw->disp,win,x,y,w,h,exposures);}

  xpixmap createPixmap(int width,int height);
  void setBackground(xpixmap &p);

  /*
  XImage *newImage(int w,int h);
  void deleteImage(XImage *img)
    {XDestroyImage(img);}
  void putImage(XImage *img,int x,int y)
    {XPutImage(xw->disp,win,gc,img,0,0,x,y,img->width,img->height);}
  */
};

#endif
// __WIN_H__

Generated by GNU enscript 1.6.2.