Exemplo n.º 1
0
    def default_traits_view(self):
        panel = self.control_panel()

        return View(self.SPLITTER(
            VGroup(Item("current_filename",
                        editor=EnumEditor(name="object.filenames")),
                   Item("settings",
                        style="custom",
                        defined_when="bool(object.SETTINGS)"),
                   panel,
                   show_labels=False),
            Item("figure",
                 editor=MPLFigureEditor(toolbar=True),
                 show_label=False)),
                    resizable=True,
                    title=self.TITLE,
                    width=self.SIZE[0],
                    height=self.SIZE[1],
                    handler=PositionHandler())
Exemplo n.º 2
0
class PolygonWidgetDemo(HasTraits):
    figure = Instance(Figure, ())
    polygon = Instance(PolygonWidget)

    view = View(
        Item("figure", editor=MPLFigureEditor(toolbar=True), show_label=False),
        resizable=True,
        width=800,
        height=600,
        handler=PositionHandler()
    )

    def __init__(self, **kw):
        super(PolygonWidgetDemo, self).__init__(**kw)
        self.axe = self.figure.add_subplot(111)

    def on_position(self):
        points = np.array([[0, 0], [1, 0], [0, 1.0]])
        style = {"marker": "o"}
        self.polygon = PolygonWidget(axe=self.axe, points=points, style=style)
        self.polygon.on_trait_change(lambda:self.figure.canvas.draw(), "changed")
class FunctionPlotter(HasTraits):
    figure = Instance(Figure, ())  #❶
    code = Code()  #❷
    points = List(Instance(Point), [])  #❸
    draw_button = Button("Plot")

    view = View(
        VSplit(
            Item("figure",
                 editor=MPLFigureEditor(toolbar=True),
                 show_label=False),  #❶
            HSplit(
                VGroup(
                    Item("code", style="custom"),  #❷
                    HGroup(Item("draw_button", show_label=False), ),
                    show_labels=False),
                Item("points", editor=point_table_editor, show_label=False)  #❸
            )),
        width=800,
        height=600,
        title="Function Plotter",
        resizable=True)

    ###2###
    ###3###
    def __init__(self, **kw):
        super(FunctionPlotter, self).__init__(**kw)
        self.figure.canvas_events = [  #❶
            ("button_press_event", self.memory_location),
            ("button_release_event", self.update_location)
        ]
        self.button_press_status = None  #保存鼠标按键按下时的状态
        self.lines = []  #保存所有曲线
        self.functions = []  #保存所有的曲线函数
        self.env = {}  #代码的执行环境

        self.axe = self.figure.add_subplot(1, 1, 1)
        self.axe.callbacks.connect('xlim_changed', self.update_data)  #❷
        self.axe.set_xlim(0, 1)
        self.axe.set_ylim(0, 1)
        self.points_line, = self.axe.plot([], [], "kx", ms=8,
                                          zorder=1000)  #数据点
###3###
###6###

    def update_data(self, axe):
        xmin, xmax = axe.get_xlim()
        x = np.linspace(xmin, xmax, 500)
        for line, func in zip(self.lines, self.functions):
            y = func(x)
            line.set_data(x, y)
        self.update_figure()
###6###
###4###

    def memory_location(self, evt):
        if evt.button in (1, 3):
            self.button_press_status = time.clock(), evt.x, evt.y
        else:
            self.button_press_status = None

    def update_location(self, evt):
        if evt.button in (1, 3) and self.button_press_status is not None:
            last_clock, last_x, last_y = self.button_press_status
            if time.clock() - last_clock > 0.5:  #❶
                return
            if ((evt.x - last_x)**2 + (evt.y - last_y)**2)**0.5 > 4:  #❷
                return

        if evt.button == 1:
            if evt.xdata is not None and evt.ydata is not None:
                point = Point(x=evt.xdata, y=evt.ydata)  #❸
                self.points.append(point)
        elif evt.button == 3:
            if self.points:
                self.points.pop()  #❹
