def play(images, show=True): if len(images.shape) == 4: pass elif len(images.shape) == 3: images = images[..., np.newaxis] layout = __layout_noaxis__() frames = [ go.Frame(data=go.Image(z=images[i]), name=str(i)) for i in range(len(images)) ] fig = go.Figure(data=go.Image(z=images[0]), frames=frames, layout=layout) updatemenus = [{ "buttons": [__play__(50), __pause__()], "direction": "left", "pad": { "r": 10, "t": 70 }, "type": "buttons", "x": 0.1, "y": 0 }] sliders = [{ "pad": { "b": 10, "t": 60 }, "len": 0.9, "x": 0.1, "y": 0, "steps": [{ "args": [[f.name], __frame_args__(0)], "label": str(k), "method": "animate" } for k, f in enumerate(fig.frames)] }] fig.update_layout(updatemenus=updatemenus, sliders=sliders) if show: fig.show() return fig
def plotly_images(file_path): files = os.listdir(file_path) numbers = np.random.randint(1, len(files), 5) fig = make_subplots(1, 5) steps = [] for step in np.arange(1, 6, 1): img = io.imread(file_path + files[numbers[step - 1]]) img = img[:, :, :3] fig.add_trace(go.Image(z=img), 1, step) fig.data[step - 1].visible = False fig.data[0].visible = True for i in range(len(fig.data)): step = dict(method="update", args=[{ "visible": [False] * len(fig.data) }]) step["args"][0]["visible"][i] = True steps.append(step) sliders = [dict(active=0, pad={"t": 5}, steps=steps)] fig.update_layout(width=500, height=250, sliders=sliders, template='plotly_dark', title_text="Image Examples", title_font=dict(size=12)) fig.update_xaxes(showticklabels=False)\ .update_yaxes(showticklabels=False) return fig #fig.show()
def get_plotly(net, env, s, title=None): s_img = env.render(mode='rgb_array') action_softmax, node_softmaxes, value = net([s], complete=True) action_probs = action_softmax.probs[0].cpu() # node_probs = node_softmaxes[0].reshape(*config.soko_size, 5).flip(0).cpu() # flip is because Heatmap flips the display :-( value = value[0].item() node_indices = s[4] node_probs = np.zeros((*config.soko_size, 5)) node_probs[tuple(node_indices.T)] = node_softmaxes[0].cpu() node_probs = np.flip(node_probs, 0) fig = make_subplots(rows=2, cols=4, subplot_titles=["State", "MOVE_TO", "PUSH_UP", "State value", "Action probs", "PUSH_LEFT", "PUSH_DOWN", "PUSH_RIGHT"]) fig.add_trace(go.Image(z=s_img), 1, 1) fig.add_trace(go.Bar(x=["MOVE_TO", "PUSH_UP", "PUSH_DOWN", "PUSH_LEFT", "PUSH_RIGHT"], y=action_probs), 2, 1) fig.add_trace(go.Bar(x=["value"], y=[value], text=[f'{value:.2f}'], textposition='auto', width=[0.2]), 1, 4) fig.update_yaxes(range=config.q_range, row=1, col=4) fig.add_trace(go.Heatmap(z=node_probs[:, :, 0], zmin=0., zmax=1., colorscale='Greys', showscale=False), 1, 2) # MOVE_TO fig.add_trace(go.Heatmap(z=node_probs[:, :, 1], zmin=0., zmax=1., colorscale='Greys', showscale=False), 1, 3) # PUSH_UP fig.add_trace(go.Heatmap(z=node_probs[:, :, 2], zmin=0., zmax=1., colorscale='Greys', showscale=False), 2, 3) # PUSH_DOWN fig.add_trace(go.Heatmap(z=node_probs[:, :, 3], zmin=0., zmax=1., colorscale='Greys', showscale=False), 2, 2) # PUSH_LEFT fig.add_trace(go.Heatmap(z=node_probs[:, :, 4], zmin=0., zmax=1., colorscale='Greys', showscale=True), 2, 4) # PUSH_RIGHT fig.update_layout(showlegend=False, title=title, title_x=0.5) return fig, value, action_probs
def scroll_images(images, show=True): if len(images.shape) == 4: pass elif len(images.shape) == 3: images = images[..., np.newaxis] #build each trace data = [go.Image(z=image, visible=False) for image in images] data[0]['visible'] = True steps = [ dict(method='update', args=[{ 'visible': [t == i for t in range(len(data))] }]) for i in range(len(images)) ] fig = go.Figure(data=data, layout=__layout_noaxis__()) fig = go.FigureWidget(fig) fig.layout.sliders = [ dict(active=0, currentvalue={"prefix": "image : "}, pad={"t": 20}, steps=steps) ] if show: fig.show() return fig
def overlap(self, images, **kwargs): """ Plot several images on one canvas using plotly: render the first one in greyscale and the rest ones in opaque 'rgb' channels, one channel for each image. Supports up to four images in total. Parameters ---------- images : list/tuple sequence of 2d-arrays for plotting. Can store up to four images. kwargs : dict max_size : int maximum size of a rendered image. title : str title of rendered image. opacity : float opacity of 'rgb' channels. xaxis : dict controls the properties of xaxis-labels; uses plotly-format. yaxis : dict controls the properties of yaxis-labels; uses plotly-format. slice : tuple sequence of slice-objects for slicing the image to a lesser one. order_axes : tuple tuple of ints; defines the order of axes for transposition operation applied to the image. other """ # update defaults to make total dict of kwargs defaults = {'coloraxis_colorbar': {'title': 'amplitude'}, 'opacity' : 1.0, 'title': 'Seismic inline', 'max_size' : 600, 'order_axes': (1, 0), 'slice': (slice(None, None), slice(None, None))} updated = {**defaults, **kwargs} # form different groups of kwargs render_kwargs = filter_kwargs(updated, ['zmin', 'zmax']) label_kwargs = filter_kwargs(updated, ['xaxis', 'yaxis', 'coloraxis_colorbar', 'title']) slc = updated['slice'] # calculate canvas sizes width, height = images[0].shape[1], images[0].shape[0] coeff = updated['max_size'] / max(width, height) width = coeff * width height = coeff * height # manually combine first image in greyscale and the rest ones colored differently combined = channelize_image(255 * np.transpose(images[0], axes=updated['order_axes']), total_channels=4, greyscale=True) for img, n_channel in zip(images[1:], (0, 1, 2)): combined += channelize_image(255 * np.transpose(img, axes=updated['order_axes']), total_channels=4, n_channel=n_channel, opacity=updated['opacity']) plot_data = go.Image(z=combined[slc], **render_kwargs) # plot manually combined image # plot the figure fig = go.Figure(data=plot_data) fig.update_layout(width=width, height=height, **label_kwargs) self.save_and_show(fig, **updated)
def format_results(img, preds): colors = { "Healthy": px.colors.qualitative.Plotly[0], "Scab": px.colors.qualitative.Plotly[0], "Rust": px.colors.qualitative.Plotly[0], "Multiple diseases": px.colors.qualitative.Plotly[0] } print(colors) if list.index(preds.tolist(), max(preds)) == 0: pred = "Healthy" if list.index(preds.tolist(), max(preds)) == 1: pred = "Multiple diseases" if list.index(preds.tolist(), max(preds)) == 2: pred = "Rust" if list.index(preds.tolist(), max(preds)) == 3: pred = "Scab" colors[pred] = px.colors.qualitative.Plotly[2] print(colors) colors = [colors[key] for key in colors.keys()] fig = make_subplots(rows=1, cols=2) fig.add_trace(go.Image(z=cv2.resize(img, (205, 150))), row=1, col=1) fig.add_trace(go.Bar(x=["Healthy", "Multiple diseases", "Rust", "Scab"], y=preds, marker=dict(color=colors)), row=1, col=2) fig.update_layout(height=400, width=800, title_text="DenseNet Model Predictions", showlegend=False) fig.update_layout(template="plotly_white") st.plotly_chart(fig)
def numpy_to_plotly_image(img, name=None, is_depth=False, scale=None, quality=95): r"""Converts a numpy array img to a `plotly.graph_objects.Image` object. Args img (np.ndarray): RGB image array name (str): Name for the returned `plotly.graph_objects.Image` object is_depth (bool): Bool indicating whether input `img` is depth image. Default: False scale (int or None): Scale factor to display on hover. If None, will not display `scale: ...`. Default: None quality (int): Image quality from 0 to 100 (the higher is the better). Default: 95 Returns: `plotly.graph_objects.Image` """ img_str = img_to_b64str(img, quality) hovertemplate = "x: %%{x}<br>y: %%{y}<br>%s: %s" if not is_depth: hover_name = "[%{z[0]}, %{z[1]}, %{z[2]}]" hovertemplate = hovertemplate % ("color", hover_name) else: hover_name = "%{z[0]}" hovertemplate = hovertemplate % ("depth", hover_name) if scale is not None: scale = int(scale) if int(scale) == scale else scale hovertemplate += f"<br>scale: x{scale}<br>" hovertemplate += "<extra></extra>" return go.Image(source=img_str, hovertemplate=hovertemplate, name=name)
def visualize(symbols, glyphs, title, get_fig=False, use_titles=True): """Visualize a square of samples and their symbol labels Args: symbols: a list of strings that correspond to each glyph glyphs: a tensor or list of glyphs. These should be normalized from 0 to 1 by a sigmoid activation function title: title of the plot get_fig: if true, return the Plotly figure object instead of visualizing immediately """ dim = len(glyphs)**(1 / 2) assert dim == int(dim), "Number of glyphs should be square" dim = int(dim) glyphs = np.array(glyphs * 255.).astype('uint8') # make visual fig = make_subplots(dim, dim, subplot_titles=symbols if use_titles else None, horizontal_spacing=0.01, vertical_spacing=0.01) row_num = 1 col_num = 1 for glyph in glyphs: if glyph.shape[2] == 1: glyph = tf.broadcast_to(glyph, (glyph.shape[0], glyph.shape[1], 3)) fig.add_trace(go.Image(z=glyph), row=row_num, col=col_num) if col_num == dim: row_num += 1 col_num = 1 else: col_num += 1 fig.update_layout(title_text=title) if get_fig: return fig else: fig.show()
def display_images(image_index, results): num_results = len(results) titles = [ 'Noisy Image', 'Denoised Image', 'Adversarial<br>Noisy Image', 'Denoised<br>Adversarial Image' ] + [''] * ((num_results - 1) * 4) fig = make_subplots(rows=num_results, cols=4, horizontal_spacing=0.005, vertical_spacing=0.005, subplot_titles=titles) annotation_interval_y = [0.95, 0.8, 0.65, 0.5, 0.35, 0.2, 0.05] annotation_interval_x = [ -0.065, -0.065, -0.11, -0.11, -0.11, -0.065, -0.065 ] for i, r in enumerate(results): noise_title, orig_np, noisy_np, denoised_np, adv_image_np, adv_denoised_np = r row = i + 1 plots = [noisy_np, denoised_np, adv_image_np, adv_denoised_np] for col, p in enumerate(plots): fig.add_trace(go.Image(z=p, colormodel='rgb', zmax=[1, 1, 1, 1], zmin=[0, 0, 0, 0]), row=row, col=col + 1) fig.update_xaxes(showgrid=False, showticklabels=False, zeroline=False, row=row, col=col + 1) fig.update_yaxes(showgrid=False, showticklabels=False, zeroline=False, row=row, col=col + 1) fig.add_annotation(x=annotation_interval_x[i], y=annotation_interval_y[i], text=noise_title, textangle=0) fig.update_annotations(xref='paper', yref='paper', showarrow=False) ## Create save directory name full_directory = 'images//final_adv_examples' # Create directory if required if not os.path.exists(full_directory): os.mkdir(full_directory) # Save figure filename = '{}//images_{}.html'.format(full_directory, image_index) plt_offline.plot(fig, filename=filename, auto_open=False)
def update_image(alpha): fig = make_subplots(1, 3) fig.add_trace(go.Image(z=image), 1, 1) iso_smooth = np.zeros_like(image) for i in range(3): iso_smooth[:, :, i] = apply_isotropic_smoothing(image[:, :, i], alpha=alpha) fig.add_trace(go.Image(z=iso_smooth), 1, 2) aniso_smooth = dtensor.smooth(image, alpha=alpha) fig.add_trace(go.Image(z=aniso_smooth), 1, 3) fig.update_layout(transition_duration=500) return fig
def separate(cls, images, **kwargs): """ Plot several images on a row of canvases using plotly. TODO: add grid support. Parameters ---------- images : list/tuple sequence of 2d-arrays for plotting. kwargs : dict max_size : int maximum size of a rendered image. title : str title of rendered image. xaxis : dict controls the properties of xaxis-labels; uses plotly-format. yaxis : dict controls the properties of yaxis-labels; uses plotly-format. slice : tuple sequence of slice-objects for slicing the image to a lesser one. order_axes : tuple tuple of ints; defines the order of axes for transposition operation applied to the image. other """ kwargs = cls.convert_kwargs('separate', kwargs) # defaults defaults = { 'max_size': 600, 'order_axes': (1, 0), 'slice': (slice(None, None), slice(None, None)) } grid = (1, len(images)) updated = {**defaults, **kwargs} # form different groups of kwargs render_kwargs = filter_kwargs(updated, []) label_kwargs = filter_kwargs(updated, ['title']) xaxis_kwargs = filter_kwargs(updated, ['xaxis']) yaxis_kwargs = filter_kwargs(updated, ['yaxis']) slc = updated['slice'] # make sure that the images are greyscale and put them each on separate canvas fig = make_subplots(rows=grid[0], cols=grid[1]) for i in range(grid[1]): img = channelize_image( 255 * np.transpose(images[i], axes=updated['order_axes']), total_channels=4, greyscale=True, opacity=1) fig.add_trace(go.Image(z=img[slc], **render_kwargs), row=1, col=i + 1) fig.update_xaxes(row=1, col=i + 1, **xaxis_kwargs['xaxis']) fig.update_yaxes(row=1, col=i + 1, **yaxis_kwargs['yaxis']) fig.update_layout(**label_kwargs) cls.save_and_show(fig, **updated)
def plot_heatmap(self): fig = go.Figure() fig.add_trace(go.Image(z=self.image)) fig.add_trace( go.Heatmap(z=self.heatmap, type='heatmap', colorscale='jet', opacity=0.7)) return fig
def rgb(cls, image, **kwargs): """ Plot one image in 'rgb' using plotly. Parameters ---------- image : np.ndarray 3d-array containing channeled rgb-image. kwargs : dict max_size : int maximum size of a rendered image. title : str title of the rendered image. xaxis : dict controls the properties of xaxis-labels; uses plotly-format. yaxis : dict controls the properties of yaxis-labels; uses plotly-format. slice : tuple sequence of slice-objects for slicing the image to a lesser one. order_axes : tuple tuple of ints; defines the order of axes for transposition operation applied to the image. other """ kwargs = cls.convert_kwargs('rgb', kwargs) # update defaults to make total dict of kwargs defaults = { 'coloraxis_colorbar': { 'title': 'depth' }, 'max_size': 600, 'order_axes': (1, 0, 2), 'slice': (slice(None, None), slice(None, None)) } updated = {**defaults, **kwargs} # form different groups of kwargs render_kwargs = filter_kwargs(updated, []) label_kwargs = filter_kwargs( updated, ['xaxis', 'yaxis', 'coloraxis_colorbar', 'title']) slc = updated['slice'] # calculate canvas sizes width, height = image.shape[1], image.shape[0] coeff = updated['max_size'] / max(width, height) width = coeff * width height = coeff * height # plot the image and set titles plot_data = go.Image(z=np.transpose(image, axes=updated['order_axes'])[slc], **render_kwargs) fig = go.Figure(data=plot_data) fig.update_layout(width=width, height=height, **label_kwargs) cls.save_and_show(fig, **updated)
def smooth_user_image(contents, alpha): image = load_image(contents) user_dtensor = DiffusionTensor2D.fromimage(image) fig = make_subplots(1, 3) fig.add_trace(go.Image(z=image), 1, 1) iso_smooth = np.zeros_like(image) for i in range(3): iso_smooth[:, :, i] = apply_isotropic_smoothing(image[:, :, i], alpha=alpha) fig.add_trace(go.Image(z=iso_smooth), 1, 2) aniso_smooth = user_dtensor.smooth(image, alpha=alpha) fig.add_trace(go.Image(z=aniso_smooth), 1, 3) fig.update_layout(transition_duration=500) return fig
def draw_image(self, **props): """Write base64 encoded images into plotly figure""" imdata = props['imdata'] base64_decoded = base64.b64decode(imdata) image = Image.open(io.BytesIO(base64_decoded)) image_np = np.array(image) self.plotly_fig.add_trace( go.Image( z=image_np, xaxis='x{0}'.format(self.axis_ct), yaxis='y{0}'.format(self.axis_ct), ), )
def add_bbox_frame(fig, image_str, bbox): fig.add_trace(go.Image(source=image_str), row=1, col=1) fig.update_xaxes(range=[0, 100], constrain='domain', scaleanchor='y', scaleratio=1, row=1, col=1) fig.update_yaxes(range=[100, 0], constrain='domain', scaleanchor='x', scaleratio=1, row=1, col=1)
def draw_figure(base64_img_string, summary_data, ann_type, visual_type): data_descript = get_data_descript(ann_type, visual_type) fig = go.Figure(go.Image(source=base64_img_string)) fig.update_traces(hoverinfo="skip", hovertemplate=None) for ann in summary_data: hover = '' if visual_type == 'SEGM': x_list = ann['mask_contour'][0] y_list = ann['mask_contour'][1] elif visual_type == 'BBOX': x_list = ann['bbox'][0] y_list = ann['bbox'][1] else: x_list = None y_list = None for dx in data_descript: hover = hover + f'<b>{data_descript[dx]["name"]}:</b> {ann[dx]}<br>' fig.add_trace( go.Scatter( x=x_list, y=y_list, fill='toself', mode='lines', fillcolor=DATA_CFG[ann['classe']]['color_tr'], line_color=DATA_CFG[ann['classe']]['color'], text=hover, name='', hoveron='fills' ) ) config = dict({ 'paper_bgcolor': 'rgba(0,0,0,0)', 'plot_bgcolor': 'rgba(0,0,0,0)', 'showlegend': False }) fig.update_layout(height=300, margin=dict(l=10, r=10, b=10, t=10), template="simple_white") fig.update_xaxes(visible=False, range=[0, 256]).update_yaxes(visible=False, range=[256, 0]) fig.update_layout(config) return fig
def _apply_mask_contour(figure, image, mask, slider_opacity): colorscale = [[0, 'gold'], [0.5, 'gold'], [1, 'gold']] image = 255 * image figure.add_trace(go.Image(z=image)) figure.update_layout(margin={"r": 60, "t": 0, "l": 0, "b": 0}) figure.add_trace( go.Contour(z=mask, contours_coloring='lines', line_width=3, opacity=slider_opacity, showlegend=False, showscale=False, colorscale=colorscale, colorbar=dict(showticklabels=False))) return figure
def update_2d_plot_data_by_axis(img_state, slider_control, face_control, view_mode, axis): if view_mode is None or view_mode["view"] == "3d": raise PreventUpdate layout = go.Layout( autosize=True, plot_bgcolor="#1D1D1D", paper_bgcolor="#1D1D1D", margin=dict( l=0, r=0, t=0, b=0, pad=0, ), xaxis=dict( autorange=True, showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ), yaxis=dict( autorange=True, showgrid=False, zeroline=False, showline=False, ticks='', showticklabels=False ) ) if img_state is None or slider_control is None: res = { "data": [], 'layout': layout } else: stateIns = StateSingleton() state = stateIns.get_state() if axis == "i": z = cv2.cvtColor(np.expand_dims(state['data'][slider_control], axis=-1), cv2.COLOR_GRAY2RGB) if axis == "j": z = cv2.cvtColor(np.expand_dims(state['data'][:, slider_control], axis=-1), cv2.COLOR_GRAY2RGB) if axis == "k": z = cv2.cvtColor(np.expand_dims(state['data'][:, :, slider_control].T, axis=-1), cv2.COLOR_GRAY2RGB) res = go.Figure(data=go.Image(z=z), layout=layout) return res
def make_figure(filename_uri, mode="layout", dragmode="drawrect", show_axes=True): if mode == "layout": fig = go.Figure() # Add trace fig.add_trace(go.Scatter(x=[], y=[])) filename = os.path.join("assets", os.path.basename(filename_uri)) im = Image.open(filename) width, height = im.size # Add images fig.add_layout_image( dict( source=filename_uri, xref="x", yref="y", x=0, y=0, sizex=width, sizey=height, sizing="contain", layer="below", ) ) fig.update_layout(template=None) fig.update_xaxes( showgrid=False, range=(0, width), showticklabels=False, zeroline=False ) fig.update_yaxes( showgrid=False, scaleanchor="x", range=(height, 0), showticklabels=False, zeroline=False, ) else: im = io.imread(filename_uri[1:]) fig = go.Figure(go.Image(z=im)) fig.update_layout( margin=dict(t=0, b=0), dragmode=dragmode, ) if not show_axes: fig.update_xaxes(showgrid=False) fig.update_yaxes(showgrid=False) return fig
def dash_plot_wc(selected_df, label, d_dict, pos_dict, neg_dict): ''' Signature: plot_wc(selected_df=None, label=None, d_dict=None) Doctring: Return plotly figure Parameter: selected_df: string, dataframe variable name label: interger, 0 or 1 d_dict: dictionary pos_dict: dictionary neg_dict: dictionary ''' df = d_dict.get(selected_df) fig = go.Figure() if label == 0: wc_df = neg_dict.get(selected_df) # create WordCoud object wc = WordCloud(background_color="white") # generate word cloud wc.generate_from_frequencies(dict(wc_df)) title = 'Top 50 Words from Negative Reviews' else: wc_df = pos_dict.get(selected_df) # create WordCoud object wc = WordCloud(background_color="white") # generate word cloud wc.generate_from_frequencies(dict(wc_df)) title = 'Top 50 Words from Positive Reviews' fig.add_trace(go.Image(z=wc)) fig.update_layout(title={ 'text': title, 'x': 0.5, 'xanchor': 'center' }, width=495, height=350, hovermode=False, autosize=False, margin=dict(l=0, r=0, b=1, t=50, pad=4)) fig.update_xaxes(showticklabels=False) fig.update_yaxes(showticklabels=False) return fig
def show_wc(selected_df, label): df = df_dict.get(selected_df) fig = go.Figure() if label == 0: wc_df = neg_wc_dict.get(selected_df) # create WordCoud object wc = WordCloud(background_color="white") # generate word cloud wc.generate_from_frequencies(dict(wc_df)) title = '<b>Top 50 Words from Negative Reviews' else: wc_df = pos_wc_dict.get(selected_df) # create WordCoud object wc = WordCloud(background_color="white") # generate word cloud wc.generate_from_frequencies(dict(wc_df)) title = '<b>Top 50 Words from Positive Reviews</b>' fig.add_trace(go.Image(z=wc)) fig.update_layout(title={ 'text': title, 'x': 0.5, 'y': 0.85, 'xanchor': 'center' }, hovermode=False, autosize=True, margin=dict(l=5, r=5, b=0, t=0), font=dict(size=15, color='#c5a654')) fig.update_xaxes(showticklabels=False, showline=True, linewidth=1, linecolor='#88bccb', mirror=True) fig.update_yaxes(showticklabels=False, showline=True, linewidth=1, linecolor='#e4c02e', mirror=True) return fig
def plot_wcloud(lst, spt1, spt2, word_type): ''' Signature: plot_wcloud(lst=None, spt1=None, spt2=None, word_type) Docstring: Return a plotly express figure of word cloud image. Parameters: lst: list of tuple of word and count. spt1: string, subplot one title. spt2: string, subplot two title. word_type: string, subplots title word ''' # create figure with 2 subplot fig = make_subplots( rows=2, cols=1, vertical_spacing=0.1, subplot_titles=(f'<i><b>{spt1}</b></i> Review Top 50 {word_type}', f'<i><b>{spt2}</b></i> Review Top 50 {word_type}')) for i, j in enumerate(lst): # create WordCoud object wc = WordCloud(background_color="white") # generate word cloud wc.generate_from_frequencies(dict(j)) fig.add_trace(go.Image(z=wc), row=i + 1, col=1) # set subplot title font size for annotation in fig['layout']['annotations']: annotation['font'] = {'size': 24} fig.update_layout(width=550, height=700, hovermode=False, autosize=False) fig.update_xaxes(showticklabels=False, showline=True, linewidth=1, linecolor='grey', mirror=True) fig.update_yaxes(showticklabels=False, showline=True, linewidth=1, linecolor='grey', mirror=True) fig.show(scale=10)
def matrice(): dg = [21, 67, 96] lg = [41, 128, 185] w = [253, 254, 254] x = [ 'CYBERIA', 'WAVENET', 'OGERONET-TRIPOLI', 'IncoNet Data Management', 'OGERONET-Jounieh', 'USJ', 'BROADBAND PLUS', 'FARAHNET', 'AUBNET' ] data = [[w, lg, lg, lg, lg, lg, lg, dg, lg], [lg, w, lg, lg, lg, lg, lg, lg, lg], [w, lg, w, lg, lg, lg, lg, lg, lg], [lg, lg, lg, w, lg, lg, lg, dg, lg], [w, lg, lg, lg, w, lg, lg, lg, lg], [lg, lg, lg, lg, lg, w, lg, dg, lg], [lg, lg, lg, lg, lg, lg, w, lg, lg], [w, lg, lg, dg, lg, lg, dg, w, dg], [lg, lg, lg, lg, lg, lg, lg, dg, w]] fig = go.Figure(go.Image(z=data)) fig.show()
def update_figure(selected_num): filtered_df = df[df['Number'] == selected_num] traces = [] fig.add_trace(go.Image(z=img), 1, 1) for i in filtered_df['Location'].unique(): df_location = filtered_df[filtered_df['Location'] == i] traces.append( dict( x=df_location['Lat'], y=df_location['Lon'], text=df_location['Location'], mode='markers', marker={ 'size': df_location['Result'] * 5, 'color': df_location['Color'] }, name=i, )), return {'data': traces, 'layout': layout}
def image_montage(image_dir, details, summary): patients = list(details.Patient.unique()) max_image_counts = int( details.groupby('Patient').agg('nunique')['fn'].max()) number_of_patients = len(patients) montage = make_subplots(number_of_patients, max_image_counts, vertical_spacing=0.05) summary = summary.set_index('Patient') for p_i, patient in enumerate(patients): patient_filter = (details.Patient == patient) patient_df = details.loc[patient_filter, ['fn', 'Predicted_label']] infection_rate = summary.loc[patient, '% Infected Cells'] montage.add_annotation( text=f"Patient {patient}: {infection_rate} % infected", xref="paper", yref="paper", x=0, # include verticle spacing y=1.05 - p_i * (1 / number_of_patients + 0.05), showarrow=False) for i_i, row in patient_df.reset_index().iterrows(): im_p = row['fn'] pred = row['Predicted_label'] img_i = Image.open(image_dir + im_p.split('/')[-1]).copy() img_i = img_i.convert('RGB') img_i = resize_image(img_i, 50) img_i = pad_image(img_i, 55, pred) img_i = np.array(img_i) montage.add_trace(go.Image(z=img_i), p_i + 1, i_i + 1) # hide subplot y-axis titles and x-axis titles for axis in montage.layout: if isinstance(montage.layout[axis], go.layout.YAxis): montage.layout[axis].tickfont = dict(color='rgba(0,0,0,0)') if isinstance(montage.layout[axis], go.layout.XAxis): montage.layout[axis].tickfont = dict(color='rgba(0,0,0,0)') return montage
def plot_image(images, show=True): if len(images.shape) == 4: pass elif len(images.shape) == 3: images = images[np.newaxis, ...] elif len(images.shape) == 2: images = images[np.newaxis, :, :, np.newaxis] g = int(np.ceil(np.sqrt(images.shape[0]))) fig = subplots.make_subplots(rows=g, cols=g, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.004, horizontal_spacing=0.004) fig.update_xaxes(**__layout_noaxis__()['xaxis']) fig.update_yaxes(**__layout_noaxis__()['yaxis']) for i, image in enumerate(images, 0): fig.add_trace(go.Image(z=image), (i % g) + 1, (i // g) + 1) if show: fig.show()
def render_figure(active_img_idx, patch, editable=True): active_img = loaded_data[active_img_idx].copy() img_width, img_height = active_img.size fig = go.Figure(go.Image(z=np.array(active_img))) fig.add_shape( editable=editable, xref="x", yref="y", layer="above", line={"color": "cyan"}, opacity=0.7, fillcolor="cyan", type="rect", **patch, ) fig.update_xaxes(showgrid=False, range=(0, img_width)) fig.update_yaxes(showgrid=False, scaleanchor="x", range=(img_height, 0)) fig.update_layout(autosize=False, width=800, height=800) return fig
def plotly_image_slider(images, ticks, slider_prefix="Distance < "): """ Plots all images with a slider named after ticks. """ fig = go.Figure() for img in images: fig.add_trace( go.Image(z=img, visible=False) ) fig.data[0].visible = True steps = [] for i, t in enumerate(ticks): step = dict( method="restyle", args=["visible", [False] * len(fig.data)], label=t ) step["args"][1][i] = True steps.append(step) sliders = [dict( active=0, currentvalue={"prefix": slider_prefix}, pad={"t": 50}, steps=steps )] fig.update_layout( template="none", sliders=sliders, ) return fig
import numpy as np import img_transform import plot_common import skimage.io import skimage.transform import plotly.graph_objects as go x = plot_common.path_to_img_ndarray('assets/Keymaker.jpg') #x=x[:10,:10,:] xrot = skimage.transform.rotate(x, 90) print('x', x.shape) print('xrot', xrot.shape) print(np.sum(xrot != 0)) print(xrot.max()) print(xrot.min()) #fig=go.Figure(data=go.Image(z=xrot)) #x=np.transpose(x,(1,0,2)) img_trace = go.Image(z=xrot, zmax=[1, 1, 1, 1]) fig = go.Figure(data=img_trace) fig.show()