OpenCV makes it very easy to read an image into memory and represent it as a Numpy array. Having a Numpy array makes it easy to manipulate the image as various mathematical matrix transformations.

How can one save the image to disk and how can one create a binary object of it in memory.

Read Image into a Numpy Array

In this example we take an image file and load it into memory using imread


import cv2 as cv
import sys

if len(sys.argv) != 2:
    exit(f"Usage: {sys.argv[0]} FILENAME")

filename = sys.argv[1]
img = cv.imread(filename)
print(type(img))  # numpy.array

Read/Write Image and convert to binary

Here we read the image from a file to a numpy array using OpenCV imread.

Then we make some simple manipulation, drawing a rectangle in the middle. We only use the fact that it is a Numpy array when extract the shape of the image. We could have done other manipulations that don't have an implementation in OpenCV.

Then we save the image as another file using imwrite.


import cv2 as cv
import sys
import io

if len(sys.argv) != 3:
    exit(f"Usage: {sys.argv[0]} IN_FILENAME OUT_FILENAME")

in_filename = sys.argv[1]
out_filename = sys.argv[2]

img = cv.imread(in_filename)
print(type(img))  # numpy.array

# Draw a rectangle in the middle in some color:
y_top = img.shape[0] // 4
x_top = img.shape[1] // 4
y_bottom = img.shape[0] - y_top
x_bottom = img.shape[1] - x_top
blue = 80
green = 70
red = 90
cv.rectangle(img, (x_top, y_top), (x_bottom, y_bottom), color=(blue, green , red), thickness=2)

# save the image to a file on the disk
cv.imwrite(out_filename, img)

# Convert the numpy array to a binary object in memory
def numpy_to_binary(arr):
    is_success, buffer = cv.imencode(".jpg", arr)
    io_buf = io.BytesIO(buffer)

binary_image = numpy_to_binary(img)

print(type(binary_image))  # bytes

Alternatively we could have converted the image into an in-memory set of bytes using imencode of OpenCV and the BytesIO of the io package.