How to read image from in memory buffer (StringIO) or from url with opencv python library

evanchin picture evanchin · Nov 11, 2012 · Viewed 24k times · Source

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

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.

Answer

evanchin picture evanchin · Nov 11, 2012

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)