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

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

错误解决办法一:

image = Image.open(request.files["fullimage"])

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

错误解决办法二:

image = Image.open(request.files["fullimage"].read())

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

正确解决办法:

img = Image.open(request.files['file'].stream)

 

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

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

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值