File: core.py

package info (click to toggle)
gamera 1:3.4.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 15,912 kB
  • sloc: xml: 122,324; cpp: 50,730; python: 35,044; ansic: 258; makefile: 114; sh: 101
file content (747 lines) | stat: -rw-r--r-- 27,269 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*-
# vim: set tabstop=3 shiftwidth=3 expandtab:
#
# Copyright (C) 2001-2005 Ichiro Fujinaga, Michael Droettboom, Karl MacMillan
#               2009-2010 Christoph Dalitz
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


"""This module contains the core parts of Gamera including all of the image
representation types, the dimension types, abstract mappings of values
to regions on an image (ImageMap), image loading, and feature generation.
 
Everything in this module can be used without the Gui to facilitate
batch processing. It contains the following classes:

ImageBase - common functionality for all of the image types.
Image - images.
SubImage - a view on part of an image.
Cc - a non-rectangular view of part of an image (the view area
     is marked with labels in the image).
MlCc - the same as Cc but with multiple labels

Additionally this module contains the following functions:

load_image - load an image from a file.
image_info - get information about an image file.
display_multi - display a list of images in a grid-like window.
init_gamera - parse the gamera options and load all of the plugins.
"""

# Python standard library
from array import array
from types import *

# import the classification states
try:
   from gameracore import UNCLASSIFIED, AUTOMATIC, HEURISTIC, MANUAL
except ImportError:
   raise ImportError("Couldn't import the core of Gamera.  Are you trying to start the GUI from the root of the Gamera source tree?  This confuses the Python module loading mechanism.")
# import the pixel types
from gameracore import ONEBIT, GREYSCALE, GREY16, RGB, FLOAT, COMPLEX
from enums import ALL, NONIMAGE
# import the storage types
from gameracore import DENSE, RLE
# import some of the basic types
from gameracore import ImageData, Size, Dim, Point, \
     FloatPoint, Rect, Region, RegionMap, ImageInfo, RGBPixel
# import confidence types
from gameracore import CONFIDENCE_DEFAULT, CONFIDENCE_KNNFRACTION, CONFIDENCE_LINEARWEIGHT, CONFIDENCE_INVERSEWEIGHT, CONFIDENCE_NUN, CONFIDENCE_NNDISTANCE, CONFIDENCE_AVGDISTANCE
# import gamera.gameracore for subclassing
import gameracore
from gamera.gui import has_gui

# from gamera.classify import *
import paths, util    # Gamera-specific
from config import config

class SegmentationError(Exception):
   pass

######################################################################

def load_image(filename, compression = DENSE):
   """**load_image** (FileOpen *filename*, Choice *storage_format* = ``DENSE``)

Load an image from the given filename.  At present, TIFF and PNG files are
supported.

*storage_format*
  The type of `storage format`__ to use for the resulting image.

.. __: image_types.html#storage-formats"""
   from gamera import plugin
   import os.path
   methods = plugin.methods_flat_category("File")
   methods = [y for x, y in methods if x.startswith("load") and x != "load_image"]

   if len(methods) == 0:
      raise RuntimeError("There don't seem to be any imported plugins that can load files.  Try running init_gamera(), or explicitly loading the plugins that support file loading, such as tiff_support and png_support.")

   try:
      filename = filename.encode('utf8')
   except Exception:
      pass
   # First, try being smart by loading by extension
   for method in methods:
      for ext in method.exts:
         if os.path.splitext(filename)[1].lower() == ext.lower():
            try:
               image = method.__call__(filename, compression)
            except Exception:
               pass
            else:
               return image

   # Then just try all options
   for method in methods:
      try:
         image = method.__call__(filename, compression)
      except Exception:
         pass
      else:
         return image

   raise IOError("'%s' could not be loaded." % filename)

