[mousetrap/gnome3-wip] Added Python 3.3 support



commit cb21fd556064391dcf54e8a44b234741a167da3f
Author: Kevin Brown <kbrown rediker com>
Date:   Sun Feb 2 13:05:18 2014 -0500

    Added Python 3.3 support
    
    This fixes many of the old-style relative imports that were left
    within the code.  These imports are not valid in Python3, and have
    been replaced by absolute imports as well as new-style relative
    imports.  The incorrect imports were replaced by absolute imports,
    as they are the most consistent and are unlikely to change in the
    future.
    
    In a few cases, module were moved and needed to be imported with
    an alias to maintain backwards compatibility.  We should consider
    moving these imports into a `compat` file, to make it easier to
    fix these imports across the entire application.

 src/mousetrap/app/lib/httpd.py           |   13 ++++++-
 src/mousetrap/app/lib/settings.py        |    7 +++-
 src/mousetrap/app/main.py                |    8 +++-
 src/mousetrap/app/ui/dialogs.py          |    2 +-
 src/mousetrap/app/ui/main.py             |    4 +-
 src/mousetrap/app/ui/scripts/__init__.py |   51 +++++++++++++++++++++++------
 src/mousetrap/app/ui/settings_gui.py     |    4 +-
 src/mousetrap/ocvfw/_ocv.py              |   52 ++++++++++++++++++-----------
 src/mousetrap/ocvfw/dev/camera.py        |   31 ++++++++++++++---
 src/mousetrap/ocvfw/idm/color.py         |    2 +-
 10 files changed, 127 insertions(+), 47 deletions(-)
---
diff --git a/src/mousetrap/app/lib/httpd.py b/src/mousetrap/app/lib/httpd.py
index f26949d..0e62cc2 100644
--- a/src/mousetrap/app/lib/httpd.py
+++ b/src/mousetrap/app/lib/httpd.py
@@ -29,8 +29,17 @@ __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
 __license__   = "GPLv2"
 
 from . import mouse
-import thread
-import BaseHTTPServer
+
+try:
+    import thread
+except ImportError:
+    # TODO: Look into using the `threading` module instead.
+    import _thread as thread
+
+try:
+    import BaseHTTPServer
+except ImportError:
+    from http import server as BaseHTTPServer
 
 from .. import debug
 from .. import environment as env
diff --git a/src/mousetrap/app/lib/settings.py b/src/mousetrap/app/lib/settings.py
index a6332b8..88aa459 100644
--- a/src/mousetrap/app/lib/settings.py
+++ b/src/mousetrap/app/lib/settings.py
@@ -28,7 +28,12 @@ __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
 __license__   = "GPLv2"
 
 import os
-import ConfigParser as configparser #FIXME should be configparser
+
+try:
+    import configparser
+except ImportError:
+    import ConfigParser as configparser
+
 import mousetrap.app.environment as env
 
 class Settings( configparser.ConfigParser ):
diff --git a/src/mousetrap/app/main.py b/src/mousetrap/app/main.py
index 3f9e27e..ebee204 100644
--- a/src/mousetrap/app/main.py
+++ b/src/mousetrap/app/main.py
@@ -1,3 +1,7 @@
+# This will for all imports to be absolute, which will allow compatibility with
+# Python 2.5+ and Python 3
+from __future__ import absolute_import
+
 # -*- coding: utf-8 -*-
 
 # MouseTrap
@@ -37,9 +41,9 @@ import sys
 sys.argv[0] = "mousetrap"
 
 from gi.repository import GObject
-import debug
+from mousetrap.app import debug
 import getopt
-import environment as env
+from mousetrap.app import environment as env
 
 from mousetrap.ocvfw import pocv
 
diff --git a/src/mousetrap/app/ui/dialogs.py b/src/mousetrap/app/ui/dialogs.py
index 6cb2022..591c82a 100644
--- a/src/mousetrap/app/ui/dialogs.py
+++ b/src/mousetrap/app/ui/dialogs.py
@@ -25,7 +25,7 @@ __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
 __license__   = "GPLv2"
 
 from gi.repository import Gtk
