6

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?

emcconville
  • 23,800
  • 4
  • 50
  • 66
c.Parsi
  • 771
  • 2
  • 9
  • 26

1 Answers1

10

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)
emcconville
  • 23,800
  • 4
  • 50
  • 66
  • 3
    Just a comment on how this works, IIUC make_blob() returns the image encoded in another format, apparently BMP, which OpenCV can then understand and decode. It would be nice to find a way to directly create the array. Apparently numpy.asarray(img) should work here, but it doesn't really do the correct thing, it creates an array of "wand.color.Color" objects... – dividebyzero Jan 23 '17 at 16:11
  • 1
    I faced a problem with alpha channel, while handling a pdf. It is better to put `img.alpha_channel = 'remove'` after having set the background color. – Vasilis Lemonidis Oct 03 '17 at 08:03