python类Image()的实例源码

visualize.py 文件源码 项目:zipline-chinese 作者: zhanghan1990 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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())
visualize.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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())
07_Inception_Model.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def classify(image_path):
    # Display the image.
    display(Image(image_path))

    # Use the Inception model to classify the image.
    pred = model.classify(image_path=image_path)

    # Print the scores and names for the top-10 predictions.
    model.print_scores(pred=pred, k=10, only_first_name=True)    


# ## Panda

# This image of a panda is included in the Inception data-file. The Inception model is quite confident that this image shows a panda, with a classification score of 89.23% and the next highest score being only 0.86% for an indri, which is another exotic animal.

# In[8]:
14_DeepDream.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot_image(image):
    # Assume the pixel-values are scaled between 0 and 255.

    if False:
        # Convert the pixel-values to the range between 0.0 and 1.0
        image = np.clip(image/255.0, 0.0, 1.0)

        # Plot using matplotlib.
        plt.imshow(image, interpolation='lanczos')
        plt.show()
    else:
        # Ensure the pixel-values are between 0 and 255.
        image = np.clip(image, 0.0, 255.0)

        # Convert pixels to bytes.
        image = image.astype(np.uint8)

        # Convert to a PIL-image and display it.
        display(PIL.Image.fromarray(image))


# Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient.

# In[13]:
visualization.py 文件源码 项目:tensorlight 作者: bsautermeister 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def image_from_array(img_array, format='png'):
    """Creates an image object from a given numpy array.
    Parameters
    ----------
    img_array : numpy.ndarray
        The image data, which can have 1 or 3 color channels.
    Returns
    -------
    IPython.display.Image
        An image object for plots.
    """
    factor = 1
    if utils.image.is_float_image(img_array):
        factor = 255

    img_data = np.uint8(img_array * factor)
    f = StringIO()
    img_data = utils.image.to_rgb(img_data)
    arr = PIL.Image.fromarray(img_data)
    arr.save(f, format)
    return Image(data=f.getvalue())
notebook_tools.py 文件源码 项目:tissuelab 作者: VirtualPlants 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def vtk_show(renderer, width=400, height=300):
    """
    Takes vtkRenderer instance and returns an IPython Image with the rendering.
    """
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetOffScreenRendering(1)
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(width, height)
    renderWindow.Render()

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renderWindow)
    windowToImageFilter.Update()

    writer = vtk.vtkPNGWriter()
    writer.SetWriteToMemory(1)
    writer.SetInputConnection(windowToImageFilter.GetOutputPort())
    writer.Write()
    data = str(buffer(writer.GetResult()))

    return Image(data)
insights.py 文件源码 项目:menrva 作者: amirziai 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def decision_tree(X, y, regression, max_depth=3):
    from sklearn.tree import export_graphviz
    from sklearn.externals.six import StringIO  
    from IPython.core.pylabtools import figsize
    from IPython.display import Image
    figsize(12.5, 6)
    import pydot

    if regression:
        clf = DecisionTreeRegressor(max_depth=max_depth)
    else:
        clf = DecisionTreeClassifier(max_depth=max_depth)

    clf.fit(X, y)
    dot_data = StringIO()  
    export_graphviz(clf, out_file=dot_data, feature_names=list(X.columns),
                    filled=True, rounded=True,)
    graph = pydot.graph_from_dot_data(dot_data.getvalue())  
    return Image(graph.create_png())
DeepDream.py 文件源码 项目:QScode 作者: PierreHao 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def Run(self, img_path, guide_image_path='', objective=0):
        """Run deep dream"""
        self.guide_path = guide_image_path
        if self.guide_path != '':
            self.Get_guide()
        self.net.blobs.keys()
        if img_path != '':
            frame = PIL.Image.open(img_path)
            frame = imresize(frame)
            frame = np.float32(frame)
        else:
            frame = self.GenerateInputImage()
        frame_i = 0
        h, w = frame.shape[:2]
        #s = 0.05 # scale coefficient
        for i in xrange(self.epoch):
            start = time.time()
            frame = self.Deepdream(frame)
            PIL.Image.fromarray(np.uint8(frame)).save("frames/%04d.jpg"%frame_i)
            #frame = nd.affine_transform(frame, [1-s,1-s,1], [h*s/2,w*s/2,0], order=1)
            frame_i += 1
            stop = time.time()
            print "Time cost for {:d}th image: {:.3f} s".format(i,stop-start)
