如何将wand图像对象转换为打开cv图像(numpy数组)

c.P*_*rsi 5 opencv imagemagick python-2.7 wand

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

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
Run Code Online (Sandbox Code Playgroud)

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

emc*_*lle 8

您只需写入字节数组缓冲区,然后传递给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)
Run Code Online (Sandbox Code Playgroud)

  • 只是评论它是如何工作的,IIUC make_blob()返回以另一种格式编码的图像,显​​然是BMP,然后OpenCV可以理解和解码.找到一种直接创建数组的方法会很好.显然numpy.asarray(img)应该在这里工作,但它并没有真正做到正确的事情,它创建了一个"wand.color.Color"对象的数组...... (3认同)