-from i18n import _
+from mousetrap.app.ui.i18n import _
 
 def addLabelMessage( dialog, message ):
     """
diff --git a/src/mousetrap/app/ui/main.py b/src/mousetrap/app/ui/main.py
index 936657a..e120a11 100644
--- a/src/mousetrap/app/ui/main.py
+++ b/src/mousetrap/app/ui/main.py
@@ -28,8 +28,8 @@ from gi.repository import Gdk
 from gi.repository import GObject
 from gi.repository import Gtk
 from gi.repository import GdkPixbuf
-import dialogs
-import settings_gui
+from mousetrap.app.ui import dialogs
+from mousetrap.app.ui import settings_gui
 import mousetrap.app.debug as debug
 import mousetrap.app.environment as env
 from mousetrap.app.addons import cpu
diff --git a/src/mousetrap/app/ui/scripts/__init__.py b/src/mousetrap/app/ui/scripts/__init__.py
index f765fd6..d3f76c8 100644
--- a/src/mousetrap/app/ui/scripts/__init__.py
+++ b/src/mousetrap/app/ui/scripts/__init__.py
@@ -24,23 +24,54 @@ __date__      = "$Date$"
 __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
 __license__   = "GPLv2"
 
-import re
-import os
 
 def get_scripts_list():
     """
-    Checks the addons folder and gets the
-    list of present addons.
+    Generate a list of preset scripts that can be used with MouseTrap.
 
-    Arguments:
-    - self: The main object pointer.
+    This will find any scripts in the current directory that only contain a mix
+    of letters (of any case) or numbers that are python files.
     """
 
-    reg = re.compile(r'([A-Za-z0-9]+)\.py$', re.DOTALL)
+    import re
+    import os
+
+    valid_script = re.compile(r'([A-Za-z0-9]+)\.py$', re.DOTALL)
     dirname = os.path.dirname(__file__)
-    return [ mod[0] for mod in [ reg.findall(f) for f in os.listdir("%s/" % dirname) if "__init__" not in f] 
if mod ]
+
+    # Get all files in the current directory
+    current_directory = os.listdir("%s/" % dirname)
+
+    # Filter all of the files in the current directory to see if the match the
+    # format of script files
+    scripts = [valid_script.search(file_name) for file_name in current_directory if "_init__" not in 
file_name]
+
+    # Get the name of the current module, this will be used for reconstructing
+    # the full import path to scripts that are found
+    current_module = __name__
+
+    return ["%s.%s" % (current_module, name.group(1)) for name in scripts if name]
 
 
 def get_script_class(script_name):
-    script = __import__(script_name, globals(), locals())
-    return getattr(script, "ScriptClass")
\ No newline at end of file
+    """
+    Get the class for script based on the name when given as a dotted path.
+
+    For backwards compatibility, this will be able to import scripts when given
+    only the name of the script, and not the full dotted path.
+    """
+
+    script_path = script_name.split(".")
+
+    # Determine if the full dotted path or just the name was given
+    if len(script_path) > 1:
+        # If the full dotted path was given, import the script from it's
+        # base module
+        script = __import__(".".join(script_path), globals(), locals(),
+                            script_path[-2])
+    else:
+        # If only the name of script was given, import it as though it is
+        # located relative to the current directory
+        script = __import__(script_name, globals(), locals())
+
+    return getattr(script, "ScriptClass")
diff --git a/src/mousetrap/app/ui/settings_gui.py b/src/mousetrap/app/ui/settings_gui.py
index 001d911..543bc4c 100644
--- a/src/mousetrap/app/ui/settings_gui.py
+++ b/src/mousetrap/app/ui/settings_gui.py
@@ -30,8 +30,8 @@ __license__   = "GPLv2"
 
 from gi.repository import GObject
 from gi.repository import Gtk
-import dialogs
-from i18n import _
+from mousetrap.app.ui import dialogs
+from mousetrap.app.ui.i18n import _
 from mousetrap.ocvfw import pocv
 import mousetrap.app.environment as env
 
diff --git a/src/mousetrap/ocvfw/_ocv.py b/src/mousetrap/ocvfw/_ocv.py
index d4319f2..90de863 100644
--- a/src/mousetrap/ocvfw/_ocv.py
+++ b/src/mousetrap/ocvfw/_ocv.py
@@ -24,10 +24,15 @@ __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli"
 __license__   = "GPLv2"
 
 import time
-import debug
-import commons as co
+from mousetrap.ocvfw import debug
+from mousetrap.ocvfw import commons as co
 import cv2 #remove
-import cv2.cv as cv
+
+try:
+    import cv2.cv as cv
+except ImportError:
+    import cv2 as cv
+
 import numpy
 import array
 
@@ -158,7 +163,7 @@ class OcvfwBase:
                 self.grey,
                 self.img_lkpoints["current"],
                 (20, 20), (0,0),
-                (cv.CV_TERMCRIT_ITER | cv.CV_TERMCRIT_EPS, 20, 0.03))
+                (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 20, 0.03))
 
             point.set_opencv( cvPoint )
             self.img_lkpoints["points"].append(point)
@@ -207,7 +212,7 @@ class OcvfwBase:
             None, #error vector
             (20, 20), #winSize
             2, #maxLevel
-            (cv2.TERM_CRITERIA_MAX_ITER|cv2.TERM_CRITERIA_EPS, 20, 0.03), #criteria
+            (cv2.TERM_CRITERIA_MAX_ITER | cv2.TERM_CRITERIA_EPS, 20, 0.03), #criteria
             cv2.OPTFLOW_USE_INITIAL_FLOW #flags
             )
 
@@ -222,12 +227,19 @@ class OcvfwBase:
         new_points = []
 
         for point in self.img_lkpoints["current"]:
+            # Make sure the next point is in the list of points
+            # This can happen because of a race condition when finding points
+            if counter >= len(self.img_lkpoints["points"]):
+                continue
 
-            # this point is a correct point
+            # Extract the x/y values for the point
+            point_x, point_y = point
+
+            # Update the corresponding point with the updated values
             current = self.img_lkpoints["points"][counter]
-            current.set_opencv((int(point.item(0)),int(point.item(1))))
+            current.set_opencv((point_x, point_y))
 
-            new_points.append( point )
+            new_points.append(point)
 
             setattr(current.parent, current.label, current)
 
@@ -237,9 +249,6 @@ class OcvfwBase:
             # increment the counter
             counter += 1
 
-
-        #debug.debug( "ocvfw", "cmShowLKPoints: Showing %d LK Points" % counter )
-
         # set back the self.imgPoints we keep
         self.img_lkpoints["current"] = new_points
 
@@ -294,15 +303,18 @@ class OcvfwPython(OcvfwBase):
     This Backend uses normal opencv python bindings.
     """
 
