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: 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 #3
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 #4
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 #5
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 #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: 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 #9
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 #10
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]:
Example #11
Source File: jupyter.py From GraphvizAnim with GNU General Public License v3.0 | 5 votes |
def interactive( animation, size = 320 ): basedir = mkdtemp() basename = join( basedir, 'graph' ) steps = [ Image( path ) for path in render( animation.graphs(), basename, 'png', size ) ] rmtree( basedir ) slider = widgets.IntSlider( min = 0, max = len( steps ) - 1, step = 1, value = 0 ) return widgets.interactive( lambda n: display(steps[ n ]), n = slider )
Example #12
Source File: utils.py From gap 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 #13
Source File: 2_dreaming_time.py From DeepDreamVideo with GNU General Public License v2.0 | 5 votes |
def showarray(a, fmt='jpeg'): a = np.uint8(np.clip(a, 0, 255)) f = StringIO() PIL.Image.fromarray(a).save(f, fmt) display(Image(data=f.getvalue()))
Example #14
Source File: 2_dreaming_time.py From DeepDreamVideo with GNU General Public License v2.0 | 5 votes |
def showarrayHQ(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())) # a couple of utility functions for converting to and from Caffe's input image layout
Example #15
Source File: 2_dreaming_time.py From DeepDreamVideo with GNU General Public License v2.0 | 5 votes |
def prepare_guide(net, image, end="inception_4c/output", maxW=224, maxH=224): # grab dimensions of input image (w, h) = image.size # GoogLeNet was trained on images with maximum width and heights # of 224 pixels -- if either dimension is larger than 224 pixels, # then we'll need to do some resizing if h > maxH or w > maxW: # resize based on width if w > h: r = maxW / float(w) # resize based on height else: r = maxH / float(h) # resize the image (nW, nH) = (int(r * w), int(r * h)) image = np.float32(image.resize((nW, nH), PIL.Image.BILINEAR)) (src, dst) = (net.blobs["data"], net.blobs[end]) src.reshape(1, 3, nH, nW) src.data[0] = preprocess(net, image) net.forward(end=end) guide_features = dst.data[0].copy() return guide_features # ------- # Make dreams # -------
Example #16
Source File: 2_dreaming_time.py From DeepDreamVideo with GNU General Public License v2.0 | 5 votes |
def resizePicture(image,width): img = PIL.Image.open(image) basewidth = width wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) return img.resize((basewidth,hsize), PIL.Image.ANTIALIAS)
Example #17
Source File: 2_dreaming_time.py From DeepDreamVideo with GNU General Public License v2.0 | 5 votes |
def morphPicture(filename1,filename2,blend,width): img1 = PIL.Image.open(filename1) img2 = PIL.Image.open(filename2) if width is not 0: img2 = resizePicture(filename2,width) return PIL.Image.blend(img1, img2, blend)
Example #18
Source File: base.py From BrainSpace with BSD 3-Clause "New" or "Revised" License | 5 votes |
def to_notebook(self, transparent_bg=True, scale=(1, 1)): # if not in_notebook(): # raise ValueError("Cannot find notebook.") wimg = self._win2img(transparent_bg, scale) writer = BSPNGWriter(writeToMemory=True) result = serial_connect(wimg, writer, as_data=False).result data = memoryview(result).tobytes() from IPython.display import Image return Image(data)
Example #19
Source File: frontmatter.py From talk-2014-strata-sc with MIT License | 5 votes |
def logos(): display(Image('images/calpoly_logo.png')) display(Image('images/ipython_logo.png'))
Example #20
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 #21
Source File: tiny_gp_plus.py From tiny_gp with GNU General Public License v3.0 | 5 votes |
def draw_tree(self, fname, footer): dot = [Digraph()] dot[0].attr(kw='graph', label = footer) count = [0] self.draw(dot, count) Source(dot[0], filename = fname + ".gv", format="png").render() display(Image(filename = fname + ".gv.png"))
Example #22
Source File: utility.py From hmd with MIT License | 5 votes |
def show_img_arr(arr): im = PIL.Image.fromarray(arr) bio = BytesIO() im.save(bio, format='png') display(Image(bio.getvalue(), format='png')) # write log in training phase
Example #23
Source File: utility.py From hmd with MIT License | 5 votes |
def save_to_img(src, output_path_name, src_type = "tensor", channel_order="cwd", scale = 255): if src_type == "tensor": src_arr = np.asarray(src) * scale elif src_type == "array": src_arr = src*scale else: print("save tensor error, cannot parse src type.") return False if channel_order == "cwd": src_arr = (np.moveaxis(src_arr,0,2)).astype(np.uint8) elif channel_order == "wdc": src_arr = src_arr.astype(np.uint8) else: print("save tensor error, cannot parse channel order.") return False src_img = PIL.Image.fromarray(src_arr) src_img.save(output_path_name) return True
Example #24
Source File: utility.py From hmd with MIT License | 5 votes |
def verts2obj(out_verts, filename): vert_num = len(out_verts) faces = np.load("../predef/smpl_faces.npy") face_num = len(faces) with open(filename, 'w') as fp: for j in range(vert_num): fp.write( 'v %f %f %f\n' % ( out_verts[j,0], out_verts[j,1], out_verts[j,2]) ) for j in range(face_num): fp.write( 'f %d %d %d\n' % (faces[j,0]+1, faces[j,1]+1, faces[j,2]+1) ) PIL.Image.fromarray(src_img.astype(np.uint8)).save("./output/src_img_%d.png" % test_num) return True # compute anchor_posi from achr_verts
Example #25
Source File: jupyter.py From rasa_core with Apache License 2.0 | 5 votes |
def _display_bot_response(response: Dict): from IPython.display import Image, display for response_type, value in response.items(): if response_type == 'text': print_success(value) if response_type == 'image': image = Image(url=value) display(image,)
Example #26
Source File: util.py From EverybodyDanceNow_reproduce_pytorch 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 #27
Source File: util.py From EverybodyDanceNow_reproduce_pytorch 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 #28
Source File: test_widget_output.py From pySINDy with MIT License | 5 votes |
def test_append_display_data(): widget = widget_output.Output() # Try appending a Markdown object. widget.append_display_data(Markdown("# snakes!")) expected = ( { 'output_type': 'display_data', 'data': { 'text/plain': '<IPython.core.display.Markdown object>', 'text/markdown': '# snakes!' }, 'metadata': {} }, ) assert widget.outputs == expected, repr(widget.outputs) # Now try appending an Image. image_data = b"foobar" image_data_b64 = image_data if sys.version_info[0] < 3 else 'Zm9vYmFy\n' widget.append_display_data(Image(image_data, width=123, height=456)) expected += ( { 'output_type': 'display_data', 'data': { 'image/png': image_data_b64, 'text/plain': '<IPython.core.display.Image object>' }, 'metadata': { 'image/png': { 'width': 123, 'height': 456 } } }, ) assert widget.outputs == expected, repr(widget.outputs)
Example #29
Source File: show_image.py From tensorflow-for-poets-2 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 #30
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!'