def save_image(image, filename):
   """**save_image** (Image(ALL) *image*, String *filename*)

Saves an image to a file.  The file type is automatically
determined from the extension.
"""
   from gamera import plugin
   import os.path
   methods = plugin.methods_flat_category("File")
   methods = [y for x, y in methods if x.startswith("save") and x != "save_image"]

   if len(methods) == 0:
      raise RuntimeError("There don't seem to be any imported plugins that can save files.  Try running init_gamera(), or explicitly loading the plugins that support file saving, such as tiff_support and png_support.")

   for method in methods:
      for ext in method.exts:
         if os.path.splitext(filename)[1][1:].lower() == ext.lower():
            method.__call__(image, filename)
            return
              
   # For backward compatibility, fall back to tiff if
   # we can't automatically determine the filetype by
   # the extension
   from gamera.plugins import _tiff_support
   _tiff_support.save_tiff(image, filename)

def nested_list_to_image(l, t=-1):
   from gamera.plugins import image_utilities
   return image_utilities.nested_list_to_image(l, t)

def image_info(filename):
   """ImageInfo **image_info** (FileOpen *filename*)

Retrieve information about an image file without loading it.

The result is an ImageInfo__ object about a given filename. The ImageInfo
object gives information such as the type (color, greyscale, onebit),
the bit-depth, resolution, size, etc.

.. __: gamera.core.ImageInfo.html"""
   import tiff_support, png_support
   try:
      return tiff_support.tiff_info(filename)
   except RuntimeError:
      try:
         return png_support.PNG_info(filename)
      except RuntimeError:
         raise IOError("File is not a PNG or TIFF file")

def display_multi(list):
   """**display_multi** (ImageList *list*)

Displays a list of images in a grid-like window.  This function has
no effect if the `Gamera GUI`__ is not running.

.. __: gui.html"""
   # If it's not a list, we'll get errors, so make it one
   if not util.is_sequence(list):
      list = [list]
   if not len(list):
      raise ValueError("Given list is empty.")
   return has_gui.gui.ShowImages(list)

# Used to cache the list of all features
all_features = None

