如何将魔杖图像对象转换为 opencv 图像(numpy 数组)

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

我已经使用以下代码导入了魔杖

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

如何将 img 对象转换为在 python 中打开 cv (cv2) 图像对象?

您只需写入一个字节数组缓冲区,然后传递给 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)