def __init__(self, on_interact=None, output=None, overwrite_previous_output=True, feedback=False, run=True, action_kws={}, *args, **kwargs): super().__init__(on_interact=on_interact, output=output, overwrite_previous_output=overwrite_previous_output, feedback=feedback, action_kws=action_kws) self.widget = widgets.ColorPicker(*args, **kwargs) if run: self.run()
def updateSubsets(self): v = [] for sset in self.gluemanager.data.subsets: kt = sset.label color = sset.style.color vc2 = widgets.Button(description=kt, style=widgets.ButtonStyle(button_color=color), disabled=False, layout=widgets.Layout( min_width='min-content', max_width='min-content')) vc3 = widgets.Button(description="", style=widgets.ButtonStyle(button_color=color), icon='remove', disabled=False, layout=widgets.Layout(width='40px')) vc3.on_click(lambda event, this=self, value=[kt]: this. deleteSubsetFromSelection(value)) icon = 'eye' if hasattr(sset, 'disabled') and sset.disabled is True: icon = 'eye-slash' vc1 = widgets.Button(description="", style=widgets.ButtonStyle(button_color=color), icon=icon, disabled=False, layout=widgets.Layout(width='40px'), value=True) vc1.on_click(lambda event, this=self, value=kt, vc=vc1: this. disableComponentFromSelection(value, vc)) vc4 = widgets.ColorPicker(description="", concise=True, value=sset.style.color, layout=widgets.Layout(width='40px', min_width='')) vc4.observe( lambda change, this=self, value=kt, vc=[vc1, vc2, vc3]: this. changeSubsetColorFromSelection(value, change['new'], vc), "value") vv = widgets.HBox([vc1, vc2, vc3, vc4], layout=widgets.Layout(width='auto')) v.append(vv) self.subsetsui.children = v
def orthoslices_3D(data, normalize=True, continuous_update=False, **kwargs): if not isnotebook: print('Function not suited for working outside of Jupyter notebooks!') else: get_ipython().magic('matplotlib notebook') get_ipython().magic('matplotlib notebook') e_range, x_range, y_range = data.shape dmin = np.amin(data) dmax = np.amax(data) w_e = widgets.IntSlider(value=e_range // 2, min=0, max=e_range - 1, step=1, description='Energy:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kx = widgets.IntSlider(value=x_range // 2, min=0, max=x_range - 1, step=1, description='kx:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_ky = widgets.IntSlider(value=y_range // 2, min=0, max=y_range - 1, step=1, description='ky:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_clim = widgets.FloatRangeSlider(value=[.1, .9], min=0, max=1, step=0.001, description='Contrast:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='.1f') w_cmap = widgets.Dropdown(options=cmaps, value='terrain', description='colormap:', disabled=False) w_bin = widgets.BoundedIntText(value=1, min=1, max=min(data.shape), step=1, description='resample:', disabled=False) w_interpolate = widgets.Checkbox(value=True, description='Interpolate', disabled=False) w_grid = widgets.Checkbox(value=False, description='Grid', disabled=False) w_trackers = widgets.Checkbox(value=True, description='Trackers', disabled=False) w_trackercol = widgets.ColorPicker(concise=False, description='tracker line color', value='orange') ui_pos = widgets.HBox([w_e, w_kx, w_ky]) ui_color = widgets.HBox([ widgets.VBox([w_clim, w_cmap]), widgets.VBox([w_bin, w_interpolate, w_grid]), widgets.VBox([w_trackers, w_trackercol]), ]) children = [ui_pos, ui_color] tab = widgets.Tab(children=children, ) tab.set_title(0, 'data select') tab.set_title(1, 'colormap') figsize = kwargs.pop('figsize', (5, 5)) fig = plt.figure(figsize=figsize, **kwargs) plt.tight_layout() # [left, bottom, width, height] # fig.locator_params(nbins=4) # cbar_ax = fig.add_axes([.05,.4,.05,4], xticklabels=[], yticklabels=[]) # cbar_ax.yaxis.set_major_locator(plt.LinearLocator(5)) img_ax = fig.add_axes([.15, .4, .4, .4], xticklabels=[], yticklabels=[]) img_ax.xaxis.set_major_locator(plt.LinearLocator(5)) img_ax.yaxis.set_major_locator(plt.LinearLocator(5)) xproj_ax = fig.add_axes([.15, .1, .4, .28], xticklabels=[], yticklabels=[]) xproj_ax.set_xlabel('$k_x$') xproj_ax.xaxis.set_major_locator(plt.LinearLocator(5)) yproj_ax = fig.add_axes([.57, .4, .28, .4], xticklabels=[], yticklabels=[]) yproj_ax.yaxis.set_label_position("right") yproj_ax.set_ylabel('$k_y$') yproj_ax.yaxis.set_major_locator(plt.LinearLocator(5)) for ax in [img_ax, yproj_ax, xproj_ax]: # ,cbar_ax]: ax.tick_params(axis="both", direction="in", bottom=True, top=True, left=True, right=True, which='both') clim_ = 0.01, .99 e_img = norm_img(data[data.shape[0] // 2, :, :]) y_img = norm_img(data[:, data.shape[1] // 2, :]) x_img = norm_img(data[:, :, data.shape[2] // 2].T) e_plot = img_ax.imshow( e_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') x_plot = yproj_ax.imshow( x_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') y_plot = xproj_ax.imshow( y_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') pe_x = img_ax.axvline(x_range / 2, c='orange') pe_y = img_ax.axhline(y_range / 2, c='orange') px_x = xproj_ax.axvline(x_range / 2, c='orange') px_e = xproj_ax.axhline(e_range / 2, c='orange') py_y = yproj_ax.axhline(y_range / 2, c='orange') py_e = yproj_ax.axvline(e_range / 2, c='orange') def update(e, kx, ky, clim, cmap, binning, interpolate, grid, trackers, trackerscol): if normalize: e_img = norm_img(data[e, :, :][::binning, ::binning]) y_img = norm_img(data[:, ky, :][::binning, ::binning]) x_img = norm_img(data[:, :, kx][::binning, ::binning]) else: e_img = data[e, :, :][::binning, ::binning] y_img = data[:, ky, :][::binning, ::binning] x_img = data[:, :, kx][::binning, ::binning] for axis, plot, img in zip([img_ax, yproj_ax, xproj_ax], [e_plot, x_plot, y_plot], [e_img, x_img.T, y_img]): plot.set_data(img) plot.set_clim(clim) plot.set_cmap(cmap) axis.grid(grid) if interpolate: plot.set_interpolation('gaussian') else: plot.set_interpolation(None) if trackers: pe_x.set_xdata(kx) pe_x.set_color(trackerscol) pe_y.set_ydata(ky) pe_y.set_color(trackerscol) px_x.set_xdata(kx) px_x.set_color(trackerscol) px_e.set_ydata(e) px_e.set_color(trackerscol) py_y.set_ydata(ky) py_y.set_color(trackerscol) py_e.set_xdata(e) py_e.set_color(trackerscol) interactive_plot = interactive_output( update, { 'e': w_e, 'kx': w_kx, 'ky': w_ky, 'clim': w_clim, 'cmap': w_cmap, 'binning': w_bin, 'interpolate': w_interpolate, 'grid': w_grid, 'trackers': w_trackers, 'trackerscol': w_trackercol, }) display(interactive_plot, tab)
def orthoslices_4D(data, axis_order=['E', 'kx', 'ky', 'kz'], normalize=True, continuous_update=True, **kwargs): if not isnotebook: raise EnvironmentError( 'Function not suited for working outside of Jupyter notebooks!') else: get_ipython().magic('matplotlib notebook') get_ipython().magic('matplotlib notebook') assert len( data.shape ) == 4, 'Data should be 4-dimensional, but data has {} dimensions'.format( data.shape) # make controls for data slicers # slicers = [] # for shape, name in zip(data.shape, axis_order): # slicers.append(widgets.IntSlider(value=shape // 2, # min=0, # max=shape - 1, # step=1, # description=name, # disabled=False, # continuous_update=False, # orientation='horizontal', # readout=True, # readout_format='d' # )) e_range, x_range, y_range, z_range = data.shape w_e = widgets.IntSlider(value=e_range // 2, min=0, max=e_range - 1, step=1, description='Energy:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kx = widgets.IntSlider(value=x_range // 2, min=0, max=x_range - 1, step=1, description='kx:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_ky = widgets.IntSlider(value=y_range // 2, min=0, max=y_range - 1, step=1, description='ky:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kz = widgets.IntSlider(value=z_range // 2, min=0, max=z_range - 1, step=1, description='kz:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') slicers = [w_e, w_kx, w_ky, w_kz] ui_slicers = widgets.HBox(slicers) # make controls for graphics appearance w_clim = widgets.FloatRangeSlider(value=[.1, .9], min=0, max=1, step=0.001, description='Contrast:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='.1f') w_cmap = widgets.Dropdown(options=cmaps, value='terrain', description='colormap:', disabled=False) w_bin = widgets.BoundedIntText(value=1, min=1, max=min(data.shape), step=1, description='resample:', disabled=False) w_interpolate = widgets.Checkbox(value=True, description='Interpolate', disabled=False) w_grid = widgets.Checkbox(value=False, description='Grid', disabled=False) w_trackers = widgets.Checkbox(value=True, description='Trackers', disabled=False) w_trackercol = widgets.ColorPicker(concise=False, description='tracker line color', value='orange') ui_color = widgets.HBox([ widgets.VBox([w_clim, w_cmap]), widgets.VBox([w_bin, w_interpolate, w_grid]), widgets.VBox([w_trackers, w_trackercol]), ]) tab = widgets.Tab(children=[ui_slicers, ui_color], ) tab.set_title(0, 'Data slicing') tab.set_title(1, 'Graphics') figsize = kwargs.pop('figsize', (5, 5)) fig = plt.figure(figsize=figsize, **kwargs) plt.tight_layout() img_ax = fig.add_axes([.15, .4, .4, .4], xticklabels=[], yticklabels=[]) img_ax.xaxis.set_major_locator(plt.LinearLocator(5)) img_ax.yaxis.set_major_locator(plt.LinearLocator(5)) xproj_ax = fig.add_axes([.15, .1, .4, .28], xticklabels=[], yticklabels=[]) xproj_ax.set_xlabel('$k_x$') xproj_ax.xaxis.set_major_locator(plt.LinearLocator(5)) yproj_ax = fig.add_axes([.57, .4, .28, .4], xticklabels=[], yticklabels=[]) yproj_ax.yaxis.set_label_position("right") yproj_ax.set_ylabel('$k_y$') yproj_ax.yaxis.set_major_locator(plt.LinearLocator(5)) for ax in [img_ax, yproj_ax, xproj_ax]: # ,cbar_ax]: ax.tick_params(axis="both", direction="in", bottom=True, top=True, left=True, right=True, which='both') clim_ = 0.01, .99 e_img = norm_img(data[data.shape[0] // 2, :, :, data.shape[3] // 2]) y_img = norm_img(data[:, data.shape[1] // 2, :, data.shape[3] // 2]) x_img = norm_img(data[:, :, data.shape[2] // 2, data.shape[3] // 2].T) e_plot = img_ax.imshow( e_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') x_plot = yproj_ax.imshow( x_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') y_plot = xproj_ax.imshow( y_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') pe_x = img_ax.axvline(x_range / 2, c='orange') pe_y = img_ax.axhline(y_range / 2, c='orange') px_x = xproj_ax.axvline(x_range / 2, c='orange') px_e = xproj_ax.axhline(e_range / 2, c='orange') py_y = yproj_ax.axhline(y_range / 2, c='orange') py_e = yproj_ax.axvline(e_range / 2, c='orange') def update(e, kx, ky, kz, clim, cmap, binning, interpolate, grid, trackers, trackerscol): if normalize: e_img = norm_img(data[e, :, :, kz][::binning, ::binning]) y_img = norm_img(data[:, ky, :, kz][::binning, ::binning]) x_img = norm_img(data[:, :, kx, kz][::binning, ::binning]) else: e_img = data[e, :, :, kz][::binning, ::binning] y_img = data[:, ky, :, kz][::binning, ::binning] x_img = data[:, :, kx, kz][::binning, ::binning] for axis, plot, img in zip([img_ax, yproj_ax, xproj_ax], [e_plot, x_plot, y_plot], [e_img, x_img.T, y_img]): plot.set_data(img) plot.set_clim(clim) plot.set_cmap(cmap) axis.grid(grid) if interpolate: plot.set_interpolation('gaussian') else: plot.set_interpolation(None) if trackers: pe_x.set_xdata(kx) pe_x.set_color(trackerscol) pe_y.set_ydata(ky) pe_y.set_color(trackerscol) px_x.set_xdata(kx) px_x.set_color(trackerscol) px_e.set_ydata(e) px_e.set_color(trackerscol) py_y.set_ydata(ky) py_y.set_color(trackerscol) py_e.set_xdata(e) py_e.set_color(trackerscol) interactive_plot = interactive_output( update, { 'e': w_e, 'kx': w_kx, 'ky': w_ky, 'kz': w_kz, 'clim': w_clim, 'cmap': w_cmap, 'binning': w_bin, 'interpolate': w_interpolate, 'grid': w_grid, 'trackers': w_trackers, 'trackerscol': w_trackercol, }) display(interactive_plot, tab)
#Extract the renamed columns, and combine them into a new dataframe data_intensity = pd.DataFrame((bike_traffic_df1['Celleneuve'], bike_traffic_df2['Lattes2'],bike_traffic_df3['Berracasa'],bike_traffic_df4['Lavérune'],bike_traffic_df5['Lattes1'],bike_traffic_df6['Vieille_poste'],bike_traffic_df7['Gerhardt'],bike_traffic_df8['Tanneurs'],bike_traffic_df9['Delmas1'],bike_traffic_df10['Delmas2'])) data_intensity=data_intensity.T #Indexing neww data by 'end_of-day' (time series) data_intensity['startday'] = time_improved data_intensity = data_intensity.set_index(['startday']) print(data_intensity ) #%% from ipywidgets import widgets color_picker = widgets.ColorPicker( concise=True, description='Background color:', value='#efefef', ) color_picker color_buttons = widgets.ToggleButtons( options=['blue', 'red', 'green','black'], description='Color:', ) color_buttons #%% def Intenity_visualisation( count_point ='latte1', day_month='d', efefef='red', start_date='2020-12-15', end_date='2021-04-01', color='black'): fig, ax = plt.subplots(1, 1, figsize=(12, 6))
def createPlotsPanel(self): components = self.gluemanager.data.components pixel_component_ids = self.gluemanager.data.pixel_component_ids world_component_ids = self.gluemanager.data.world_component_ids v = [] for k in components: if k not in world_component_ids: #k not in pixel_component_ids and kt = str(k) color = self.gluemanager.data.get_component(k).color color = re.match(GlueManagerWidget.r, color) color = (int(color[1]), int(color[2]), int(color[3])) color = '#%02x%02x%02x' % color vc1 = widgets.Checkbox(value=False, tooltip=kt, indent=False, layout=widgets.Layout(width='40px')) vc2 = widgets.Button( description=kt, style=widgets.ButtonStyle(button_color=color), disabled=False, layout=widgets.Layout(min_width='min-content', max_width='min-content')) vc2.on_click( lambda event, v=vc1: setattr(v, 'value', not v.value)) vc3 = widgets.ColorPicker(description="", concise=True, value=color, layout=widgets.Layout(width='40px', min_width='')) vc3.observe(lambda change, this=self, value=kt, vc=[vc2]: this. changeComponentColorFromSelection( value, change['new'], vc), "value") vv = widgets.HBox([vc3, vc2, vc1], layout=widgets.Layout(width='auto')) v.append(vv) self.dimensions = widgets.HBox(v, layout=widgets.Layout(display='flex', flex_flow='wrap')) cr = widgets.Button(description='Create new visualization', disabled=False, button_style='', tooltip='', layout=widgets.Layout(width='100%')) views = self.gluemanager.listPlots() dd = widgets.Dropdown(options=views, value=views[0], disabled=False, layout=widgets.Layout(width='auto')) ss = widgets.Checkbox( value=False, description='Only subsets', disabled=False, indent=False, ) tx = widgets.Text(value='', placeholder='New_Visualization', disabled=False, layout=widgets.Layout(width='auto')) hb1 = widgets.HBox([ss, cr], layout=widgets.Layout(width='auto')) vb1 = widgets.VBox([self.dimensions, dd, tx, hb1], layout=widgets.Layout(width='auto')) from IPython.display import display cr.on_click(lambda e, b=self.dimensions, this=self: this.createNewView( e, dd, b, tx, ss)) return vb1
def draw_workflow(self, start_end, workflow, name): assert isinstance(workflow, Workflow) start_s = start_end["seconds"]["start"] last_s = start_end["seconds"]["last"] start_t = start_end["time"]["start"] last_t = start_end["time"]["last"] # 1. get main stacked axis list main_stacked_results = [] main_stacked_results.append(("BLANK", "#eeeeee", [ (0, c.from_seconds) for c in chain.from_iterable( s.intervals for s in workflow.start_group.iter_nxtgroups()) ])) for group in workflow.sort_topologically(): _name = group.desc color = getcolor_byint(group.intervals[0], ignore_lr=True) main_stacked_results.append( (_name, color, [(c.from_seconds, c.to_seconds) for c in group.intervals])) # 2. calc main_x_list from main_stacked_results types, colors, main_x_list, main_ys_list =\ _generate_stackeddata(main_stacked_results) # 3. calc and check the arguments x_start_default = 0 y_start_default = 0 x_end_default = last_s * 1.05 y_end_default = workflow.len_reqs def _interact(x, y, selects, color): with self._build_fig("workflowplot", name, figsize=(30, 6)) as fig: ax = fig.add_subplot(1, 1, 1) ax.set_xlabel("lapse (seconds)") ax.set_ylabel("requests") ax.set_xlim(x[0], x[1]) ax.set_ylim(y[0], y[1]) plot_colors = colors[:] if color: for s in selects: plot_colors[s] = color ax.annotate(start_t, xy=(0, 0), xytext=(0, 0)) ax.annotate(last_t, xy=(last_s, 0), xytext=(last_s, 0)) ax.plot([0, last_s], [0, 0], 'r*') ax.stackplot(main_x_list, *main_ys_list, colors=plot_colors, edgecolor="black", linewidth=.1) # ax.legend((mpatches.Patch(color=color) for color in colors), types) if self.out_path: _interact((x_start_default, x_end_default), (y_start_default, y_end_default), [], None) else: from ipywidgets import widgets, interactive_output, fixed, Layout from IPython.display import display layout = Layout(width="99%") w_lapse = widgets.FloatRangeSlider( value=[x_start_default, x_end_default], min=x_start_default, max=x_end_default, step=0.0001, description='x-lapse:', continuous_update=False, readout_format='.4f', layout=layout) w_requests = widgets.IntRangeSlider( value=[y_start_default, y_end_default], min=y_start_default, max=y_end_default, description='y-requests:', continuous_update=False, layout=layout) w_range = widgets.VBox([w_lapse, w_requests]) w_color = widgets.ColorPicker(concise=True, description='Highlight:', value='#ff40ff', layout=layout) options = [types[i] for i in range(1, len(types) - 1)] dedup = defaultdict(lambda: -1) for i, o in enumerate(options): dedup[o] += 1 if dedup[o]: options[i] = ("%s (%d)" % (options[i], dedup[o])) options = [(v, i + 1) for i, v in enumerate(options)] w_select = widgets.SelectMultiple(options=options, rows=min(10, len(options)), description='Steps:', layout=layout) w_highlight = widgets.VBox([w_color, w_select]) w_tab = widgets.Tab() w_tab.children = [w_range, w_highlight] w_tab.set_title(0, "range") w_tab.set_title(1, "highlight") out = widgets.interactive_output( _interact, { 'x': w_lapse, 'y': w_requests, 'selects': w_select, 'color': w_color }) display(w_tab, out)
def make_colorpicker(color): return widgets.ColorPicker(concise=False, description='Pick a color', value=color, disabled=False)
def __init__(self, fig): super().__init__() self.fig = fig self.nSubs = sum(['xaxis' in i for i in fig['layout']]) # Layout control widgets field_lay = widgets.Layout(max_height='40px', max_width='120px', min_height='30px', min_width='70px') fonts_names = ["Arial", "Balto", "Courier New", "Droid Sans", "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman"] fonts_list = [(fnt, i+1) for i, fnt in enumerate(fonts_names)] tickoptions_names = ['inside', 'outside', ''] tickoptions_list = [(v, i+1) for i, v in enumerate(tickoptions_names)] # General -------------------------------------------------------------- chk_general_autosize = widgets.Checkbox( value=fig.layout.autosize, description='Autosize') self.txt_gen_width = widgets.FloatText(value=fig.layout.width, layout=field_lay) self.txt_gen_height = widgets.FloatText(value=fig.layout.height, layout=field_lay) hb_dims = HBox([widgets.Label('width/height:'), self.txt_gen_width, self.txt_gen_height]) txt_fontsize = widgets.FloatText(value=fig.layout.font.size, layout=field_lay) drd_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.font.family)+1) drd_fontfamily.observe(self.set_gen_fontfamily, names='label') clr_font = widgets.ColorPicker(concise=True, value=fig.layout.font.color) hb_font = HBox([widgets.Label('font:'), txt_fontsize, drd_fontfamily, clr_font]) clr_paperbg = widgets.ColorPicker(layout=field_lay, concise=True, value=fig.layout.paper_bgcolor, description='paper_bgcolor') clr_plotbg = widgets.ColorPicker(layout=field_lay, concise=True, value=fig.layout.plot_bgcolor, description='plot_bgcolor') hb_colorbg = HBox([clr_paperbg, clr_plotbg]) drd_hovermode = widgets.Dropdown( options=[('Closest', 1), ('x', 2), ('y', 3), ('False', 4)], value=1, layout=field_lay) drd_hovermode.observe(self.set_gen_hovermode, names='label') hb_hovermode = HBox([widgets.Label('hovermode:'), drd_hovermode]) vb_general = VBox([chk_general_autosize, hb_dims, hb_font, hb_colorbg, hb_hovermode]) controls_general = { 'autosize': chk_general_autosize, 'width': self.txt_gen_width, 'height': self.txt_gen_height, 'fontsize': txt_fontsize, 'fontcolor': clr_font, 'paperbgcolor': clr_paperbg, 'plotbgcolor': clr_plotbg, } widgets.interactive_output(self.set_general, controls_general) # Title ---------------------------------------------------------------- txt_titletext = widgets.Text(value=fig.layout.title.text, description='Text:') txt_titlefontsize = widgets.FloatText(value=fig.layout.titlefont.size, layout=field_lay) drd_titlefontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.titlefont.family)+1) drd_titlefontfamily.observe(self.set_gen_titlefontfamily, names='label') clr_titlefont = widgets.ColorPicker(concise=True, value=fig.layout.titlefont.color) hb_title = HBox([widgets.Label('font:'), txt_titlefontsize, drd_titlefontfamily, clr_titlefont]) vb_title = VBox([txt_titletext, hb_title]) controls = { 'title_text': txt_titletext, 'title_fontsize': txt_titlefontsize, 'title_fontcolor': clr_titlefont, } widgets.interactive_output(self.set_title, controls) # X axis --------------------------------------------------------------- chk_xaxis_visible = widgets.Checkbox( value=fig.layout.xaxis.visible, description='Visible') clr_xaxis = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.color) hb0_xaxis = HBox([chk_xaxis_visible, clr_xaxis]) txt_xaxis_fontsize = widgets.FloatText(value=fig.layout.xaxis.titlefont.size, layout=field_lay) drd_xaxis_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.xaxis.titlefont.family)+1) drd_xaxis_fontfamily.observe(self.set_xaxis_titlefontfamily, names='label') clr_xaxis_font = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.titlefont.color) hb1_xaxis = HBox([widgets.Label('font:'), txt_xaxis_fontsize, drd_xaxis_fontfamily, clr_xaxis_font]) drd_xaxis_ticks = widgets.Dropdown( options=tickoptions_list, layout=field_lay, value=tickoptions_names.index(fig.layout.xaxis.ticks)+1) drd_xaxis_ticks.observe(self.set_xaxis_ticks, names='label') txt_xaxis_nticks = widgets.IntText(value=fig.layout.xaxis.nticks, layout=field_lay) hb2_xaxis = HBox([widgets.Label('ticks:'), drd_xaxis_ticks, txt_xaxis_nticks]) txt_xaxis_ticklen = widgets.FloatText(value=fig.layout.xaxis.ticklen, layout=field_lay) txt_xaxis_tickwid = widgets.FloatText(value=fig.layout.xaxis.tickwidth, layout=field_lay) clr_xaxis_tick = widgets.ColorPicker(concise=True, value=fig.layout.xaxis.tickcolor) hb3_xaxis = HBox([widgets.Label('ticks len/wid:'), txt_xaxis_ticklen, txt_xaxis_tickwid, clr_xaxis_tick]) chk_xaxis_showticklabels = widgets.Checkbox( value=fig.layout.xaxis.showticklabels, description='Show tick labels') chk_xaxis_tickangle = widgets.Checkbox( value=not isinstance(fig.layout.xaxis.tickangle, (int, float)), description='auto') self.txt_xaxis_tickangle = widgets.FloatText( value=fig.layout.xaxis.tickangle if fig.layout.xaxis.tickangle != 'auto' else 0, layout=field_lay) hb4_xaxis = HBox([widgets.Label('ticks angle:'), chk_xaxis_tickangle, self.txt_xaxis_tickangle]) vb_xaxis = VBox([hb0_xaxis, hb1_xaxis, hb2_xaxis, hb3_xaxis, chk_xaxis_showticklabels, hb4_xaxis]) xaxis_controls = { 'visible': chk_xaxis_visible, 'color': clr_xaxis, 'title_fontsize': txt_xaxis_fontsize, 'title_fontcolor': clr_xaxis_font, 'nticks': txt_xaxis_nticks, 'ticklen': txt_xaxis_ticklen, 'tickwid': txt_xaxis_tickwid, 'tickcolor': clr_xaxis_tick, 'showticklabels': chk_xaxis_showticklabels, 'tickangleauto': chk_xaxis_tickangle, 'tickangle': self.txt_xaxis_tickangle, } widgets.interactive_output(self.set_xaxis, xaxis_controls) # Y axis --------------------------------------------------------------- chk_yaxis_visible = widgets.Checkbox( value=fig.layout.yaxis.visible, description='Visible') clr_yaxis = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.color) hb0_yaxis = HBox([chk_yaxis_visible, clr_yaxis]) txt_yaxis_fontsize = widgets.FloatText(value=fig.layout.yaxis.titlefont.size, layout=field_lay) drd_yaxis_fontfamily = widgets.Dropdown( options=fonts_list, layout=field_lay, value=fonts_names.index(fig.layout.yaxis.titlefont.family)+1) drd_yaxis_fontfamily.observe(self.set_yaxis_titlefontfamily, names='label') clr_yaxis_font = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.titlefont.color) hb1_yaxis = HBox([widgets.Label('font:'), txt_yaxis_fontsize, drd_yaxis_fontfamily, clr_yaxis_font]) drd_yaxis_ticks = widgets.Dropdown( options=tickoptions_list, layout=field_lay, value=tickoptions_names.index(fig.layout.yaxis.ticks)+1) drd_yaxis_ticks.observe(self.set_yaxis_ticks, names='label') txt_yaxis_nticks = widgets.IntText(value=fig.layout.yaxis.nticks, layout=field_lay) hb2_yaxis = HBox([widgets.Label('ticks:'), drd_yaxis_ticks, txt_yaxis_nticks]) txt_yaxis_ticklen = widgets.FloatText(value=fig.layout.yaxis.ticklen, layout=field_lay) txt_yaxis_tickwid = widgets.FloatText(value=fig.layout.yaxis.tickwidth, layout=field_lay) clr_yaxis_tick = widgets.ColorPicker(concise=True, value=fig.layout.yaxis.tickcolor) hb3_yaxis = HBox([widgets.Label('ticks len/wid:'), txt_yaxis_ticklen, txt_yaxis_tickwid, clr_yaxis_tick]) chk_yaxis_showticklabels = widgets.Checkbox( value=fig.layout.yaxis.showticklabels, description='Show tick labels') chk_yaxis_tickangle = widgets.Checkbox( value=not isinstance(fig.layout.yaxis.tickangle, (int, float)), description='auto') self.txt_yaxis_tickangle = widgets.FloatText( value=fig.layout.yaxis.tickangle if fig.layout.yaxis.tickangle != 'auto' else 0, layout=field_lay) hb4_yaxis = HBox([widgets.Label('ticks angle:'), chk_yaxis_tickangle, self.txt_yaxis_tickangle]) vb_yaxis = VBox([hb0_yaxis, hb1_yaxis, hb2_yaxis, hb3_yaxis, chk_yaxis_showticklabels, hb4_yaxis]) yaxis_controls = { 'visible': chk_yaxis_visible, 'color': clr_yaxis, 'title_fontsize': txt_yaxis_fontsize, 'title_fontcolor': clr_yaxis_font, 'nticks': txt_yaxis_nticks, 'ticklen': txt_yaxis_ticklen, 'tickwid': txt_yaxis_tickwid, 'tickcolor': clr_yaxis_tick, 'showticklabels': chk_yaxis_showticklabels, 'tickangleauto': chk_yaxis_tickangle, 'tickangle': self.txt_yaxis_tickangle, } widgets.interactive_output(self.set_yaxis, yaxis_controls) # Export --------------------------------------------------------------- # Organize buttons layout ---------------------------------------------- self.tab_nest = widgets.Tab() self.tab_nest.children = [vb_general, vb_title, vb_xaxis, vb_yaxis] self.tab_nest.set_title(0, 'General') self.tab_nest.set_title(1, 'Title') self.tab_nest.set_title(2, 'X axis') self.tab_nest.set_title(3, 'Y axis') acc_all = widgets.Accordion( children=[self.tab_nest], selected_index=None ) acc_all.set_title(0, 'Edit layout') self.children = [acc_all, fig]
def identifica_cor(frame): ''' Segmenta o maior objeto cuja cor é parecida com cor_h (HUE da cor, no espaço HSV). ''' colorpicker = widgets.ColorPicker(concise=False, description='Escolha uma cor', value='#01ff13', disabled=False) hsv1, hsv2 = aux.ranges(colorpicker.value) # No OpenCV, o canal H vai de 0 até 179, logo cores similares ao # vermelho puro (H=0) estão entre H=-8 e H=8. # Precisamos dividir o inRange em duas partes para fazer a detecção # do vermelho: # frame = cv2.flip(frame, -1) # flip 0: eixo x, 1: eixo y, -1: 2 eixos frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) #cor_menor = np.array([52, 50, 50]) #cor_maior = np.array([62, 255, 255]) segmentado_cor = cv2.inRange(frame_hsv, hsv1, hsv2) #cor_menor = np.array([172, 50, 50]) #cor_maior = np.array([180, 255, 255]) #segmentado_cor += cv2.inRange(frame_hsv, cor_menor, cor_maior) # Note que a notacão do numpy encara as imagens como matriz, portanto o enderecamento é # linha, coluna ou (y,x) # Por isso na hora de montar a tupla com o centro precisamos inverter, porque centro = (frame.shape[1] // 2, frame.shape[0] // 2) def cross(img_rgb, point, color, width, length): cv2.line(img_rgb, (point[0] - length / 2, point[1]), (point[0] + length / 2, point[1]), color, width, length) cv2.line(img_rgb, (point[0], point[1] - length / 2), (point[0], point[1] + length / 2), color, width, length) # A operação MORPH_CLOSE fecha todos os buracos na máscara menores # que um quadrado 7x7. É muito útil para juntar vários # pequenos contornos muito próximos em um só. segmentado_cor = cv2.morphologyEx(segmentado_cor, cv2.MORPH_CLOSE, np.ones((7, 7))) # Encontramos os contornos na máscara e selecionamos o de maior área #contornos, arvore = cv2.findContours(segmentado_cor.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contornos, arvore = cv2.findContours(segmentado_cor.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) maior_contorno = None maior_contorno_area = 0 for cnt in contornos: area = cv2.contourArea(cnt) if area > maior_contorno_area: maior_contorno = cnt maior_contorno_area = area # Encontramos o centro do contorno fazendo a média de todos seus pontos. if not maior_contorno is None: cv2.drawContours(frame, [maior_contorno], -1, [0, 0, 255], 5) maior_contorno = np.reshape(maior_contorno, (maior_contorno.shape[0], 2)) media = maior_contorno.mean(axis=0) media = media.astype(np.int32) cv2.circle(frame, (media[0], media[1]), 5, [255, 0, 0]) cross(frame, centro, [0, 255, 0], 1, 17) else: media = (0, 0) # Representa a area e o centro do maior contorno no frame font = cv2.FONT_HERSHEY_COMPLEX_SMALL cv2.putText(frame, "{:d} {:d}".format(*media), (20, 100), 1, 4, (255, 255, 255), 2, cv2.LINE_AA) cv2.putText(frame, "{:0.1f}".format(maior_contorno_area), (20, 50), 1, 4, (255, 255, 255), 2, cv2.LINE_AA) # cv2.imshow('video', frame) cv2.imshow('seg', segmentado_cor) cv2.waitKey(1) return media, centro, maior_contorno_area