Python IPython.display.Image() Examples
The following are 30
code examples of IPython.display.Image().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
IPython.display
, or try the search function
.
Example #1
Source File: viewer.py From pivy with ISC License | 7 votes |
def show(self, exec_widget=True): super(Viewer, self).show() self.viewAll() rec = self.app.desktop().screenGeometry() self.move(rec.width() - self.size().width(), rec.height() - self.size().height()) if not exec_widget: timer = QtCore.QTimer() # timer.timeout.connect(self.close) timer.singleShot(20, self.close) self.app.exec_() try: from IPython.display import Image return Image(self.name) except ImportError as e: print(e)
Example #2
Source File: visualize.py From zipline-chinese with Apache License 2.0 | 6 votes |
def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed. Can't display graph.") if format == 'svg': display_cls = display.SVG elif format in ("jpeg", "png"): display_cls = partial(display.Image, format=format, embed=True) out = BytesIO() _render(g, out, format, include_asset_exists=include_asset_exists) return display_cls(data=out.getvalue())
Example #3
Source File: visualize.py From catalyst with Apache License 2.0 | 6 votes |
def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed. Can't display graph.") if format == 'svg': display_cls = display.SVG elif format in ("jpeg", "png"): display_cls = partial(display.Image, format=format, embed=True) out = BytesIO() _render(g, out, format, include_asset_exists=include_asset_exists) return display_cls(data=out.getvalue())
Example #4
Source File: macro.py From magics-python with Apache License 2.0 | 6 votes |
def _jplot(*args): from IPython.display import Image with _MAGICS_LOCK: f, tmp = tempfile.mkstemp(".png") os.close(f) base, ext = os.path.splitext(tmp) img = output( output_formats=["png"], output_name_first_page_number="off", output_name=base, ) all = [img] all.extend(args) _plot(all) image = Image(tmp) os.unlink(tmp) return image
Example #5
Source File: visualization.py From TINT with BSD 2-Clause "Simplified" License | 6 votes |
def embed_mp4_as_gif(filename): """ Makes a temporary gif version of an mp4 using ffmpeg for embedding in IPython. Intended for use in Jupyter notebooks. """ if not os.path.exists(filename): print('file does not exist.') return dirname = os.path.dirname(filename) basename = os.path.basename(filename) newfile = tempfile.NamedTemporaryFile() newname = newfile.name + '.gif' if len(dirname) != 0: os.chdir(dirname) os.system('ffmpeg -i ' + basename + ' ' + newname) try: with open(newname, 'rb') as f: display(Image(f.read(), format='png')) finally: os.remove(newname)
Example #6
Source File: sbmldiagram.py From tellurium with Apache License 2.0 | 6 votes |
def draw(self, layout='neato', **kwargs): """ Draw the graph. Optional layout=['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop'] will use specified graphviz layout method. :param layout: pygraphviz layout algorithm (default: 'neato') :type layout: str """ f, filePath = tempfile.mkstemp(suffix='.png') self.g.layout(prog=layout) self.g.draw(filePath) i = Image(filename=filePath) display(i) os.close(f) os.remove(filePath)
Example #7
Source File: FastNeuralTransfer.py From Deep-learning-with-cats with GNU General Public License v3.0 | 5 votes |
def forward(self, input): # Return itself + the result of the two convolutions output = self.model(input) + input return output # Image transformation network
Example #8
Source File: functions.py From quantipy with MIT License | 5 votes |
def parrot(): from IPython.display import Image from IPython.display import display import os filename = os.path.dirname(__file__) + '\\parrot.gif' try: return display(Image(filename=filename, format='png')) except: print ':sad_parrot: Looks like the parrot is not available!'
Example #9
Source File: LocationTracking_Functions.py From ezTrack with GNU General Public License v3.0 | 5 votes |
def display_image(frame,fps,resize): img = PIL.Image.fromarray(frame, "L") img = img.resize(size=resize) if resize else img buffer = BytesIO() img.save(buffer,format="JPEG") display(Image(data=buffer.getvalue())) time.sleep(1/fps) clear_output(wait=True) ########################################################################################
Example #10
Source File: FreezeAnalysis_Functions.py From ezTrack with GNU General Public License v3.0 | 5 votes |
def display_image(frame,fps,resize): img = PIL.Image.fromarray(frame, "L") img = img.resize(size=resize) if resize else img buffer = BytesIO() img.save(buffer,format="JPEG") display(Image(data=buffer.getvalue())) time.sleep(1/fps) clear_output(wait=True) ########################################################################################
Example #11
Source File: utils.py From open-solution-data-science-bowl-2018 with MIT License | 5 votes |
def view_pydot(pydot_object): plt = Image(pydot_object.create_png()) display(plt)
Example #12
Source File: load_redten_ipython_env.py From sci-pype with Apache License 2.0 | 5 votes |
def get_job_analysis(job_id, show_plots=True, debug=False): job_report = {} if job_id == None: boom("Failed to start a new job") else: job_res = helper_get_job_analysis(job_id) if job_res["status"] != "SUCCESS": boom("Job=" + str(job_id) + " failed with status=" + str(job_res["status"]) + " err=" + str(job_res["error"])) else: job_report = job_res["record"] # end of get job analysis if show_plots: if "images" in job_report: for img in job_report["images"]: anmt(img["title"]) lg("URL: " + str(img["image"])) ipyDisplay(ipyImage(url=img["image"])) lg("---------------------------------------------------------------------------------------") else: boom("Job=" + str(job_id) + " does not have any images yet") # end of if images exist # end of downloading job plots return job_report # end of get_job_analysis
Example #13
Source File: utils.py From open-solution-toxic-comments with MIT License | 5 votes |
def view_pydot(pydot_object): plt = Image(pydot_object.create_png()) display(plt)
Example #14
Source File: show_image.py From sketch-to-react-native with MIT License | 5 votes |
def show_image(image_path): display(Image(image_path)) image_rel = image_path.replace(root,'') caption = "Image " + ' - '.join(attributions[image_rel].split(' - ')[:-1]) display(HTML("<div>%s</div>" % caption))
Example #15
Source File: _base.py From sumpy with Apache License 2.0 | 5 votes |
def print_dependency_graph(self, filename=None, to_iPython=True): import pygraphviz as pgv if not hasattr(self, "_dependency_graph") or \ self._dependency_graph is None: self.build_dependency_graph() if filename is None: filename = "sumpy.tmp.png" G = pgv.AGraph(strict=False, directed=True) for node in self._dependency_graph: if node in self._annotators: G.add_node(node) G.get_node(node).attr["shape"] ="rectangle" elif node.startswith("f:"): G.add_node(node) G.get_node(node).attr["shape"] ="parallelogram" for edge in self._dependency_graph.in_edges(node): G.add_edge(edge[0], edge[1], color="green") else: for in_edge in self._dependency_graph.in_edges(node): for out_edge in self._dependency_graph.out_edges(node): G.add_edge(in_edge[0], out_edge[1], label=node, key=node) G.layout("dot") G.draw(filename) if to_iPython is True: from IPython.display import Image return Image(filename=filename)
Example #16
Source File: show_image.py From pokemon-mini with Apache License 2.0 | 5 votes |
def show_image(image_path): display(Image(image_path)) image_rel = image_path.replace(root,'') caption = "Image " + ' - '.join(attributions[image_rel].split(' - ')[:-1]) display(HTML("<div>%s</div>" % caption))
Example #17
Source File: utils.py From open-solution-mapping-challenge with MIT License | 5 votes |
def view_pydot(pydot_object): plt = Image(pydot_object.create_png()) display(plt)
Example #18
Source File: utils.py From deep-learning-from-scratch-3 with MIT License | 5 votes |
def plot_dot_graph(output, verbose=True, to_file='graph.png'): dot_graph = get_dot_graph(output, verbose) tmp_dir = os.path.join(os.path.expanduser('~'), '.dezero') if not os.path.exists(tmp_dir): os.mkdir(tmp_dir) graph_path = os.path.join(tmp_dir, 'tmp_graph.dot') with open(graph_path, 'w') as f: f.write(dot_graph) extension = os.path.splitext(to_file)[1][1:] # Extension(e.g. png, pdf) cmd = 'dot {} -T {} -o {}'.format(graph_path, extension, to_file) subprocess.run(cmd, shell=True) # Return the image as a Jupyter Image object, to be displayed in-line. try: from IPython import display return display.Image(filename=to_file) except: pass # ============================================================================= # Utility functions for numpy (numpy magic) # =============================================================================
Example #19
Source File: plotly.py From lddmm-ot with MIT License | 5 votes |
def ishow(cls, figure_or_data, format='png', width=None, height=None, scale=None): """Display a static image of the plot described by `figure_or_data` in an IPython Notebook. positional arguments: - figure_or_data: The figure dict-like or data list-like object that describes a plotly figure. Same argument used in `py.plot`, `py.iplot`, see https://plot.ly/python for examples - format: 'png', 'svg', 'jpeg', 'pdf' - width: output width - height: output height - scale: Increase the resolution of the image by `scale` amount Only valid for PNG and JPEG images. example: ``` import plotly.plotly as py fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]} py.image.ishow(fig, 'png', scale=3) """ if format == 'pdf': raise exceptions.PlotlyError( "Aw, snap! " "It's not currently possible to embed a pdf into " "an IPython notebook. You can save the pdf " "with the `image.save_as` or you can " "embed an png, jpeg, or svg.") img = cls.get(figure_or_data, format, width, height, scale) from IPython.display import display, Image, SVG if format == 'svg': display(SVG(img)) else: display(Image(img))
Example #20
Source File: Plots.py From pyaf with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_hierarchy(structure , iAnnotations, name): import pydot graph = pydot.Dot(graph_type='graph', rankdir='LR', fontsize="12.0"); graph.set_node_defaults(shape='record') lLevelsReversed = sorted(structure.keys(), reverse=True); for level in lLevelsReversed: color = '#%02x%02x%02x' % (255, 255, 127 + int(128 * (1.0 - (level + 1.0) / len(lLevelsReversed)))); for col in structure[level].keys(): lLabel = col if iAnnotations is None else str(iAnnotations[col]); if iAnnotations is not None: lLabel = build_record_label(iAnnotations[col]); node_col = pydot.Node(col, label=lLabel, style="filled", fillcolor=color, fontsize="12.0") graph.add_node(node_col); for col1 in structure[level][col]: lLabel1 = col1 if iAnnotations is not None: lLabel1 = build_record_label(iAnnotations[col1]); color1 = '#%02x%02x%02x' % (255, 255, 128 + int(128 * (1.0 - (level + 2.0) / len(lLevelsReversed)))); node_col1 = pydot.Node(col1, label=lLabel1, style="filled", fillcolor=color1, fontsize="12.0") graph.add_node(node_col1); lEdgeLabel = ""; if iAnnotations is not None: lEdgeLabel = iAnnotations[col + "_" + col1]; lEdge = pydot.Edge(node_col, node_col1, color="red", label=lEdgeLabel, fontsize="12.0") graph.add_edge(lEdge) # print(graph.obj_dict) if(name is not None): graph.write_png(name); else: from IPython.display import Image, display plot1 = Image(graph.create_png()) display(plot1)
Example #21
Source File: show_image.py From AudioNet with MIT License | 5 votes |
def show_image(image_path): display(Image(image_path)) image_rel = image_path.replace(root,'') caption = "Image " + ' - '.join(attributions[image_rel].split(' - ')[:-1]) display(HTML("<div>%s</div>" % caption))
Example #22
Source File: dot.py From xarray-simlab with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_display_cls(format): """ Get the appropriate IPython display class for `format`. Returns `IPython.display.SVG` if format=='svg', otherwise `IPython.display.Image`. If IPython is not importable, return dummy function that swallows its arguments and returns None. """ dummy = lambda *args, **kwargs: None try: import IPython.display as display except ImportError: # Can't return a display object if no IPython. return dummy if format in IPYTHON_NO_DISPLAY_FORMATS: # IPython can't display this format natively, so just return None. return dummy elif format in IPYTHON_IMAGE_FORMATS: # Partially apply `format` so that `Image` and `SVG` supply a uniform # interface to the caller. return partial(display.Image, format=format) elif format == "svg": return display.SVG else: raise ValueError(f"Unknown format '{format}' passed to `dot_graph`")
Example #23
Source File: test_dot.py From xarray-simlab with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_filenames_and_formats(model): # Test with a variety of user provided args filenames = [ "modelpdf", "model.pdf", "model.pdf", "modelpdf", "model.pdf.svg", ] formats = ["svg", None, "svg", None, None] targets = [ "modelpdf.svg", "model.pdf", "model.pdf.svg", "modelpdf.png", "model.pdf.svg", ] result_types = { "png": Image, "pdf": type(None), "svg": SVG, } for filename, format, target in zip(filenames, formats, targets): expected_result_type = result_types[target.split(".")[-1]] result = dot_graph(model, filename=filename, format=format) assert os.path.isfile(target) assert isinstance(result, expected_result_type) _ensure_not_exists(target)
Example #24
Source File: utils.py From steppy with MIT License | 5 votes |
def display_upstream_structure(structure_dict): """Displays pipeline structure in the jupyter notebook. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure`. """ graph = _create_graph(structure_dict) plt = Image(graph.create_png()) display(plt)
Example #25
Source File: util.py From poseGuidedImgGeneration with MIT License | 5 votes |
def showBGRimage(a, fmt='jpeg'): a = np.uint8(np.clip(a, 0, 255)) a[:,:,[0,2]] = a[:,:,[2,0]] # for B,G,R order f = StringIO() PIL.Image.fromarray(a).save(f, fmt) display(Image(data=f.getvalue()))
Example #26
Source File: util.py From poseGuidedImgGeneration with MIT License | 5 votes |
def showmap(a, fmt='png'): a = np.uint8(np.clip(a, 0, 255)) f = StringIO() PIL.Image.fromarray(a).save(f, fmt) display(Image(data=f.getvalue())) #def checkparam(param): # octave = param['octave'] # starting_range = param['starting_range'] # ending_range = param['ending_range'] # assert starting_range <= ending_range, 'starting ratio should <= ending ratio' # assert octave >= 1, 'octave should >= 1' # return starting_range, ending_range, octave
Example #27
Source File: profiles.py From pyEX with Apache License 2.0 | 5 votes |
def logoNotebook(symbol, token='', version='', filter=''): '''This is a helper function, but the google APIs url is standardized. https://iexcloud.io/docs/api/#logo 8am UTC daily Args: symbol (string); Ticker to request token (string); Access token version (string); API version filter (string); filters: https://iexcloud.io/docs/api/#filter-results Returns: image: result ''' _raiseIfNotStr(symbol) url = logo(symbol, token, version, filter)['url'] return ImageI(url=url)
Example #28
Source File: tutorial.py From feets with MIT License | 5 votes |
def macho_example11(): picture = Image(filename='_static/curvas_ejemplos11.jpg') picture.size = (100, 100) return picture # the library
Example #29
Source File: MNIST.py From tutorials with Apache License 2.0 | 5 votes |
def AddMLPModel(model, data): size = 28 * 28 * 1 sizes = [size, size * 2, size * 2, 10] layer = data for i in range(len(sizes) - 1): layer = brew.fc(model, layer, 'dense_{}'.format(i), dim_in=sizes[i], dim_out=sizes[i + 1]) layer = brew.relu(model, layer, 'relu_{}'.format(i)) softmax = brew.softmax(model, layer, 'softmax') return softmax # ### LeNet Model Definition # # **Note**: This is the model used when the flag *USE_LENET_MODEL=True* # # Below is another possible (and very powerful) architecture called LeNet. The primary difference from the MLP model is that LeNet is a Convolutional Neural Network (CNN), and therefore uses convolutional layers ([Conv](https://caffe2.ai/docs/operators-catalogue.html#conv)), max pooling layers ([MaxPool](https://caffe2.ai/docs/operators-catalogue.html#maxpool)), [ReLUs](https://caffe2.ai/docs/operators-catalogue.html#relu), *and* fully-connected ([FC](https://caffe2.ai/docs/operators-catalogue.html#fc)) layers. A full explanation of how a CNN works is beyond the scope of this tutorial but here are a few good resources for the curious reader: # # - [Stanford cs231 CNNs for Visual Recognition](http://cs231n.github.io/convolutional-networks/) (**Recommended**) # - [Explanation of Kernels in Image Processing](https://en.wikipedia.org/wiki/Kernel_%28image_processing%29) # - [Convolutional Arithmetic Tutorial](http://deeplearning.net/software/theano_versions/dev/tutorial/conv_arithmetic.html) # # Notice, this function also uses Brew. However, this time we add more than just FC and Softmax layers. # In[5]:
Example #30
Source File: MNIST.py From tutorials with Apache License 2.0 | 5 votes |
def AddLeNetModel(model, data): ''' This part is the standard LeNet model: from data to the softmax prediction. For each convolutional layer we specify dim_in - number of input channels and dim_out - number or output channels. Also each Conv and MaxPool layer changes the image size. For example, kernel of size 5 reduces each side of an image by 4. While when we have kernel and stride sizes equal 2 in a MaxPool layer, it divides each side in half. ''' # Image size: 28 x 28 -> 24 x 24 conv1 = brew.conv(model, data, 'conv1', dim_in=1, dim_out=20, kernel=5) # Image size: 24 x 24 -> 12 x 12 pool1 = brew.max_pool(model, conv1, 'pool1', kernel=2, stride=2) # Image size: 12 x 12 -> 8 x 8 conv2 = brew.conv(model, pool1, 'conv2', dim_in=20, dim_out=50, kernel=5) # Image size: 8 x 8 -> 4 x 4 pool2 = brew.max_pool(model, conv2, 'pool2', kernel=2, stride=2) # 50 * 4 * 4 stands for dim_out from previous layer multiplied by the image size # Here, the data is flattened from a tensor of dimension 50x4x4 to a vector of length 50*4*4 fc3 = brew.fc(model, pool2, 'fc3', dim_in=50 * 4 * 4, dim_out=500) relu3 = brew.relu(model, fc3, 'relu3') # Last FC Layer pred = brew.fc(model, relu3, 'pred', dim_in=500, dim_out=10) # Softmax Layer softmax = brew.softmax(model, pred, 'softmax') return softmax # The `AddModel` function below allows us to easily switch from MLP to LeNet model. Just change `USE_LENET_MODEL` at the very top of the notebook and rerun the whole thing. # In[6]: