首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >AI展示框架(2):flask图像上传无法输入为图像识别程序的PIL图像的问题解决

AI展示框架(2):flask图像上传无法输入为图像识别程序的PIL图像的问题解决

作者头像
sparkexpert
发布2019-05-26 14:12:53
发布2019-05-26 14:12:53
1.9K0
举报

在DL+图像场景识别的程序中,其输入大多需要PIL的图像格式,而flask上传的图像的格式如何转化为PIL的图像格式,这是碰到的问题之一,因此即时将之记录下来,虽然解决方法很简单。

错误解决办法一:

代码语言:javascript
复制
image = Image.open(request.files["fullimage"])

出现错误,还是无法识别图像

错误解决办法二:

代码语言:javascript
复制
image = Image.open(request.files["fullimage"].read())

仍然出现错误,这种方法还是解决不了。

正确解决办法:

代码语言:javascript
复制
img = Image.open(request.files['file'].stream)

定位到文件打开的代码,才发现输入可以是stream.

代码语言:javascript
复制
def open(fp, mode="r"):
    """
    Opens and identifies the given image file.
    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data (or call the
    :py:meth:`~PIL.Image.Image.load` method).  See
    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.
    :param fp: A filename (string), pathlib.Path object or a file object.
       The file object must implement :py:meth:`~file.read`,
       :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,
       and be opened in binary mode.
    :param mode: The mode.  If given, this argument must be "r".
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception IOError: If the file cannot be found, or the image cannot be
       opened and identified.
    """

    if mode != "r":
        raise ValueError("bad mode %r" % mode)

    exclusive_fp = False
    filename = ""
    if isPath(fp):
        filename = fp
    elif HAS_PATHLIB and isinstance(fp, Path):
        filename = str(fp.resolve())

    if filename:
        fp = builtins.open(filename, "rb")
        exclusive_fp = True

    try:
        fp.seek(0) # 在此打开文件流
    except (AttributeError, io.UnsupportedOperation):
        fp = io.BytesIO(fp.read())
        exclusive_fp = True
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年04月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档