Example #1
0
def create_gpx(track, positions):
    f = StringIO()
    w = XMLWriter(f, 'utf-8')

    gpx = w.start('gpx', creator='Gypsum', version='1.1')

    w.start('trk')
    w.start('name')
    w.data(track.__unicode__())
    w.end('name')

    w.start('trkseg')

    for p in positions:
        w.start('trkpt', lat=str(p.latitude), lon=str(p.longitude))

        if p.altitude != None:
            w.start('ele')
            w.data(str(p.altitude))
            w.end('ele')
        w.start('time')
        w.data(datetime.datetime.strftime(p.time, '%Y-%m-%dT%H:%M:%S.%fZ'))
        w.end('time')

        w.end('trkpt')

    w.end('trkseg')

    w.end('trk')

    w.close(gpx)

    return f.getvalue()
Example #2
0
def main(sysargs):
    # settings
    args = EasyArgs(sysargs)
    cfg = EasyConfig(args.config, group="trainer")
    max_clicks = args.clicks or cfg.default_clicks
    window_name = "EagleEye Trainer"
    
    if "help" in args:
        usage()
        return 0
    
    # grab marks from args
    if len(args) > 5:
        mark_in = args[4]
        mark_out = args[5]
        
        # test integer-ness
        try: int(mark_in) and int(mark_out)
        except: 
            usage()
            return 1
        
    elif len(args) > 3:
        ret, mark_in, mark_out = marker_tool(args[1], cfg.buffer_size, window_name)
        if not ret:
            print "Not processing - exiting."
            return 1
    else:
        usage()
        return 1
    
    ## clicking time!
    cropped_total = mark_out - mark_in
    print "video cropped at:", mark_in, "to", mark_out, "- ({} frames)".format(cropped_total)
    
    # clicking function
    def on_mouse(event, x, y, flags, params):
        # left click to mark
        if event == cv2.EVENT_LBUTTONDOWN:
            params['pos'] = (x, y)
            params['status'] = Status.record
            
        # right click to skip
        elif event == cv2.EVENT_RBUTTONDOWN:
            params['status'] = Status.skip
    
    # working variables
    params = {'status': Status.wait, 'pos': None}
    write_xml = False
    textstatus = ""
    dataQuality = 0   # 0 = good, >0 = bad/potentially bad
    
    # default right side (buttonside)
    if cfg.dual_mode:
        lens = Theta.Right
        trainer_points = {Theta.Right:{}, Theta.Left:{}}
    else: # both sides otherwise
        lens = Theta.Both
        trainer_points = {Theta.Both:{}}
    
    print "Minimum reflectors: {} | Ignore Negative xyz: {}".format(cfg.min_reflectors, cfg.check_negatives)
        
    # load video (again)
    in_vid = BuffSplitCap(args[1], crop=(0,0,0,0), rotate=BuffSplitCap.r0, buff_max=cfg.buffer_size)
    in_vid.restrict(mark_in, mark_out)
    
    # load csv (with appropriate ratio)
    in_csv = Memset(args[2])
    in_csv.restrict()
    in_csv.setRatio(cropped_total)
    
    # test for marker data
    if len(in_csv.row()) < 10:
        print "This CSV contains no marker data!\nAborting."
        return 1
    
    # status
    print ""
    print "Writing to:", args[3]
    print "Number of clicks at:", max_clicks
    print ""
    
    cv2.namedWindow(window_name)
    cv2.setMouseCallback(window_name, on_mouse, params)
    
    # grab clicks (Process 2)
    while in_vid.isOpened():
        frame = in_vid.frame(side=lens)
        
        sys.stdout.write(in_vid.status() + " | Clicks {} / {}\r".format(
                                                len(trainer_points[lens]), max_clicks))
        sys.stdout.flush()
        
        # prepare CSV data, click data
        tx = float(in_csv.row()[2])
        ty = float(in_csv.row()[3])
        tz = float(in_csv.row()[4])
        rx = float(in_csv.row()[5])
        ry = float(in_csv.row()[6])
        rz = float(in_csv.row()[7])
        
        # data quality status
        visible = int(in_csv.row()[9])
        max_visible = int(in_csv.row()[8])
        
        # status text to write
        textrow = "VICON - x: {:.4f} y: {:.4f} z: {:.4f} | rx: {:.4f} ry: {:.4f} rz: {:.4f}".format(tx, ty, tz, rx, ry, rz)
        textquality = "Visible: {} , Max Visible: {}".format(visible, max_visible)
        textstatus = "{} | {}/{} clicks".format(in_vid.status(), len(trainer_points[lens]), max_clicks)
        
        if lens == Theta.Left:
            textstatus += " - back side"
        elif lens == Theta.Right:
            textstatus += " - button side"
        #else none, no lens split
        
        # if data is qualified bad, reduce timeout by one
        if dataQuality > 0:
            dataQuality -= 1
        
        if dataQuality == 0:
            dataStatus = " - Good data!!"
            dataStatus_colour = (0, 255, 0) # green
        else:
            dataStatus = " - Potentially bad data (wait {})".format(dataQuality)
            dataStatus_colour = (0, 255, 255) # yellow
        
        # Data tests
        # values must be above 0 and minimum reflectors
        if (cfg.check_negatives and (tx <= 0 or ty <= 0 or tz <= 0)) \
                or visible < cfg.min_reflectors:
            dataStatus = " - Bad data!!"
            dataStatus_colour = (0, 0, 255) # red
            
            if cfg.ignore_baddata:
                dataStatus += " Ignored."
                dataQuality = 1 + cfg.quality_delay
        
        # draw the trainer dot (if applicable)
        if in_vid.at() in trainer_points[lens]:
            cv2.circle(frame, trainer_points[lens][in_vid.at()][0], 1, cfg.dot_colour, 2)
            cv2.circle(frame, trainer_points[lens][in_vid.at()][0], 15, cfg.dot_colour, 1)
        
        # draw text and show
        displayText(frame, textrow, top=True)
        displayText(frame, textquality)
        displayText(frame, textstatus)
        displayText(frame, dataStatus, endl=True, colour=dataStatus_colour)
        
        cv2.imshow(window_name, frame)
        
        # pause for input
        while params['status'] == Status.wait:
            key = cv2.waitKey(10)
            if key == Key.esc:
                params['status'] = Status.stop
            elif key == Key.enter:
                write_xml = True
                params['status'] = Status.stop
            elif key == Key.right:
                params['status'] = Status.skip
            elif key == Key.left:
                params['status'] = Status.back
            elif key == Key.backspace:
                params['status'] = Status.remove
            elif Key.char(key, '1') and cfg.dual_mode:
                params['status'] = Status.still
                lens = Theta.Left
            elif Key.char(key, '2') and cfg.dual_mode:
                params['status'] = Status.still
                lens = Theta.Right
            
        # catch exit status
        if params['status'] == Status.stop:
            print "\nprocess aborted!"
            break
        
        # write data
        if params['status'] == Status.record \
                and len(trainer_points[lens]) != max_clicks: # TODO: does this disable recording clicks on the last frame
                
            if dataQuality == 0:
                trainer_points[lens][in_vid.at()] = (params['pos'], in_csv.row()[2:5], in_csv.row()[8:10])
            params['status'] = Status.skip
        
        # or remove it
        elif params['status'] == Status.remove \
                and in_vid.at() in trainer_points[lens]:
            del trainer_points[lens][in_vid.at()]
            print "\nremoved dot"
        
        # load next csv frame
        if params['status'] == Status.skip:
            if in_vid.next():
                in_csv.next()
            else:
                write_xml = True
                print "\nend of video: {}/{}".format(in_vid.at() -1, mark_out -1)
                break
        
        # or load previous csv frame
        elif params['status'] == Status.back:
            if in_vid.back():
                in_csv.back()
        
        # reset status
        params['status'] = Status.wait
    
    # clean up
    cv2.destroyAllWindows()
    
    
    ## write xml
    if write_xml:
        out_xml = XMLWriter(args[3])
        out_xml.declaration()
        doc = out_xml.start("TrainingSet")
        
        # source information
        out_xml.start("video", mark_in=str(mark_in), mark_out=str(mark_out))
        out_xml.data(os.path.basename(args[1]))
        out_xml.end()
        out_xml.element("csv", os.path.basename(args[2]))
        
        # training point data
        for lens in trainer_points:
            if lens == Theta.Right:
                out_xml.start("buttonside", points=str(len(trainer_points[lens])))
            elif lens == Theta.Left:
                out_xml.start("backside", points=str(len(trainer_points[lens])))
            else: # non dualmode
                out_xml.start("frames", points=str(len(trainer_points[lens])))
            
            for i in trainer_points[lens]:
                pos, row, markers = trainer_points[lens][i]
                x, y = pos
                
                out_xml.start("frame", num=str(i))
                out_xml.element("plane", 
                                x=str(x), 
                                y=str(y))
                out_xml.element("vicon", 
                                x=str(row[0]), y=str(row[1]), z=str(row[2]))
                out_xml.element("visibility", 
                                visibleMax=str(markers[0]), 
                                visible=str(markers[1]))
                out_xml.end()
                
            out_xml.end() # frames
        
        # clean up
        out_xml.close(doc)
        
        print "Data was written."
    else:
        print "No data was written"
    
    print "\nDone."
    return 0