-    co.cv = __import__("cv",
-                        globals(),
-                        locals(),
-                        [''])
-
-    co.hg = __import__("cv",
-                        globals(),
-                        locals(),
-                        ['']) #should be removed
+    try:
+        co.cv = __import__("cv",
+                           globals(),
+                           locals(),
+                           [''])
+    except ImportError:
+        co.cv = __import__("cv2",
+                           globals(),
+                           locals(),
+                           [''])
+
+    co.hg = co.cv
 
     def __init__( self ):
         """
diff --git a/src/mousetrap/ocvfw/dev/camera.py b/src/mousetrap/ocvfw/dev/camera.py
index ffb0a72..1e64dfb 100644
--- a/src/mousetrap/ocvfw/dev/camera.py
+++ b/src/mousetrap/ocvfw/dev/camera.py
@@ -284,20 +284,39 @@ class Capture(object):
 
     def color(self, new_color, channel=None, copy=False):
         """
-        Changes the image's color.
+        Changes the image's color from one color mode to another.
 
-        Arguments:
-        - self: The main object pointer.
-        - color: The new color.
+        The new color mode to be used must be passed in, or the color mode
+        will not be changed and the previous color will be returned.
 
-        returns self.color if color == None
+        Optionally, the channel to be used can be passed in as an argument.  If
+        a channel is not passed in, the channel for the new color mode will be
+        detected and used instead.
+
+        Optionally, the converted image can also be used as the internal image.
+        By default, the internal image is not altered and the converted image
+        is returned.
         """
 
         channel = channel if channel != None else co.get_ch(new_color)
 
         if new_color:
+            # Create the base key for converting between two color modes
+            color_convert = "%s2%s" % (self.__color, new_color)
+
+            # By default, assume that the key format is `color_[convert_code]`
+            color_key = "color_%s" % color_convert
+
+            # Check that the key for converting between the two color modes
+            # is present in the conversion dictionary
+            if not color_key in self.__color_int:
+                # If the color conversion key is not present, default to the
+                # legacy OpenCV key naming convention
+                color_key = "cv_%s" % color_convert
+
             tmp = self.__images_cn[channel]
-            tmp = cv2.cvtColor(self.__image, self.__color_int['cv_%s2%s' % (self.__color, new_color) ])
+            tmp = cv2.cvtColor(self.__image, self.__color_int[color_key])
+
             self.__color = new_color
             self.__ch = channel
 
diff --git a/src/mousetrap/ocvfw/idm/color.py b/src/mousetrap/ocvfw/idm/color.py
index 746c2e9..0eab8fa 100644
--- a/src/mousetrap/ocvfw/idm/color.py
+++ b/src/mousetrap/ocvfw/idm/color.py
@@ -114,7 +114,7 @@ class Module(object):
         global a_settings
 
         self.debugLevel = self.ctr.cfg.getint("main", "debugLevel")
-        print self.debugLevel
+        print(self.debugLevel)
 
         # If the dict is empty then
         # use the default settings defined in a_settings


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]