###4###
###5###

    @on_trait_change("points[]")
    def _points_changed(self, obj, name, new):
        for point in new:
            point.on_trait_change(self.update_points, name="x, y")  #❶
        self.update_points()

    def update_points(self):  #❷
        arr = np.array([(point.x, point.y) for point in self.points])
        if arr.shape[0] > 0:
            self.points_line.set_data(arr[:, 0], arr[:, 1])
        else:
            self.points_line.set_data([], [])
        self.update_figure()

    def update_figure(self):  #❸
        if self.figure.canvas is not None:  #❹
            self.figure.canvas.draw_idle()
###5###
###7###

    def _draw_button_fired(self):
        self.plot_lines()

    def plot_lines(self):
        xmin, xmax = self.axe.get_xlim()  #❶
        x = np.linspace(xmin, xmax, 500)
        self.env = {
            "points": np.array([(point.x, point.y) for point in self.points])
        }  #❷
        exec self.code in self.env

        results = []
        for line in self.lines:
            line.remove()
        self.axe.set_color_cycle(None)  #重置颜色循环
        self.functions = []
        self.lines = []
        for name, value in self.env.items():  #❸
            if name.startswith("_"):  #忽略以_开头的名字
                continue
            if callable(value):
                try:
                    y = value(x)
                    if y.shape != x.shape:  #输出数组应该与输入数组的形状一致
                        raise ValueError(
                            "the return shape is not the same as x")
                except Exception as ex:
                    import traceback
                    print "failed when call function {}\n".format(name)
                    traceback.print_exc()
                    continue

                results.append((name, y))
                self.functions.append(value)

        for (name, y), function in zip(results, self.functions):
            #如果函数有plot_parameters属性,则用其作为plot()的参数
            kw = getattr(function, "plot_parameters", {})  #❹
            label = kw.get("label", name)
            line, = self.axe.plot(x, y, label=label, **kw)
            self.lines.append(line)

        points = self.env.get("points", None)  #❺
        if points is not None:
            self.points = [
                Point(x=x, y=y) for x, y in np.asarray(points).tolist()
            ]

        self.axe.legend()
        self.update_figure()
class IFSDesigner(HasTraits):
    color_maps = List
    current_map = Str("Greens")
    figure = Instance(Figure)  # 控制绘图控件的Figure对象
    ifs_triangle = Instance(IFSTriangles)
    add_button = Button(u"添加三角形")
    del_button = Button(u"删除三角形")
    settings = Instance(SettingManager)
    clear = Bool(True)

    view = View(VGroup(
        HGroup(Item("add_button"),
               Item("del_button"),
               Item("settings", style="custom"),
               Item("current_map", editor=EnumEditor(name="color_maps")),
               show_labels=False),
        Item("figure", editor=MPLFigureEditor(toolbar=False),
             show_label=False),
    ),
                resizable=True,
                height=450,
                width=800,
                title=u"迭代函数系统设计器",
                handler=IFSHandler())

    def _settings_default(self):
        settings = SettingManager(target=self)
        return settings

    def _color_maps_default(self):
        return sorted(cm.cmap_d.keys())

    def load_settings(self, setting):
        self.ifs_triangle.set_points(np.array(setting["points"]))
        self.current_map = setting["cmap"]

    def get_settings(self):
        return dict(points=self.ifs_triangle.points.tolist(),
                    cmap=self.current_map)

    def _add_button_fired(self):
        """
        添加三角形按钮事件处理
        """
        self.ifs_triangle.add_triangle()

    def _del_button_fired(self):
        self.ifs_triangle.del_triangle()

    def ifs_calculate(self):
        if self.clear == True:
            self.clear = False
            self.initpos = [0, 0]
            p = self.ifs_triangle.get_areas()
            eqs = self.ifs_triangle.get_eqs()
            self.ifs = IFS(p, eqs, 100000, size=600)
            self.ax2.clear()
            self.img = self.ax2.imshow(np.ones((10, 10)),
                                       norm=LogNorm(),
                                       cmap=self.current_map,
                                       origin="lower")
            self.ax2.set_aspect("equal")
            self.ax2.axis("off")

        try:
            count = self.ifs.update()
        except ZeroDivisionError:
            count = None
        if count is None:
            return
        self.img.set_data(count)
        self.img.norm.autoscale(count)
        self.img.set_cmap(self.current_map)
        h, w = count.shape
        self.img.set_extent([0, w, 0, h])
        self.ax2.set_xlim(0, w)
        self.ax2.set_ylim(0, h)
        self.figure.canvas.draw()

    @on_trait_change("ifs_triangle.version")
    def on_ifs_version_changed(self):
        """
        当三角形更新时,重新绘制所有的迭代点
        """
        self.clear = True

    def _figure_default(self):
        """
        figure属性的缺省值,直接创建一个Figure对象
        """
        figure = Figure(figsize=(8, 4), dpi=100)
        self.ax = figure.add_subplot(121)
        self.ax2 = figure.add_subplot(122)
        self.ax.set_axis_off()
        figure.subplots_adjust(left=0,
                               right=1,
                               bottom=0,
                               top=1,
                               wspace=0,
                               hspace=0)
        figure.patch.set_facecolor("w")
        return figure

    def init_gui_component(self):
        self.ifs_triangle = IFSTriangles(self.ax)
        self.figure.canvas.draw()
        self.settings.select_last()
        self.timer = Timer(10, self.ifs_calculate)