Example #3
0
class XMLReporter(BaseReporter):
    """Reports test results in XML, in a format resembling Ant's JUnit xml
    formatting output."""
    def __init__(self):
        BaseReporter.__init__(self)

        from cStringIO import StringIO
        self._sio = StringIO()
        try:
            from elementtree.SimpleXMLWriter import XMLWriter
        except ImportError:
            from testoob.compatibility.SimpleXMLWriter import XMLWriter
        self.writer = XMLWriter(self._sio, "utf-8")

        self.test_starts = {}

    def start(self):
        BaseReporter.start(self)
        self.writer.start("results")
        self.writer.start("testsuites")

    def done(self):
        BaseReporter.done(self)

        self.writer.element("total_time", value="%.4f" % self.total_time)
        self.writer.end("testsuites")

        if self.cover_amount is not None and self.cover_amount == "xml":
            self._write_coverage(self.coverage)

        self.writer.end("results")

    def get_xml(self):
        return self._sio.getvalue()

    def startTest(self, test_info):
        BaseReporter.startTest(self, test_info)
        self.test_starts[test_info] = time.time()

    def addError(self, test_info, err_info):
        BaseReporter.addError(self, test_info, err_info)
        self._add_unsuccessful_testcase("error", test_info, err_info)

    def addFailure(self, test_info, err_info):
        BaseReporter.addFailure(self, test_info, err_info)
        self._add_unsuccessful_testcase("failure", test_info, err_info)

    def _add_testcase_element(self,
                              test_info,
                              result,
                              add_elements=lambda: None):
        self._start_testcase_tag(test_info)
        self.writer.element("result", result)
        add_elements()
        self.writer.end("testcase")

    def addSuccess(self, test_info):
        BaseReporter.addSuccess(self, test_info)
        self._add_testcase_element(test_info, "success")

    def addSkip(self, test_info, err_info, isRegistered=True):
        BaseReporter.addSkip(self, test_info, err_info, isRegistered)

        def add_elements():
            self.writer.element("reason", err_info.exception_value())

        self._add_testcase_element(test_info, "skip")

    def _add_unsuccessful_testcase(self, failure_type, test_info, err_info):
        def add_elements():
            "Additional elements specific for failures and errors"
            self.writer.element(failure_type,
                                str(err_info),
                                type=err_info.exception_type(),
                                message=err_info.exception_value())

        self._add_testcase_element(test_info, failure_type, add_elements)

    def _start_testcase_tag(self, test_info):
        self.writer.start("testcase",
                          name=str(test_info),
                          time=self._test_time(test_info))

    def _test_time(self, test_info):
        result = time.time() - self.test_starts[test_info]
        return "%.4f" % result

    def _write_coverage(self, coverage):
        self.writer.start("coverage")
        for filename, stats in coverage.getstatistics().items():
            # TODO: can probably extract loop body to a method
            self.writer.start("sourcefile",
                              name=filename,
                              statements=str(stats["lines"]),
                              executed=str(stats["covered"]),
                              percent=str(stats["percent"]))
            lines, covered = coverage.coverage[filename].values()
            missing = [line for line in covered if line not in lines]
            self.writer.data(str(missing)[1:-1].replace(" ", ""))
            self.writer.end("sourcefile")
        self.writer.end("coverage")