main.py 文件源码 项目:rstviewer 作者: arne-cl 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def embed_rs3_image(rs3_filepath, shrink_to_fit=True):
    """Render an RST tree given the path to an .rs3 file."""
    from IPython.display import display, Image
    display(Image(rs3topng(rs3_filepath), unconfined=not(shrink_to_fit)))
dot.py 文件源码 项目:xarray-simlab 作者: benbovy 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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("Unknown format '%s' passed to `dot_graph`" % format)
circuit.py 文件源码 项目:quantum-SVM 作者: JinlongHuang 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def png(self):
        from IPython.display import Image
        return Image(self._repr_png_(), embed=True)
load_redten_ipython_env.py 文件源码 项目:sci-pype 作者: jay-johnson 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
script.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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()))


#ANIMAL model (default)
#Here you select the model
2models.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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()))


#ANIMAL model (default)
#Here you select the model
DreamControl.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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()))



#Here you select the model
layer_key_gen.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()))


#ANIMAL
#PLEASE MAKE SURE TO SELECT THE RIGHT MODEL FOR THE KEYS!!!
video.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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()))



#Here you select the model
video-convert.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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()))


#ANIMAL model (default)
#Here you select the model
performance.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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()))



#Here you select the model
inception.py 文件源码 项目:deepdream 作者: martinkaptein 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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()))



#Here you select the model
util.py 文件源码 项目:video-pose-extractor 作者: JustinShenk 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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()))
util.py 文件源码 项目:video-pose-extractor 作者: JustinShenk 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
plotly.py 文件源码 项目:lddmm-ot 作者: jeanfeydy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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))

```

14_DeepDream.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def load_image(filename):
    image = PIL.Image.open(filename)

    return np.float32(image)


# Save an image as a jpeg-file. The image is given as a numpy array with pixel-values between 0 and 255.

# In[11]:
14_DeepDream.py 文件源码 项目:LIE 作者: EmbraceLife 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def save_image(image, filename):
    # Ensure the pixel-values are between 0 and 255.
    image = np.clip(image, 0.0, 255.0)

    # Convert to bytes.
    image = image.astype(np.uint8)

    # Write the image-file in jpeg-format.
    with open(filename, 'wb') as file:
        PIL.Image.fromarray(image).save(file, 'jpeg')


# This function plots an image. Using matplotlib gives low-resolution images. Using PIL gives pretty pictures.

# In[12]:
FastNeuralTransfer.py 文件源码 项目:Deep-learning-with-cats 作者: AlexiaJM 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def forward(self, input):
        # Return itself + the result of the two convolutions
        output = self.model(input) + input
        return output

# Image transformation network
show_image.py 文件源码 项目:tensorflow-for-poets-2 作者: googlecodelabs 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
visualization.py 文件源码 项目:tensorlight 作者: bsautermeister 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def display_image(image):
    """Display an image object.
    Remarks: Some RGB images might be displayed with changed colors.
    Parameters
    ----------
    image : IPython.display.Image
        The image to display.
    """
    if image is None:
        return

    display(image)
formatter.py 文件源码 项目:yuuno 作者: Irrational-Encoding-Wizardry 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def ipy_image(self) -> IPyImage:
        """
        Converts a clip to an image.
        """
        raw = self.environment.parent.output.bytes_of(self.first_frame)
        return IPyImage(
            data=raw,
            format="png",
            embed=True,
            unconfined=True,
            width=self.first_frame.width,
            height=self.first_frame.height
        )
deepdream.py 文件源码 项目:DeepArt 作者: jiriroz 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def loadimg(self, filename):
        return np.float32(PIL.Image.open(filename))


问题


面经


文章

微信
公众号

扫码关注公众号