class ImageBase:
   """Base class for all of the image objects. This class contains
   common functionality for all of the image types including
   the necessary infrastructure to support dynamically added plugins."""
   # Stores the categorized set of methods.  Bears no relationship
   # to __methods__
   methods = {}

   class Properties(dict):
      def __getitem__(self, attr):
         return dict.get(self, attr, None)
      def __getattr__(self, attr):
         return self.__getitem__(attr)
      def __setattr__(self, attr, value):
         return dict.__setitem__(self, attr, value)
   
   def __init__(self):
      self.name = "Untitled"
      self._display = None
      self.last_display = None
      self.properties = self.__class__.Properties()
      # Keep a list of tuples of (feature_name, feature_function) that
      # have already been generated for this Image
      self.feature_functions = [[], 0]

   def __del__(self):
      if self._display:
         self._display.close()

   def pixel_type_name(self):
      """String **pixel_type_name** ()

Returns a string representing the pixel type of the image. Intended
primarily for display (GUI) purposes, since using the integer values
in ``Image.data.pixel_type`` is more efficient.

See `pixel types`_ for more information."""
      return util.get_pixel_type_name(self.data.pixel_type)
   pixel_type_name = property(pixel_type_name, doc=pixel_type_name.__doc__)

   _storage_format_names = {DENSE:  "Dense",
                            RLE:    "RLE"}
   
   def storage_format_name(self):
      """String **storage_format_name** ()

Returns a string representing the storage format of the image.
Intended primarily for display (GUI) purposes, since using the integer
values in ``Image.data.storage_format`` is more efficient.

See `storage formats`_ for more information."""
      return self._storage_format_names[self.data.storage_format]
   storage_format_name = property(storage_format_name, doc=storage_format_name.__doc__)

   def load_image(filename, compression=DENSE):
      """Load an image from the given filename.  At present, TIFF and PNG files are
supported.

*storage_format*
  The type of `storage format`__ to use for the resulting image.

.. __: image_types.html#storage-formats"""
      return load_image(filename, compression)
   load_image = staticmethod(load_image)

   def save_image(self, filename):
      """Saves an image to a file.  The file type is automatically
determined from the extension."""
      return save_image(self, filename)

   def memory_size(self):
      """Int **memory_size** ()

Returns the memory used by the underlying data of the image (in
bytes).  Note that this memory may be shared with other image views on
the same data."""
      return self.data.bytes
   memory_size = property(memory_size, doc=memory_size.__doc__)

   def set_display(self, _display):
      self._display = _display

   def display(self, title=None):
      """Displays the image in its own window.  (See `Using the Gamera GUI`__).  If the GUI
process is not running, this method has no effect.

.. __: gui.html

.. image:: images/display.png"""
      if self.data.pixel_type in (COMPLEX, FLOAT):
         conversion = "to_greyscale"
      else:
         conversion = None
      if self._display:
         self._display.set_image(self, conversion)
      else:
         if title == None:
            self.set_display(
               has_gui.gui.ShowImage(self, self.name, conversion,
                                     owner=self))
         else:
            self.set_display(
               has_gui.gui.ShowImage(self, title, conversion,
                                     owner=self))
      self.last_display = "normal"
      return self._display

   def display_ccs(self):
      """Displays the image in its own window.  (See `Using the Gamera GUI`__).
Each connected component is assigned to one of eight colors.  This
display can be used to see how connected component analysis performs
on a given image.  Uses color_ccs_ under the hood.

.. __: gui.html
.. _color_ccs: gui_support.html#color-ccs

.. note: Connected component analysis must already be performed on the image
   (using cc_analysis_, for example) in order for this to work.

.. _cc_analysis: segmentation.html#cc-analysis

.. image:: images/display_ccs.png"""
      if self._display:
         self._display.set_image(self, "color_ccs")
      else:
         self.set_display(
            has_gui.gui.ShowImage(self, self.name, "color_ccs",
                          owner=self))
      self.last_display = "normal"
      return self._display

   def display_false_color(self):
      """Displays the image using false coloring.  (See false_color_).

.. _false_color: color.html#false-color

.. image:: images/display_false_color.png"""
      if self._display:
         self._display.set_image(self, "false_color")
      else:
         self.set_display(
            has_gui.gui.ShowImage(self, self.name, "false_color",
                          owner=self))
      self.last_display = "normal"
      return self._display

   def unclassify(self):
      """Sets the image back to an UNCLASSIFIED state.  Use this
when you are not longer sure of the identity of the image and you
want an automatic classifier to reclassify."""
      self.id_name = []
      self.confidence = {}
      self.classification_state = UNCLASSIFIED

   def classify_manual(self, id_name):
      """Classifies the image as the value *id_name* and sets the state
to MANUAL.  Use this method when an end user has classified this glyph.
This method also unsets the *confidence* map.

*id_name*
  Can come in one of two forms:

    **string**
       image is classified using the given ``.``-delimited class name.
       As in this case no confidence is provided, it is set to one.
    **list of tuples**
       A list of tuples where each tuple is the pair (*confidence*, *class_name*).

       *confidence*
         A value in range (0, 1), where 0 is uncertain and 1 is certain.
       *class_name*
         A ``.``-delimited class name."""
      if util.is_string_or_unicode(id_name):
         id_name = [(1.0, id_name)]
      elif type(id_name) != ListType:
         raise TypeError("id_name must be a string or a list")
      self.id_name = id_name
      self.confidence = {}
      self.classification_state = MANUAL

   def classify_automatic(self, id_name):
      """Classifies the image as the value *id_name* and sets the state
to AUTOMATIC.  Use this method when an automatic classifier has classified
this glyph. Note that this method does not touch the *confidence* map for
the main id; this must be set separately.

*id_name*
  Can come in one of two forms:

    **string**
       image is classified using the given ``.``-delimited class name.
       As in this case no confidence is provided, it is set to zero.
    **list of tuples**
       A list of tuples where each tuple is the pair (*confidence*, *class_name*).

       *confidence*
         A value in range (0, 1), where 0 is uncertain and 1 is certain.
       *class_name*
         A ``.``-delimited class name."""
      if util.is_string_or_unicode(id_name):
         id_name = [(0.0, id_name)]
      elif type(id_name) != ListType:
         raise TypeError("id_name must be a string or a list")
      self.id_name = id_name
      self.classification_state = AUTOMATIC

   def classify_heuristic(self, id_name):
      """Classifies the image as the value *id_name* and sets the state
to HEURISTIC.  Use this method when a heuristic process has classified
this glyph. This method also unsets the *confidence* map.

*id_name*
  Can come in one of two forms:

    **string**
       image is classified using the given ``.``-delimited class name.
       As in this case no confidence is provided, it is set to 0.5.
    **list of tuples**
       A list of tuples where each tuple is the pair (*confidence*, *class_name*).

       *confidence*
         A value in range (0, 1), where 0 is uncertain and 1 is certain.
       *class_name*
         A ``.``-delimited class name."""
      if util.is_string_or_unicode(id_name):
         id_name = [(0.5, id_name)]
      elif type(id_name) != ListType:
         raise TypeError("id_name must be a string or a list")
      self.id_name = id_name
      self.confidence = {}
      self.classification_state = HEURISTIC

   def get_main_id(self):
      """Returns the primary class name assigned to the image.

If the image is unclassified, the result is 'UNCLASSIFIED'.
"""
      if self.classification_state == UNCLASSIFIED or not len(self.id_name):
         return 'UNCLASSIFIED'
      return self.id_name[0][1]

   def get_confidence(self, confidence_type=None):
      """Returns the confidence of the primary class assigned to the image.
*confidence_type* can be one of the predefined `confidence measures`__, e.g.

.. __: classify.html#confidence

.. code:: Python

   from gamera.gameracore import CONFIDENCE_KNNFRACTION
   glyph.get_confidence(CONFIDENCE_KNNFRACTION)

When no *confidence_type* is given, the default confidence stored with
``id_name[0]`` is returned. If the image is unclassified, -1.0 is returned.

For details about the confidence computation in Gamera, see

   C. Dalitz: `Reject Options and Confidence Measures for kNN Classifiers.`__
   In C. Dalitz (Ed.): "Document Image Analysis with the Gamera Framework."
   Schriftenreihe des Fachbereichs Elektrotechnik und Informatik,
   Hochschule Niederrhein, vol. 8, pp. 16-38, Shaker Verlag (2009).

.. __: http://lionel.kr.hsnr.de/~dalitz/data/publications/sr09-knn-rejection.pdf
"""
      if self.classification_state == UNCLASSIFIED:
         return -1.0
      if not confidence_type:
         return self.id_name[0][0]
      else:
         if self.confidence.has_key(confidence_type):
            return self.confidence[confidence_type]
         else:
            raise ValueError("Given confidence %i not stored in confidence map of image" % confidence_type)

   def has_id_name(self, name):
      """Returns ``True`` if the image has the given classification ``name``."""
      for confidence, id_name in self.id_name:
         if name == id_name:
            return True
      return False

   def subimage(self, *args, **kwargs):
      """Creates a new view on existing data.

There are a number of ways to create a subimage:

   - subimage(Point *upper_left*, Point *lower_right*)
      
   - subimage(Point *upper_left*, Size *size*)

   - subimage(Point *upper_left*, Dim *dim*)

   - subimage(Rect *rectangle*)

Changes to subimages will affect all other subimages viewing the same data.

.. warning:: The *upper_left* and *lower_right* coordinates are absolute and
   not relative to the image origin. Hence, for all practical use cases,
   you must add the image offset to the coordinates, e.g.

   .. code:: Python

      subimg = image.subimage(Point(p.x + image.offset_x, p.y + image.offset_y), dim)
      # or, equivalently:
      subimg = image.subimage(p + image.ul, dim)

"""
      if hasattr(self, "label"):
         return Cc(self, self.label, *args, **kwargs)
      if self.__class__.__name__=="MlCc": #seems more robust to me
         return self.copy(*args, **kwargs)
      else:
         return SubImage(self, *args, **kwargs)

   def _get_feature_vector_size(cls, functions):
      num_features = 0
      for name, function in functions:
          num_features += function.return_type.length
      return num_features
   _get_feature_vector_size = classmethod(_get_feature_vector_size)

   def get_feature_functions(cls, features='all'):
      from gamera import plugin
      global all_features
      if all_features is None:
         all_features = plugin.methods_flat_category('Features', ONEBIT)
         all_features.sort()
      if features == 'all' or features is None:
         functions = all_features
         return functions, cls._get_feature_vector_size(functions)
      features = util.make_sequence(features)
      all_strings = True
      for feature in features:
         if not util.is_string_or_unicode(feature):
            all_strings = False
            break
      if not all_strings:
         import plugin
         all_functions = False
         if (type(features) == tuple and
             len(features) == 2 and
             type(features[0]) == list and
             type(features[1]) == int):
            all_functions = True
            for feature in features[0]:
               if not (type(feature) == tuple and
                       util.is_string_or_unicode(feature[0]) and
                       issubclass(feature[1], plugin.PluginFunction)):
                  all_functions = False
                  break
         if not all_functions:
            raise ValueError(
               "'%s' is not a valid way to specify a list of features."
               % str(features))
         else:
            return features
      else:
         features.sort()
         functions = []
         for feature in features:
            found = 0
            for i in all_features:
               if feature == i[0]:
                  functions.append(i)
                  found = 1
                  break
            if not found:
               raise ValueError("'%s' is not a known feature function." % feature)
         functions.sort()
         return functions, cls._get_feature_vector_size(functions)
   get_feature_functions = classmethod(get_feature_functions)

   def to_xml(self, stream=None):
      """
      Returns a string containing the Gamera XML representation of the image.
      (See the Gamera XML DTD in ``misc/gamera.dtd`` in the source distribution.)
      """
      import gamera_xml
      return gamera_xml.WriteXML(glyphs=[self]).write_stream(stream)

   def to_xml_filename(self, filename):
      """
      Saves the Gamera XML representation of the image to the given *filename*.
      (See the Gamera XML DTD in ``misc/gamera.dtd`` in the source distribution.)
      """
      import gamera_xml
      return gamera_xml.WriteXML(glyphs=[self]).write_filename(filename)

   def set_property(self, name, value):
      self.property[name] = value

   def get_property(self, name):
      return self.property[name]

