本文整理汇总了Python中matplotlib.patches.Polygon.add_callback方法的典型用法代码示例。如果您正苦于以下问题:Python Polygon.add_callback方法的具体用法?Python Polygon.add_callback怎么用?Python Polygon.add_callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.patches.Polygon
的用法示例。
在下文中一共展示了Polygon.add_callback方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_new_poly
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
def draw_new_poly(self):
coords = default_vertices(self.ax)
Poly = Polygon(coords, animated=True,
fc="white", ec='none', alpha=0.2, picker=True)
self.polyList.append(Poly)
self.ax.add_patch(Poly)
x, y = zip(*Poly.xy)
#line_color = 'none'
color = np.array((1,1,1))
marker_face_color = (1,1,1)
line_width = 4;
line_kwargs = {'lw': line_width, 'color': color, 'mfc': marker_face_color}
self.line.append(plt.Line2D(x, y, marker='o', alpha=1, animated=True, **line_kwargs))
self._update_line()
self.ax.add_line(self.line[-1])
Poly.add_callback(self.poly_changed)
Poly.num = self.poly_count
self._ind = None # the active vert
self.poly_count+=1;
示例2: BoundaryInteractor
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
#.........这里部分代码省略.........
def __init__(self, x, y=None, beta=None, ax=None, proj=None,
**gridgen_options):
if isinstance(x, str):
bry_dict = np.load(x)
x = bry_dict['x']
y = bry_dict['y']
beta = bry_dict['beta']
assert len(x) >= 4, 'Boundary must have at least four points.'
if ax is None:
ax = plt.gca()
self._ax = ax
self.proj = proj
# Set default gridgen option, and copy over specified options.
self.gridgen_options = {'ul_idx': 0, 'shp': (32, 32)}
for key, value in gridgen_options.iteritems():
self.gridgen_options[key] = gridgen_options[key]
x = list(x); y = list(y)
assert len(x)==len(y), 'arrays must be equal length'
if beta is None:
self.beta = [0 for xi in x]
else:
assert len(x)==len(beta), 'beta must have same length as x and y'
self.beta = list(beta)
self._line = Line2D(x, y, animated=True,
ls='-', color='k', alpha=0.5, lw=1)
self._ax.add_line(self._line)
self._canvas = self._line.figure.canvas
self._poly = Polygon(self.verts, alpha=0.1, fc='k', animated=True)
self._ax.add_patch(self._poly)
# Link in the lines that will show the beta values
# pline for positive turns, mline for negative (minus) turns
# otherwize zline (zero) for straight sections
self._pline = Line2D([], [], marker='^', ms=12, mfc='g',\
animated=True, lw=0)
self._mline = Line2D([], [], marker='v', ms=12, mfc='r',\
animated=True, lw=0)
self._zline = Line2D([], [], marker='o', mfc='k', animated=True, lw=0)
self._sline = Line2D([], [], marker='s', mfc='k', animated=True, lw=0)
self._update_beta_lines()
self._ax.add_artist(self._pline)
self._ax.add_artist(self._mline)
self._ax.add_artist(self._zline)
self._ax.add_artist(self._sline)
# get the canvas and connect the callback events
cid = self._poly.add_callback(self._poly_changed)
self._ind = None # the active vert
self._canvas.mpl_connect('draw_event', self._draw_callback)
self._canvas.mpl_connect('button_press_event',\
self._button_press_callback)
self._canvas.mpl_connect('key_press_event', self._key_press_callback)
self._canvas.mpl_connect('button_release_event',\
self._button_release_callback)
self._canvas.mpl_connect('motion_notify_event',\
self._motion_notify_callback)
def save_bry(self, bry_file='bry.pickle'):
f = open(bry_file, 'wb')
bry_dict = {'x': self.x, 'y': self.y, 'beta': self.beta}
cPickle.dump(bry_dict, f, protocol=-1)
f.close()
def load_bry(self, bry_file='bry.pickle'):
bry_dict = np.load(bry_file)
x = bry_dict['x']
y = bry_dict['y']
self._line.set_data(x, y)
self.beta = bry_dict['beta']
if hasattr(self, '_poly'):
self._poly.xy = zip(x, y)
self._update_beta_lines()
self._draw_callback(None)
self._canvas.draw()
def save_grid(self, grid_file='grid.pickle'):
f = open(grid_file, 'wb')
cPickle.dump(self.grd, f, protocol=-1)
f.close()
def _get_verts(self): return zip(self.x, self.y)
verts = property(_get_verts)
def get_xdata(self): return self._line.get_xdata()
x = property(get_xdata)
def get_ydata(self): return self._line.get_ydata()
y = property(get_ydata)
示例3: BoundaryClick
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
#.........这里部分代码省略.........
for line in self._gridlines:
self._ax.lines.remove(line)
delattr(self, '_gridlines')
def _init_boundary_interactor(self):
"""Send polyclick thread to boundary interactor"""
# Get rid old mpl connections.
self._ax.figure.canvas.mpl_disconnect(self._key_id)
self._ax.figure.canvas.mpl_disconnect(self._click_id)
# Shade the selected region in a polygon
self._poly = Polygon(self.verts, alpha=0.1, fc='k', animated=True)
self._ax.add_patch(self._poly)
# change line to animated
# self._line.set_animated(True)
# self._line.set_markerfacecolor('k')
self._line.set_marker('None')
# Link in the two lines that will show the beta values
# pline for positive turns, mline for negative (minus) turns.
self._pline = Line2D([], [], marker='^', ms=12, mfc='g', animated=True, lw=0)
self._mline = Line2D([], [], marker='v', ms=12, mfc='r', animated=True, lw=0)
self._zline = Line2D([], [], marker='o', mfc='k', animated=True, lw=0)
self._sline = Line2D([], [], marker='s', mfc='k', animated=True, lw=0)
self._update_beta_lines()
self._ax.add_artist(self._pline)
self._ax.add_artist(self._mline)
self._ax.add_artist(self._zline)
self._ax.add_artist(self._sline)
# get the canvas and connect the callback events
cid = self._poly.add_callback(self._poly_changed)
self._ind = None # the active vert
self._canvas.mpl_connect('draw_event', self._draw_callback)
self._canvas.mpl_connect('button_press_event', self._button_press_callback)
self._canvas.mpl_connect('key_press_event', self._key_press_callback)
self._canvas.mpl_connect('button_release_event', self._button_release_callback)
self._canvas.mpl_connect('motion_notify_event', self._motion_notify_callback)
def _on_return(self, event):
if event.key in ('enter', None):
self._init_boundary_interactor()
def _on_click(self, event):
self.x.append(event.xdata)
self.y.append(event.ydata)
self.beta.append(0)
self._line.set_data(self.x, self.y)
self._background = self._canvas.copy_from_bbox(self._ax.bbox)
self._ax.draw_artist(self._line)
self._canvas.blit(self._ax.bbox)
def _draw_callback(self, event):
self._background = self._canvas.copy_from_bbox(self._ax.bbox)
self._ax.draw_artist(self._poly)
self._ax.draw_artist(self._pline)
self._ax.draw_artist(self._mline)
self._ax.draw_artist(self._zline)
self._ax.draw_artist(self._sline)
self._ax.draw_artist(self._line)
self._canvas.blit(self._ax.bbox)
示例4: MaskDrawer
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class MaskDrawer(object):
"""An interactive polygon mask drawer on an image.
Parameters
----------
ax : matplotlib plot axis
Inpimg : 2d numpy array
Input image to overlay for drawing mask
Mask : Boolean numpy array same size of inpimg
A Mask which will be used as initial mask and updated upon confirmation
max_ds : float
Max pixel distance to count as a vertex hit.
PolyAtStart : List of vertices
A list of square vertices to draw the initial polygon
Key-bindings
------------
't' : toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' : delete the vertex under point
'i' : insert a vertex at point. You must be within max_ds of the
line connecting two existing vertices
'n' : Invert the region selected by polynomial for masking
'c' : Confirm the polygon and update the mask
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
def __init__(self, ax, Inpimg, Mask, max_ds=10,PolyAtStart = [(50,50),(100,50),(100,100),(50,100)]):
self.showverts = True
self.max_ds = max_ds
self.Mask = Mask
self.img = Inpimg
self.maskinvert = False
# imshow the image
self.imgplot = ax.imshow(np.ma.filled(np.ma.array(self.img,mask=self.Mask,fill_value=np.nan)), cmap=cm.gray)
self.poly = Polygon(PolyAtStart, animated=True,
fc='y', ec='none', alpha=0.5)
ax.add_patch(self.poly)
ax.set_clip_on(False)
ax.set_title("Click and drag a point to move it; "
"'i' to insert; 'd' to delete.\n"
"'n' to invert the region for masking, 'c' to confirm & apply the mask.")
self.ax = ax
x, y = zip(*self.poly.xy)
self.line = Line2D(x, y, color='none', marker='o', mfc='r',
alpha=0.7, animated=True)
# self._update_line()
self.ax.add_line(self.line)
self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas = self.poly.figure.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
# display coords
xy = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt-event.x)**2 + (yt-event.y)**2)
indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
ind = indseq[0]
if d[ind]>=self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self.showverts: return
if event.inaxes==None: return
if event.button != 1: return
self._ind = self.get_ind_under_point(event)
#.........这里部分代码省略.........
示例5: MaskCreator
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class MaskCreator(object):
"""An interactive polygon editor.
Parameters
----------
poly_xy : list of (float, float)
List of (x, y) coordinates used as vertices of the polygon.
max_ds : float
Max pixel distance to count as a vertex hit.
Key-bindings
------------
't' : toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' : delete the vertex under point
'i' : insert a vertex at point. You must be within max_ds of the
line connecting two existing vertices
"""
def __init__(self, ax, poly_xy=None, max_ds=10):
self.showverts = True
self.max_ds = max_ds
if poly_xy is None:
poly_xy = default_vertices(ax)
self.poly = Polygon(poly_xy, animated=True,
fc='y', ec='none', alpha=0.4)
ax.add_patch(self.poly)
ax.set_clip_on(False)
ax.set_title("Click and drag a point to move it; "
"'i' to insert; 'd' to delete.\n"
"Close figure when done.")
self.ax = ax
x, y = zip(*self.poly.xy)
self.line = plt.Line2D(x, y, color='none', marker='o', mfc='r',
alpha=0.2, animated=True)
self._update_line()
self.ax.add_line(self.line)
self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas = self.poly.figure.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def get_mask(self, shape):
"""Return image mask given by mask creator"""
h, w = shape
y, x = np.mgrid[:h, :w]
points = np.transpose((x.ravel(), y.ravel()))
mask = path.Path.contains_point(points)
return mask.reshape(h, w)
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
#Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def draw_callback(self, event):
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def button_press_callback(self, event):
'whenever a mouse button is pressed'
ignore = not self.showverts or event.inaxes is None or event.button != 1
if ignore:
return
self._ind = self.get_ind_under_cursor(event)
def button_release_callback(self, event):
'whenever a mouse button is released'
ignore = not self.showverts or event.button != 1
if ignore:
return
self._ind = None
def key_press_callback(self, event):
'whenever a key is pressed'
if not event.inaxes:
return
if event.key=='t':
self.showverts = not self.showverts
self.line.set_visible(self.showverts)
if not self.showverts:
self._ind = None
elif event.key=='d':
ind = self.get_ind_under_cursor(event)
if ind is None:
return
if ind == 0 or ind == self.last_vert_ind:
print "Cannot delete root node"
return
self.poly.xy = [tup for i,tup in enumerate(self.poly.xy)
#.........这里部分代码省略.........
示例6: PolyRegionEditor
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class PolyRegionEditor(uiutils.UI):
def __init__(self, img, prj=None, max_ds=10, current_folder=None):
self.max_ds = max_ds
self.showverts = True
self.current_folder = current_folder
uiutils.UI.__init__(self, 750, 600, "PolyRegion Editor")
vbox = QtGui.QVBoxLayout()
self.setLayout(vbox)
canva_box = QtGui.QHBoxLayout()
vbox.addLayout(canva_box)
self.canvas = plotutils.BaseCustomCanvas()
canva_box.addWidget(self.canvas)
ctl = QtGui.QHBoxLayout()
vbox.addLayout(ctl)
ctl.addWidget(plotutils.NavigationToolbar(self.canvas, self))
self.title_entry = uiutils.EntryDescription("Title")
ctl.addWidget(self.title_entry)
self.color_entry = uiutils.EntryDescription("Color")
ctl.addWidget(self.color_entry)
save_bn = QtGui.QPushButton("Save")
save_bn.clicked.connect(self.on_save_clicked)
ctl.addWidget(save_bn)
load_bn = QtGui.QPushButton("Load")
load_bn.clicked.connect(self.on_load_clicked)
ctl.addWidget(load_bn)
save_bn = QtGui.QPushButton("New")
save_bn.clicked.connect(self.on_new_clicked)
ctl.addWidget(save_bn)
self.ax = self.canvas.figure.subplots()
if prj is None:
prj = img.get_projection()
self.prj = prj
self.img = img
plotutils.imshow_image(self.ax, self.img, projection=self.prj, title=False)
self.poly = Polygon([[0, 0]], animated=True,
fc='b', ec='none', alpha=0.4)
self.ax.add_patch(self.poly)
self.ax.set_clip_on(False)
self.ax.set_title("Click and drag a point to move it; "
"'i' to insert; 'd' to delete.")
x, y = zip(*self.poly.xy)
self.line = plt.Line2D(x, y, color='none', marker='o', mfc='r',
alpha=0.8, animated=True, lw=2, markersize=self.max_ds)
self._update_line()
self.ax.add_line(self.line)
self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas = self.poly.figure.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
self.load_default()
self.canvas.setFocus()
def get_axes(self):
return self.ax
def load_poly_region(self, poly_region):
self.title_entry.set_text(poly_region.title)
self.color_entry.set_text(poly_region.color)
self.poly.set_fc(poly_region.color)
vertices = list(poly_region.vertices)
vertices.append(vertices[0])
self.poly.xy = vertices
self._update_line()
self.canvas.draw()
def load_default(self):
default_poly_region = imgutils.PolyRegion.default_from_ax(self.ax)
self.load_poly_region(default_poly_region)
def on_load_clicked(self, bn):
filename = uiutils.open_file(parent=self, current_folder=self.current_folder)
if filename is not None:
#.........这里部分代码省略.........
示例7: MaskCreator
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class MaskCreator(object):
"""An interactive polygon editor.
Parameters
----------
poly_xy : list of (float, float)
List of (x, y) coordinates used as vertices of the polygon.
max_ds : float
Max pixel distance to count as a vertex hit.
Key-bindings
------------
't' : toggle vertex markers on and off. When vertex markers are on,
you can move them, delete them
'd' : delete the vertex under point
'i' : insert a vertex at point. You must be within max_ds of the
line connecting two existing vertices
"""
def __init__(self, ax, poly_xy=None, max_ds=10, line_width=2,
line_color=(0, 0, 1), face_color=(1, .5, 0)):
self.showverts = True
self.max_ds = max_ds
if poly_xy is None:
poly_xy = default_vertices(ax)
self.poly = Polygon(poly_xy, animated=True,
fc=face_color, ec='none', alpha=0.4)
ax.add_patch(self.poly)
ax.set_clip_on(False)
ax.set_title("Click and drag a point to move it; or click once, then click again."
"\n"
"Close figure when done.")
self.ax = ax
x, y = zip(*self.poly.xy)
#line_color = 'none'
color = np.array(line_color) * .6
marker_face_color = line_color
line_kwargs = {'lw': line_width, 'color': color, 'mfc': marker_face_color}
self.line = plt.Line2D(x, y, marker='o', alpha=0.8, animated=True, **line_kwargs)
self._update_line()
self.ax.add_line(self.line)
self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
canvas = self.poly.figure.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
canvas.mpl_connect('button_press_event', self.button_press_callback)
canvas.mpl_connect('button_release_event', self.button_release_callback)
#canvas.mpl_connect('key_press_event', self.key_press_callback)
canvas.mpl_connect('motion_notify_event', self.motion_notify_callback)
self.canvas = canvas
def get_mask(self, shape):
"""Return image mask given by mask creator"""
mask = verts_to_mask(shape, self.verts)
return mask
def poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
#Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def draw_callback(self, event):
#print('[mask] draw_callback(event=%r)' % event)
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.blit(self.ax.bbox)
def button_press_callback(self, event):
'whenever a mouse button is pressed'
if not self._ind is None:
self._ind = None;
return
ignore = not self.showverts or event.inaxes is None or event.button != 1
if ignore:
return
self._ind = self.get_ind_under_cursor(event)
if self._ind != None:
self.indX, self.indY = self.poly.xy[self._ind]
self.mouseX,self.mouseY = event.xdata, event.ydata
def button_release_callback(self, event):
'whenever a mouse button is released'
ignore = not self.showverts or event.button != 1
if ignore:
return
if self._ind is None:
return
currX, currY = self.poly.xy[self._ind]
#print (currX, ' ', currY)
#print (math.fabs(self.indX - currX)<3, ' and ', math.fabs(self.indY-currY)<3)
if math.fabs(self.indX - currX)<3 and math.fabs(self.indY-currY)<3:
return
self._ind = None
#.........这里部分代码省略.........
示例8: PolygonInteractor
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class PolygonInteractor(QtCore.QObject):
"""
Polygon Interactor
Parameters
----------
axtmp : matplotlib axis
matplotlib axis
pntxy :
"""
showverts = True
epsilon = 5 # max pixel distance to count as a vertex hit
polyi_changed = QtCore.pyqtSignal(list)
def __init__(self, axtmp, pntxy):
QtCore.QObject.__init__(self)
self.ax = axtmp
self.poly = Polygon([(1, 1)], animated=True)
self.ax.add_patch(self.poly)
self.canvas = self.poly.figure.canvas
self.poly.set_alpha(0.5)
self.pntxy = pntxy
self.ishist = True
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
xtmp, ytmp = list(zip(*self.poly.xy))
self.line = Line2D(xtmp, ytmp, marker='o', markerfacecolor='r',
color='y', animated=True)
self.ax.add_line(self.line)
self.poly.add_callback(self.poly_changed)
self._ind = None # the active vert
self.canvas.mpl_connect('button_press_event',
self.button_press_callback)
self.canvas.mpl_connect('button_release_event',
self.button_release_callback)
self.canvas.mpl_connect('motion_notify_event',
self.motion_notify_callback)
def draw_callback(self):
""" Draw callback """
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
QtWidgets.QApplication.processEvents()
self.canvas.restore_region(self.background)
self.ax.draw_artist(self.poly)
self.ax.draw_artist(self.line)
self.canvas.update()
def new_poly(self, npoly):
""" New Polygon """
self.poly.set_xy(npoly)
self.line.set_data(list(zip(*self.poly.xy)))
self.canvas.draw()
self.update_plots()
def poly_changed(self, poly):
""" Changed Polygon """
# this method is called whenever the polygon object is called
# only copy the artist props to the line (except visibility)
vis = self.line.get_visible()
Artist.update_from(self.line, poly)
self.line.set_visible(vis) # don't use the poly visibility state
def get_ind_under_point(self, event):
"""get the index of vertex under point if within epsilon tolerance"""
# display coords
xytmp = np.asarray(self.poly.xy)
xyt = self.poly.get_transform().transform(xytmp)
xtt, ytt = xyt[:, 0], xyt[:, 1]
dtt = np.sqrt((xtt - event.x) ** 2 + (ytt - event.y) ** 2)
indseq = np.nonzero(np.equal(dtt, np.amin(dtt)))[0]
ind = indseq[0]
if dtt[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
"""whenever a mouse button is pressed"""
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
if self._ind is None:
xys = self.poly.get_transform().transform(self.poly.xy)
ptmp = event.x, event.y # display coords
if len(xys) == 1:
self.poly.xy = np.array(
[(event.xdata, event.ydata)] +
[(event.xdata, event.ydata)])
#.........这里部分代码省略.........
示例9: PolyClick
# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import add_callback [as 别名]
class PolyClick(object):
"""
p = PolyClick() # Start interactive polygon generator, or
p = PolyClick(verts, ax=gca()) # Initialize polygon based on verts, or
p = PolyClick(x, y, ax=gca()) # Initialize polygon based on x and y, or
p = PolyClick('verts.pickle', ax=gca()) # Load in verts from pickle file
If verts or (x, y) are not given, an interactive polygon creation session is
started. Verticies are orange. Switch to editing mode by hitting return. This
changes the vertecies to black. The points may be moved with the mouse, or
modified with the key commands listed below. Current data are always
available in bry.x, bry.y and bry.verts.
Key commands:
enter : switch to grid editing mode
t : toggle visibility of verticies
d : delete a vertex
i : insert a vertex at a point on the polygon line
Methods:
p.dump(bry_file='bry.pickle)
Write the current boundary informtion (bry.verts) to a cPickle
file bry_file.
p.load(bry_file='bry.pickle)
Read in boundary informtion (verts) from the cPickle file bry_file.
Attributes:
p.x, p.y : The x and y locations of the polygon verticies.
p.verts : The verticies of the polygon (equiv. to zip(x, y))
p.area : the area of the polygon. Positive for a counterclockwise path,
negative for a clockwise path.
p.centroid : the (x, y) location of the polygon centroid.
"""
_showverts = True
_epsilon = 5 # max pixel distance to count as a vertex hit
def _init_boundary_interactor(self):
"""Send polyclick thread to boundary interactor"""
# Get rid old mpl connections.
self._ax.figure.canvas.mpl_disconnect(self._key_id)
self._ax.figure.canvas.mpl_disconnect(self._click_id)
# Shade the selected region in a polygon
self._poly = Polygon(self.verts, alpha=0.2, fc='k', animated=True)
self._ax.add_patch(self._poly)
# modify the line properties
self._line.set_markerfacecolor('k')
# get the canvas and connect the callback events
cid = self._poly.add_callback(self._poly_changed)
self._ind = None # the active vert
self._canvas.mpl_connect('draw_event', self._draw_callback)
self._canvas.mpl_connect('button_press_event', self._button_press_callback)
self._canvas.mpl_connect('key_press_event', self._key_press_callback)
self._canvas.mpl_connect('button_release_event', self._button_release_callback)
self._canvas.mpl_connect('motion_notify_event', self._motion_notify_callback)
def _draw_callback(self, event):
self._background = self._canvas.copy_from_bbox(self._ax.bbox)
self._ax.draw_artist(self._poly)
self._ax.draw_artist(self._line)
self._canvas.blit(self._ax.bbox)
def _poly_changed(self, poly):
'this method is called whenever the polygon object is called'
# only copy the artist props to the line (except visibility)
vis = self._line.get_visible()
Artist.update_from(self._line, poly)
self._line.set_visible(vis) # don't use the poly visibility state
def _get_ind_under_point(self, event):
'get the index of the vertex under point if within epsilon tolerance'
try:
x, y = zip(*self._poly.xy)
# display coords
xt, yt = self._poly.get_transform().numerix_x_y(x, y)
d = sqrt((xt-event.x)**2 + (yt-event.y)**2)
indseq = nonzero(equal(d, amin(d)))
ind = indseq[0]
if d[ind]>=self._epsilon:
ind = None
return ind
except:
#.........这里部分代码省略.........