Exemplo n.º 5
0
class StereoDemo(HasTraits):

    update_button = Button(u"Update")
    scene = Instance(SceneModel, ())
    figure = Instance(Figure, ())

    view = View(
        VGroup(
            HGroup(
                "update_button",
                show_labels=False
            ),
            HSplit(
                Item(name="figure", editor=MPLFigureEditor(toolbar=False)),
                Item(name="scene", editor=SceneEditor(scene_class=Scene)),
                show_labels=False
            )
        ),
        title="Stereo Camera Demo",
        width=800,
        height=400,
        resizable=True,
    )

    def __init__(self, **kw):
        super(StereoDemo, self).__init__(**kw)
        self.axes = self.figure.add_subplot(111)

    def _update_button_fired(self):
        self.calc()

    def calc(self):
        img_left = cv2.pyrDown(cv2.imread(path.join(FOLDER, 'aloeL.jpg')))
        img_right = cv2.pyrDown(cv2.imread(path.join(FOLDER, 'aloeR.jpg')))

        img_left = cv2.cvtColor(img_left, cv2.COLOR_BGR2RGB)
        img_right = cv2.cvtColor(img_right, cv2.COLOR_BGR2RGB)

        stereo_parameters = dict(
            SADWindowSize=5,
            numDisparities=192,
            preFilterCap=4,
            minDisparity=-24,
            uniquenessRatio=1,
            speckleWindowSize=150,
            speckleRange=2,
            disp12MaxDiff=10,
            fullDP=False,
            P1=600,
            P2=2400)

        stereo = cv2.StereoSGBM(**stereo_parameters)
        disparity = stereo.compute(img_left, img_right).astype(np.float32) / 16

        h, w = img_left.shape[:2]
        ygrid, xgrid = np.mgrid[:h, :w]
        ygrid = ygrid.astype(np.float32)
        xgrid = xgrid.astype(np.float32)

        Bf = w * 0.8
        x = (xgrid - w * 0.5)
        y = (ygrid - h * 0.5)
        d = (disparity + 1e-6)
        z = (Bf / d).ravel()
        x = (x / d).ravel()
        y = -(y / d).ravel()

        mask = (z > 0) & (z < 30)
        points = np.c_[x, y, z][mask]
        colors = img_left.reshape(-1, 3)[mask]

        poly = tvtk.PolyData()
        poly.points = points
        poly.verts = np.arange(len(points)).reshape(-1, 1)
        poly.point_data.scalars = colors.astype(np.uint8)
        mapper = tvtk.PolyDataMapper()
        mapper.set_input_data(poly)
        actor = tvtk.Actor(mapper=mapper)
        self.scene.add_actor(actor)
        self.scene.camera.position = (0, 20, -60)
        self.scene.camera.view_up = 0, 1, 0
        self.scene.render()

        self.axes.clear()
        self.axes.imshow(disparity)
        self.figure.canvas.draw()