7

I am converting pdf files to image using Wand. Then, I do further image processing using ndimage.

I would like to directly convert the Wand image into a ndarray... I have seen the answer here, but it use OpenCV. Is this possible without using OpenCV?

For the moment I save a temporary file, which is re-opened with scipy.misc.imread()

xdze2
  • 3,986
  • 2
  • 12
  • 29

4 Answers4

7

As of Wand 0.5.3 this is supported directly

import numpy as np
from wand.image import Image

with Image(filename='rose:') as img:
    array = np.array(img)
    print(array.shape)  #=> (70, 46, 3)
Pranasas
  • 597
  • 6
  • 22
1

You can use a buffer, like this:

import cStringIO
import skimage.io
from wand.image import Image
import numpy

#create the image, then place it in a buffer
with Image(width = 500, height = 100) as image:
    image.format        = 'bmp'
    image.alpha_channel = False
    img_buffer=numpy.asarray(bytearray(image.make_blob()), dtype=numpy.uint8)

#load the buffer into an array
img_stringIO = cStringIO.StringIO(img_buffer)
img = skimage.io.imread(img_stringIO)

img.shape
MrMartin
  • 411
  • 5
  • 18
1

Here is a Python3 version of MrMartin's answer

from io import BytesIO
import skimage.io
from wand.image import Image
import numpy

with Image(width=100, height=100) as image:
    image.format = 'bmp'
    image.alpha_channel = False
    img_buffer = numpy.asarray(bytearray(image.make_blob()), dtype='uint8')
bytesio = BytesIO(img_buffer)
img = skimage.io.imread(bytesio)

print(img.shape)
simlmx
  • 999
  • 12
  • 17
1

Here's what worked for me with Python3 without buffers:

from wand.image import Image
import numpy
with Image(width=100, height=100) as image:
    image.format = 'gray' #If rgb image, change this to 'rgb' to get raw values
    image.alpha_channel = False
    img_array = numpy.asarray(bytearray(image.make_blob()), dtype='uint8').reshape(image.size)
kamyonet
  • 88
  • 5