Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert wand image object to open cv image (numpy array)

I have imported wand using the following code

from wand.image import Image as WandImage
from wand.color import Color
with WandImage(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
    img.background_color = Color('white')
    img.format        = 'tif'
    img.alpha_channel = False

How can i convert img object to open cv (cv2) image object in python?

like image 369
c.Parsi Avatar asked May 03 '16 23:05

c.Parsi


People also ask

Can an image could be converted into a NumPy array?

Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.

Why do we convert image to NumPy array?

Converting an image to an array is an important task to train a machine learning model based on the features of an image. We mainly use the NumPy library in Python to work with arrays so we can also use it to convert images to an array. Other than NumPy, we can also use the Keras library in Python for the same task.


1 Answers

You would simply write to a byte-array buffer, and pass to cv2.imdecode.

from wand.image import Image as WandImage
from wand.color import Color
import numpy
import cv2

RESOLUTION=72
source_file='rose:'
img_buffer=None

with WandImage(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
    img.background_color = Color('white')
    img.format        = 'tif'
    img.alpha_channel = False
    # Fill image buffer with numpy array from blob
    img_buffer=numpy.asarray(bytearray(img.make_blob()), dtype=numpy.uint8)

if img_buffer is not None:
    retval = cv2.imdecode(img_buffer, cv2.IMREAD_UNCHANGED)
like image 97
emcconville Avatar answered Sep 21 '22 22:09

emcconville