"""
Created on Sun Dec 28 21:43:03 2014

@author: jmalinchak
"""

from elementtree.SimpleXMLWriter import XMLWriter
import sys

w = XMLWriter(sys.stdout)

html = w.start("html")

w.start("head")
w.element("title", "my document")
w.element("meta", name="generator", value="my application 1.0")
w.end()

w.start("body")
w.element("h1", "this is a heading")
w.element("p", "this is a paragraph")

w.start("p")
w.data("this is ")
w.element("b", "bold")
w.data(" and ")
w.element("i", "italic")
w.data(".")
w.end("p")

w.close(html)
Example #5
0
class XMLReporter(BaseReporter):
    """Reports test results in XML, in a format resembling Ant's JUnit xml
    formatting output."""
    def __init__(self):
        BaseReporter.__init__(self)

        from cStringIO import StringIO
        self._sio = StringIO()
        try:
            from elementtree.SimpleXMLWriter import XMLWriter
        except ImportError:
            from testoob.compatibility.SimpleXMLWriter import XMLWriter
        self.writer = XMLWriter(self._sio, "utf-8")

        self.test_starts = {}

    def start(self):
        BaseReporter.start(self)
        self.writer.start("results")
        self.writer.start("testsuites")

    def done(self):
        BaseReporter.done(self)

        self.writer.element("total_time", value="%.4f"%self.total_time)
        self.writer.end("testsuites")

        if self.cover_amount is not None and self.cover_amount == "xml":
            self._write_coverage(self.coverage)

        self.writer.end("results")

    def get_xml(self):
        return self._sio.getvalue()

    def startTest(self, test_info):
        BaseReporter.startTest(self, test_info)
        self.test_starts[test_info] = time.time()

    def addError(self, test_info, err_info):
        BaseReporter.addError(self, test_info, err_info)
        self._add_unsuccessful_testcase("error", test_info, err_info)

    def addFailure(self, test_info, err_info):
        BaseReporter.addFailure(self, test_info, err_info)
        self._add_unsuccessful_testcase("failure", test_info, err_info)

    def _add_testcase_element(self, test_info, result, add_elements = lambda:None):
        self._start_testcase_tag(test_info)
        self.writer.element("result", result)
        add_elements()
        self.writer.end("testcase")

    def addSuccess(self, test_info):
        BaseReporter.addSuccess(self, test_info)
        self._add_testcase_element(test_info, "success")

    def addSkip(self, test_info, err_info, isRegistered=True):
        BaseReporter.addSkip(self, test_info, err_info, isRegistered)
        def add_elements():
            self.writer.element( "reason", err_info.exception_value() )
        self._add_testcase_element(test_info, "skip")

    def _add_unsuccessful_testcase(self, failure_type, test_info, err_info):
        def add_elements():
            "Additional elements specific for failures and errors"
            self.writer.element(failure_type, str(err_info), type=err_info.exception_type(), message=err_info.exception_value())
        self._add_testcase_element(test_info, failure_type, add_elements)

    def _start_testcase_tag(self, test_info):
        self.writer.start("testcase", name=str(test_info), time=self._test_time(test_info))

    def _test_time(self, test_info):
        result = time.time() - self.test_starts[test_info]
        return "%.4f" % result

    def _write_coverage(self, coverage):
        self.writer.start("coverage")
        for filename, stats in coverage.getstatistics().items():
            # TODO: can probably extract loop body to a method
            self.writer.start("sourcefile", name=filename,
                              statements=str(stats["lines"]),
                              executed=str(stats["covered"]),
                              percent=str(stats["percent"]))
            lines, covered =  coverage.coverage[filename].values()
            missing = [line for line in covered if line not in lines]
            self.writer.data(str(missing)[1:-1].replace(" ", ""))
            self.writer.end("sourcefile")
        self.writer.end("coverage")