######################################################################

class Image(gameracore.Image, ImageBase):
   def __init__(self, *args, **kwargs):
      ImageBase.__init__(self)
      gameracore.Image.__init__(self, *args, **kwargs)
   __init__.__doc__ = gameracore.Image.__doc__

   def __del__(self):
      if self._display:
         self._display.close()

######################################################################

class SubImage(gameracore.SubImage, ImageBase):
   def __init__(self, *args, **kwargs):
      ImageBase.__init__(self)
      gameracore.SubImage.__init__(self, *args, **kwargs)
   __init__.__doc__ = gameracore.SubImage.__doc__

   def __del__(self):
      if self._display:
         self._display.close()


######################################################################

class Cc(gameracore.Cc, ImageBase):
   def __init__(self, *args, **kwargs):
      ImageBase.__init__(self)
      gameracore.Cc.__init__(self, *args, **kwargs)
   __init__.__doc__ = gameracore.Cc.__doc__

   def __del__(self):
      if self._display:
         self._display.close()
   
   def display_context(self):
      """**display_context** ()

Displays the Cc in context, by opening a window displaying the underlying
image with the given Cc highlighted.  This method has no effect if the GUI
is not running.
"""
      image = self.parent()
      if self._display:
         self._display.set_image(image)
      else:
         self.set_display(
            has_gui.gui.ShowImage(image,
                          "Connected Component",
                          owner=self))
      self._display.highlight_cc(self)
      self._display.focus(self)
      self.last_display = "context"

