如何从内存缓冲区(StringIO)或使用opencv python库的url读取映像 [英] How to read image from in memory buffer (StringIO) or from url with opencv python library

查看:901
本文介绍了如何从内存缓冲区(StringIO)或使用opencv python库的url读取映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需共享一种从内存缓冲区或url创建opencv图像对象的方法来提高性能。

Just share a way to create opencv image object from in memory buffer or from url to improve performance.

有时我们从url获取图像二进制文件,以避免其他文件IO,我们希望从内存缓冲区或url中 imread 此图像,但imread仅支持从带有路径的文件系统读取图像。

Sometimes we get image binary from url, to avoid additional file IO, we want to imread this image from in memory buffer or from url, but imread only supports read image from file system with path.

推荐答案

要使用内存缓冲区(StringIO)创建OpenCV图像对象,我们可以使用OpenCV API imdecode,请参阅下面的代码:

To create an OpenCV image object with in memory buffer(StringIO), we can use OpenCV API imdecode, see code below:

import cv2
import numpy as np
from urllib2 import urlopen
from cStringIO import StringIO

def create_opencv_image_from_stringio(img_stream, cv2_img_flag=0):
    img_stream.seek(0)
    img_array = np.asarray(bytearray(img_stream.read()), dtype=np.uint8)
    return cv2.imdecode(img_array, cv2_img_flag)

def create_opencv_image_from_url(url, cv2_img_flag=0):
    request = urlopen(url)
    img_array = np.asarray(bytearray(request.read()), dtype=np.uint8)
    return cv2.imdecode(img_array, cv2_img_flag)

这篇关于如何从内存缓冲区(StringIO)或使用opencv python库的url读取映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