Example #6
0
def main(sysargs):
    # settings
    args = EasyArgs(sysargs)
    cfg = EasyConfig(args.config, group="trainer")
    max_clicks = args.clicks or cfg.default_clicks
    window_name = "EagleEye Trainer"

    if "help" in args:
        usage()
        return 0

    # grab marks from args
    if len(args) > 5:
        mark_in = args[4]
        mark_out = args[5]

        # test integer-ness
        try:
            int(mark_in) and int(mark_out)
        except:
            usage()
            return 1

    elif len(args) > 3:
        ret, mark_in, mark_out = marker_tool(args[1], cfg.buffer_size,
                                             window_name)
        if not ret:
            print "Not processing - exiting."
            return 1
    else:
        usage()
        return 1

    ## clicking time!
    cropped_total = mark_out - mark_in
    print "video cropped at:", mark_in, "to", mark_out, "- ({} frames)".format(
        cropped_total)

    # clicking function
    def on_mouse(event, x, y, flags, params):
        # left click to mark
        if event == cv2.EVENT_LBUTTONDOWN:
            params['pos'] = (x, y)
            params['status'] = Status.record

        # right click to skip
        elif event == cv2.EVENT_RBUTTONDOWN:
            params['status'] = Status.skip

    # working variables
    params = {'status': Status.wait, 'pos': None}
    write_xml = False
    textstatus = ""
    dataQuality = 0  # 0 = good, >0 = bad/potentially bad

    # default right side (buttonside)
    if cfg.dual_mode:
        lens = Theta.Right
        trainer_points = {Theta.Right: {}, Theta.Left: {}}
    else:  # both sides otherwise
        lens = Theta.Both
        trainer_points = {Theta.Both: {}}

    print "Minimum reflectors: {} | Ignore Negative xyz: {}".format(
        cfg.min_reflectors, cfg.check_negatives)

    # load video (again)
    in_vid = BuffSplitCap(args[1],
                          crop=(0, 0, 0, 0),
                          rotate=BuffSplitCap.r0,
                          buff_max=cfg.buffer_size)
    in_vid.restrict(mark_in, mark_out)

    # load csv (with appropriate ratio)
    in_csv = Memset(args[2])
    in_csv.restrict()
    in_csv.setRatio(cropped_total)

    # test for marker data
    if len(in_csv.row()) < 10:
        print "This CSV contains no marker data!\nAborting."
        return 1

    # status
    print ""
    print "Writing to:", args[3]
    print "Number of clicks at:", max_clicks
    print ""

    cv2.namedWindow(window_name)
    cv2.setMouseCallback(window_name, on_mouse, params)

    # grab clicks (Process 2)
    while in_vid.isOpened():
        frame = in_vid.frame(side=lens)

        sys.stdout.write(in_vid.status() + " | Clicks {} / {}\r".format(
            len(trainer_points[lens]), max_clicks))
        sys.stdout.flush()

        # prepare CSV data, click data
        tx = float(in_csv.row()[2])
        ty = float(in_csv.row()[3])
        tz = float(in_csv.row()[4])
        rx = float(in_csv.row()[5])
        ry = float(in_csv.row()[6])
        rz = float(in_csv.row()[7])

        # data quality status
        visible = int(in_csv.row()[9])
        max_visible = int(in_csv.row()[8])

        # status text to write
        textrow = "VICON - x: {:.4f} y: {:.4f} z: {:.4f} | rx: {:.4f} ry: {:.4f} rz: {:.4f}".format(
            tx, ty, tz, rx, ry, rz)
        textquality = "Visible: {} , Max Visible: {}".format(
            visible, max_visible)
        textstatus = "{} | {}/{} clicks".format(in_vid.status(),
                                                len(trainer_points[lens]),
                                                max_clicks)

        if lens == Theta.Left:
            textstatus += " - back side"
        elif lens == Theta.Right:
            textstatus += " - button side"
        #else none, no lens split

        # if data is qualified bad, reduce timeout by one
        if dataQuality > 0:
            dataQuality -= 1

        if dataQuality == 0:
            dataStatus = " - Good data!!"
            dataStatus_colour = (0, 255, 0)  # green
        else:
            dataStatus = " - Potentially bad data (wait {})".format(
                dataQuality)
            dataStatus_colour = (0, 255, 255)  # yellow

        # Data tests
        # values must be above 0 and minimum reflectors
        if (cfg.check_negatives and (tx <= 0 or ty <= 0 or tz <= 0)) \
                or visible < cfg.min_reflectors:
            dataStatus = " - Bad data!!"
            dataStatus_colour = (0, 0, 255)  # red

            if cfg.ignore_baddata:
                dataStatus += " Ignored."
                dataQuality = 1 + cfg.quality_delay

        # draw the trainer dot (if applicable)
        if in_vid.at() in trainer_points[lens]:
            cv2.circle(frame, trainer_points[lens][in_vid.at()][0], 1,
                       cfg.dot_colour, 2)
            cv2.circle(frame, trainer_points[lens][in_vid.at()][0], 15,
                       cfg.dot_colour, 1)

        # draw text and show
        displayText(frame, textrow, top=True)
        displayText(frame, textquality)
        displayText(frame, textstatus)
        displayText(frame, dataStatus, endl=True, colour=dataStatus_colour)

        cv2.imshow(window_name, frame)

        # pause for input
        while params['status'] == Status.wait:
            key = cv2.waitKey(10)
            if key == Key.esc:
                params['status'] = Status.stop
            elif key == Key.enter:
                write_xml = True
                params['status'] = Status.stop
            elif key == Key.right:
                params['status'] = Status.skip
            elif key == Key.left:
                params['status'] = Status.back
            elif key == Key.backspace:
                params['status'] = Status.remove
            elif Key.char(key, '1') and cfg.dual_mode:
                params['status'] = Status.still
                lens = Theta.Left
            elif Key.char(key, '2') and cfg.dual_mode:
                params['status'] = Status.still
                lens = Theta.Right

        # catch exit status
        if params['status'] == Status.stop:
            print "\nprocess aborted!"
            break

        # write data
        if params['status'] == Status.record \
                and len(trainer_points[lens]) != max_clicks: # TODO: does this disable recording clicks on the last frame

            if dataQuality == 0:
                trainer_points[lens][in_vid.at()] = (params['pos'],
                                                     in_csv.row()[2:5],
                                                     in_csv.row()[8:10])
            params['status'] = Status.skip

        # or remove it
        elif params['status'] == Status.remove \
                and in_vid.at() in trainer_points[lens]:
            del trainer_points[lens][in_vid.at()]
            print "\nremoved dot"

        # load next csv frame
        if params['status'] == Status.skip:
            if in_vid.next():
                in_csv.next()
            else:
                write_xml = True
                print "\nend of video: {}/{}".format(in_vid.at() - 1,
                                                     mark_out - 1)
                break

        # or load previous csv frame
        elif params['status'] == Status.back:
            if in_vid.back():
                in_csv.back()

        # reset status
        params['status'] = Status.wait

    # clean up
    cv2.destroyAllWindows()

    ## write xml
    if write_xml:
        out_xml = XMLWriter(args[3])
        out_xml.declaration()
        doc = out_xml.start("TrainingSet")

        # source information
        out_xml.start("video", mark_in=str(mark_in), mark_out=str(mark_out))
        out_xml.data(os.path.basename(args[1]))
        out_xml.end()
        out_xml.element("csv", os.path.basename(args[2]))

        # training point data
        for lens in trainer_points:
            if lens == Theta.Right:
                out_xml.start("buttonside",
                              points=str(len(trainer_points[lens])))
            elif lens == Theta.Left:
                out_xml.start("backside",
                              points=str(len(trainer_points[lens])))
            else:  # non dualmode
                out_xml.start("frames", points=str(len(trainer_points[lens])))

            for i in trainer_points[lens]:
                pos, row, markers = trainer_points[lens][i]
                x, y = pos

                out_xml.start("frame", num=str(i))
                out_xml.element("plane", x=str(x), y=str(y))
                out_xml.element("vicon",
                                x=str(row[0]),
                                y=str(row[1]),
                                z=str(row[2]))
                out_xml.element("visibility",
                                visibleMax=str(markers[0]),
                                visible=str(markers[1]))
                out_xml.end()

            out_xml.end()  # frames

        # clean up
        out_xml.close(doc)

        print "Data was written."
    else:
        print "No data was written"

    print "\nDone."
    return 0
@author: jmalinchak
"""

from elementtree.SimpleXMLWriter import XMLWriter
import sys



w = XMLWriter(sys.stdout)

html = w.start("html")

w.start("head")
w.element("title", "my document")
w.element("meta", name="generator", value="my application 1.0")
w.end()

w.start("body")
w.element("h1", "this is a heading")
w.element("p", "this is a paragraph")

w.start("p")
w.data("this is ")
w.element("b", "bold")
w.data(" and ")
w.element("i", "italic")
w.data(".")
w.end("p")

w.close(html)