在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