如何将魔杖图像对象转换为 numpy 数组(没有 OpenCV)?

How to convert a wand image object to numpy array (without OpenCV)?

我正在使用 Wand 将 pdf 文件转换为图像。然后,我使用 ndimage 进行进一步的图像处理。

我想直接将Wand图像转换成ndarray...我看到了答案,但它使用OpenCV。这可能不使用 OpenCV 吗?

目前我保存了一个临时文件,用scipy.misc.imread()

重新打开

您可以像这样使用缓冲区:

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

这是

的 Python3 版本
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)

以下是 Python3 没有缓冲区时对我有用的方法:

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)

Wand 0.5.3 开始直接支持此功能

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)