class MlCc(gameracore.MlCc, ImageBase):
   def __init__(self, *args, **kwargs):
      ImageBase.__init__(self)
      gameracore.MlCc.__init__(self, *args, **kwargs)
   __init__.__doc__ = gameracore.MlCc.__doc__

   def __del__(self):
      if self._display:
         self._display.close()

# this is a convenience function for using in a console
_gamera_initialised = False
def _init_gamera():
   global _gamera_initialised
   if _gamera_initialised:
      return
   _gamera_initialised = True
   import plugin, gamera_xml, sys
   from gamera.args import NoneDefault
   # Create the default functions for the menupl
   for method in (
      plugin.PluginFactory(
         "load_image", "File", plugin.ImageType(ALL, "image"),
         plugin.ImageType(ALL), plugin.Args([plugin.FileOpen("filename", extension=util.load_image_file_extension_finder)])),
      plugin.PluginFactory(
         "save_image", "File", None,
         plugin.ImageType(ALL), plugin.Args([plugin.FileSave("filename", extension=util.save_image_file_extension_finder)])),
      plugin.PluginFactory(
         "display", "Displaying", None, plugin.ImageType(ALL), None),
      plugin.PluginFactory(
         "display_ccs", "Displaying", None, plugin.ImageType([ONEBIT]),
         None),
      plugin.PluginFactory(
         "display_false_color", "Displaying", None,
         plugin.ImageType([GREYSCALE, FLOAT]),
         None),
      plugin.PluginFactory(
         "classify_manual", "Classification", None,
         plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])),
      plugin.PluginFactory(
         "classify_heuristic", "Classification", None,
         plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])),
      plugin.PluginFactory(
         "classify_automatic", "Classification", None,
         plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])),
      plugin.PluginFactory(
         "unclassify", "Classification", None,
         plugin.ImageType([ONEBIT]), None),
      plugin.PluginFactory(
         "get_main_id", "Classification", plugin.String("id"),
         plugin.ImageType([ONEBIT]), None),
      plugin.PluginFactory(
         "get_confidence", "Classification", plugin.Float("confidence"),
         plugin.ImageType([ONEBIT]), plugin.Args([plugin.Choice("confidence_type", default=NoneDefault)])),
      plugin.PluginFactory(
         "has_id_name", "Classification", plugin.Check("result"),
         plugin.ImageType([ONEBIT]), plugin.Args([plugin.String("id")])),
      plugin.PluginFactory(
         #"subimage", "Utility", plugin.Check("result"),
         "subimage", "Utility", plugin.ImageType(ALL),
         plugin.ImageType(ALL), plugin.Args([plugin.Point("upper_left"),
                                             plugin.Point("lower_right")])),
      plugin.PluginFactory(
         "to_xml", "XML", plugin.String('xml'),
         plugin.ImageType([ONEBIT]), None),
      plugin.PluginFactory(
         "to_xml_filename", "XML", None, plugin.ImageType([ONEBIT]),
         plugin.Args([
      plugin.FileSave("filename", extension=gamera_xml.extensions)]))
      ):
      method.register()
   try:
      verbose = config.get("verbosity_level")
   except Exception:
      verbose = 0
   paths.import_directory(paths.plugins, globals(), locals(), verbose)
   sys.path.append(".")

