def extract_foreground(self, **kwargs): img = self.image if self._initialized: bg, fg = self.draw_bg.element, self.draw_fg.element else: self._initialized = True bg, fg = self.bg_paths, self.fg_paths bg, fg = (gv.project(g, projection=img.crs) for g in (bg, fg)) if not len(bg) or not len(fg): return gv.Path([], img.kdims, crs=img.crs) if self.downsample != 1: kwargs = {'dynamic': False} h, w = img.interface.shape(img, gridded=True) kwargs['width'] = int(w * self.downsample) kwargs['height'] = int(h * self.downsample) img = regrid(img, **kwargs) foreground = extract_foreground(img, background=bg, foreground=fg, iterations=self.iterations) with warnings.catch_warnings(): warnings.filterwarnings('ignore') foreground = gv.Path( [contours(foreground, filled=True, levels=1).split()[0].data], kdims=foreground.kdims, crs=foreground.crs) self.result = gv.project(foreground, projection=self.crs) return foreground
def __init__(self, image, fg_data=[], bg_data=[], **params): self.image = image super(GrabCutDashboard, self).__init__(transient=True, **params) self.bg_paths = gv.project(self.path_type(bg_data, crs=self.crs), projection=image.crs) self.fg_paths = gv.project(self.path_type(fg_data, crs=self.crs), projection=image.crs) self.draw_bg = PolyDraw(source=self.bg_paths) self.draw_fg = PolyDraw(source=self.fg_paths) self._initialized = False
def __init__(self, image, fg_data=[], bg_data=[], **params): self.image = image super(GrabCutPanel, self).__init__(**params) self.bg_paths = gv.project(self.path_type(bg_data, crs=self.crs), projection=image.crs) self.fg_paths = gv.project(self.path_type(fg_data, crs=self.crs), projection=image.crs) self.draw_bg = FreehandDraw(source=self.bg_paths) self.draw_fg = FreehandDraw(source=self.fg_paths) self._initialized = False self._filter = False
def __init__(self, image, fg_data=[], bg_data=[], **params): self.image = image super(GrabCutDashboard, self).__init__(transient=True, **params) self.bg_paths = gv.project(self.path_type(bg_data, crs=self.crs), projection=image.crs) self.fg_paths = gv.project(self.path_type(fg_data, crs=self.crs), projection=image.crs) self.draw_bg = FreehandDraw(source=self.bg_paths) self.draw_fg = FreehandDraw(source=self.fg_paths) self.filter_stream = hv.streams.Stream.define( 'Filter', filter=False)(transient=True) self._initialized = False self._filter = False
def _link_polys(self): style = dict(editable=True) plot = dict(width=self.table_width, height=self.table_height) # Add annotation columns to poly data for col in self.poly_columns: if col not in self.polys: self.polys = self.polys.add_dimension(col, 0, '', True) self.poly_stream.source = self.polys self.vertex_stream.source = self.polys self._poly_selection.source = self.polys if len(self.polys): poly_data = gv.project(self.polys).split() self.poly_stream.event( data={ kd.name: [p.dimension_values(kd) for p in poly_data] for kd in self.polys.kdims }) poly_data = { c: self.polys.dimension_values(c, expanded=False) for c in self.poly_columns } if len(set(len(v) for v in poly_data.values())) != 1: raise ValueError('poly_columns must refer to value dimensions ' 'which vary per path while at least one of ' '%s varies by vertex.' % self.poly_columns) self.poly_table = Table(poly_data, self.poly_columns, []).opts(plot=plot, style=style) self.poly_link = DataLink(source=self.polys, target=self.poly_table) self.vertex_table = Table([], self.polys.kdims, self.vertex_columns).opts(plot=plot, style=style) self.vertex_link = VertexTableLink(self.polys, self.vertex_table)
def contour(self, x=None, y=None, z=None, data=None, filled=False): from holoviews.operation import contours if 'projection' in self._plot_opts: import cartopy.crs as ccrs t = self._plot_opts['projection'] if isinstance(t, ccrs.CRS) and not isinstance(t, ccrs.Projection): raise ValueError('invalid transform:' ' Spherical contouring is not supported - ' ' consider using PlateCarree/RotatedPole.') opts = dict(plot=self._plot_opts, style=self._style_opts, norm=self._norm_opts) qmesh = self.quadmesh(x, y, z, data) if self.geo: # Apply projection before rasterizing import cartopy.crs as ccrs from geoviews import project projection = self._plot_opts.get('projection', ccrs.GOOGLE_MERCATOR) qmesh = project(qmesh, projection=projection) if filled: opts['style']['line_alpha'] = 0 if opts['plot']['colorbar']: opts['plot']['show_legend'] = False levels = self.kwds.get('levels', 5) if isinstance(levels, int): opts['plot']['color_levels'] = levels return contours(qmesh, filled=filled, levels=levels).opts(**opts)
def fg_path_view(self): if self._clear: self._fg_data = [] elif self._initialized: self._fg_data = self.draw_fg.element.data else: self._fg_data = gv.project(self.path_type(self._fg_data, crs=self.crs), projection=self.image.crs) return self.path_type(self._fg_data, crs=self.image.crs)
def _link_points(self): style = dict(editable=True) plot = dict(width=self.table_width, height=self.table_height) for col in self.point_columns: if col not in self.points: self.points = self.points.add_dimension(col, 0, None, True) self.point_stream = PointDraw(source=self.points, data={}) projected = gv.project(self.points, projection=ccrs.PlateCarree()) self.point_table = Table(projected).opts(plot=plot, style=style) self.point_link = PointTableLink(source=self.points, target=self.point_table)
def __init__(self, poly_data={}, **params): super(PolyAnnotator, self).__init__(**params) style = dict(editable=True) plot = dict(width=self.width, height=self.table_height) self.polys.data = poly_to_geopandas(self.polys, self.poly_columns) self.polys.interface = GeoPandasInterface if len(self.polys): poly_data = gv.project(self.polys).split() self.poly_stream.event( data={ kd.name: [p.dimension_values(kd) for p in poly_data] for kd in self.polys.kdims }) self.poly_table = Table(self.polys.data, self.poly_columns, []).opts(plot=plot, style=style)
def extract_foreground(self, **kwargs): img = self.image bg, fg = self.bg_path_view(), self.fg_path_view() self._initialized = True if not len(bg) or not len(fg): return gv.Path([], img.kdims, crs=img.crs) if self.downsample != 1: kwargs = {'dynamic': False} h, w = img.interface.shape(img, gridded=True) kwargs['width'] = int(w*self.downsample) kwargs['height'] = int(h*self.downsample) img = regrid(img, **kwargs) foreground = extract_foreground(img, background=bg, foreground=fg, iterations=self.iterations) foreground = gv.Path([contours(foreground, filled=True, levels=1).split()[0].data], kdims=foreground.kdims, crs=foreground.crs) self.result = gv.project(foreground, projection=self.crs) return foreground
def _simplify_contours(self, obj, **kwargs): if self.tolerance > 0: obj = simplify_paths(obj, tolerance=self.tolerance) self.result = gv.project(obj, projection=self.crs) return obj
def __call__(self, kind, x, y): kind = self.kind or kind method = getattr(self, kind) groups = self.groupby zs = self.kwds.get('z', []) if not isinstance(zs, list): zs = [zs] grid = [] if self.row: grid.append(self.row) if self.col: grid.append(self.col) groups += grid if groups or len(zs) > 1: if self.streaming: raise NotImplementedError( "Streaming and groupby not yet implemented") data = self.data if not self.gridded and any(g in self.indexes for g in groups): data = data.reset_index() dataset = Dataset(data) if groups: dataset = dataset.groupby(groups, dynamic=self.dynamic) if len(zs) > 1: dimensions = [Dimension(self.group_label, values=zs) ] + dataset.kdims if self.dynamic: obj = DynamicMap( lambda *args: getattr(self, kind) (x, y, args[0], dataset[args[1:]].data), kdims=dimensions) else: obj = HoloMap( {(z, ) + k: getattr(self, kind)(x, y, z, dataset[k]) for k, v in dataset.data.items() for z in zs}, kdims=dimensions) else: obj = dataset.map( lambda ds: getattr(self, kind)(x, y, data=ds.data), Dataset) elif len(zs) > 1: if self.dynamic: dataset = DynamicMap( lambda z: getattr(self, kind) (x, y, z, data=dataset.data), kdims=[Dimension(self.group_label, values=zs)]) else: dataset = HoloMap( { z: getattr(self, kind)(x, y, z, data=dataset.data) for z in zs }, kdims=[self.group_label]) else: obj = getattr(self, kind)(x, y, data=dataset.data) if grid: obj = obj.grid(grid).options(shared_xaxis=True, shared_yaxis=True) else: if self.streaming: cbcallable = StreamingCallable(partial(method, x, y), periodic=self.cb) obj = DynamicMap(cbcallable, streams=[self.stream]) else: obj = method(x, y) if not (self.datashade or self.rasterize): return obj try: from holoviews.operation.datashader import datashade, rasterize, dynspread from datashader import count_cat except: raise ImportError('Datashading is not available') opts = dict(width=self._plot_opts['width'], height=self._plot_opts['height'], dynamic=self.dynamic) if 'cmap' in self._style_opts and self.datashade: levels = self._plot_opts.get('color_levels') opts['cmap'] = process_cmap(self._style_opts['cmap'], levels) opts['color_key'] = opts['cmap'] if self.by: opts['aggregator'] = count_cat(self.by[0]) if self.aggregator: opts['aggregator'] = self.aggregator if self.precompute: opts['precompute'] = self.precompute if self.x_sampling: opts['x_sampling'] = self.x_sampling if self.y_sampling: opts['y_sampling'] = self.y_sampling style = {} if self.datashade: operation = datashade eltype = 'RGB' else: operation = rasterize eltype = 'Image' if 'cmap' in self._style_opts: style['cmap'] = self._style_opts['cmap'] if self.crs: # Apply projection before rasterizing import cartopy.crs as ccrs from geoviews import project projection = self._plot_opts.get('projection', ccrs.GOOGLE_MERCATOR) obj = project(obj, projection=projection) processed = operation(obj, **opts) if self.dynspread: if self.datashade: processed = dynspread(processed, max_px=self.kwds.get('max_px', 3), threshold=self.kwds.get( 'threshold', 0.5)) else: self.warning( 'dynspread may only be applied on datashaded plots, ' 'use datashade=True instead of rasterize=True.') return processed.opts( {eltype: { 'plot': self._plot_opts, 'style': style }})
def _filter_contours(self, obj, **kwargs): if self._filter: obj = filter_polygons(obj, minimum_size=self.minimum_size) self.result = gv.project(obj, projection=self.crs) return obj
def __call__(self, kind, x, y): kind = self.kind or kind method = getattr(self, kind) groups = self.groupby zs = self.kwds.get('z', []) if not isinstance(zs, list): zs = [zs] grid = [] if self.row: grid.append(self.row) if self.col: grid.append(self.col) groups += grid if groups or len(zs) > 1: if self.streaming: raise NotImplementedError( "Streaming and groupby not yet implemented") dataset = Dataset(self.data) if groups: dataset = dataset.groupby(groups, dynamic=self.dynamic) if len(zs) > 1: dimensions = [Dimension(self.group_label, values=zs) ] + dataset.kdims if self.dynamic: obj = DynamicMap( lambda *args: getattr(self, kind) (x, y, args[0], dataset[args[1:]].data), kdims=dimensions) else: obj = HoloMap( {(z, ) + k: getattr(self, kind)(x, y, z, dataset[k]) for k, v in dataset.data.items() for z in zs}, kdims=dimensions) else: obj = dataset.map( lambda ds: getattr(self, kind)(x, y, data=ds.data), Dataset) elif len(zs) > 1: if self.dynamic: dataset = DynamicMap( lambda z: getattr(self, kind) (x, y, z, data=dataset.data), kdims=[Dimension(self.group_label, values=zs)]) else: dataset = HoloMap( { z: getattr(self, kind)(x, y, z, data=dataset.data) for z in zs }, kdims=[self.group_label]) else: obj = getattr(self, kind)(x, y, data=dataset.data) if grid: obj = obj.grid(grid).options(shared_xaxis=True, shared_yaxis=True) else: if self.streaming: cbcallable = StreamingCallable(partial(method, x, y), periodic=self.cb) obj = DynamicMap(cbcallable, streams=[self.stream]) else: obj = method(x, y) if not (self.datashade or self.rasterize): return obj try: from holoviews.operation.datashader import datashade, rasterize from datashader import count_cat except: raise ImportError('Datashading is not available') opts = dict(width=self._plot_opts['width'], height=self._plot_opts['height']) if 'cmap' in self._style_opts and self.datashade: opts['cmap'] = self._style_opts['cmap'] if self.by: opts['aggregator'] = count_cat(self.by[0]) if self.aggregator: opts['aggregator'] = self.aggregator style = {} if self.datashade: operation = datashade eltype = 'RGB' else: operation = rasterize eltype = 'Image' if 'cmap' in self._style_opts: style['cmap'] = self._style_opts['cmap'] if self.crs: # Apply projection before rasterizing import cartopy.crs as ccrs from geoviews import project projection = self._plot_opts.get('projection', ccrs.GOOGLE_MERCATOR) obj = project(obj, projection=projection) return operation(obj, **opts).opts( {eltype: { 'plot': self._plot_opts, 'style': style }})