import sys
if sys.platform == 'win32':
   # Windows doesn't generally keep the console window open, making it difficult to
   # diagnose fatal errors.  This catch-all should help.
   def init_gamera():
      try:
         _init_gamera()
      except Exception, e:
         print type(e)
         if not isinstance(e, SystemExit):
            import traceback
            print "Gamera made a fatal error:"
            print
            traceback.print_exc()
            print
            print "Press <ENTER> to exit."
            x = raw_input()
            sys.exit(1)
else:
   init_gamera = _init_gamera

if __name__ == "__main__":
   init_gamera()

__all__ = ("init_gamera UNCLASSIFIED AUTOMATIC HEURISTIC MANUAL "
           "ONEBIT GREYSCALE GREY16 RGB FLOAT COMPLEX ALL DENSE RLE "
           "CONFIDENCE_DEFAULT CONFIDENCE_KNNFRACTION "
           "CONFIDENCE_LINEARWEIGHT CONFIDENCE_INVERSEWEIGHT "
           "CONFIDENCE_NUN CONFIDENCE_NNDISTANCE CONFIDENCE_AVGDISTANCE "
           "ImageData Size Dim Point FloatPoint Rect Region RegionMap "
           "ImageInfo Image SubImage Cc MlCc load_image image_info "
           "display_multi ImageBase nested_list_to_image RGBPixel "
           "save_image").split()