来自numpy数组的

时间:2016-09-16 14:10:57

标签: python image numpy opencl pyopencl

我想使用pyopencl从numpy数组构建一个OpenCL 3D RGBA图像。我知道cl.image_from_array()函数,它基本上就是这样,但是没有对cl.enqueue_copy()公开的命令队列或事件进行任何控制。所以我真的想使用后一个函数,将3D RGBA图像从主机传输到设备,但我似乎无法正确获取图像构造函数的语法。

所以在这种环境下

import pyopencl as cl
import numpy as np

platform = cl.get_platforms()[0]
devs = platform.get_devices()
device1 = devs[1]
mf = cl.mem_flags
ctx = cl.Context([device1])
Queue1=cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)

我想做一些模拟

的事情
  d_colortest = cl.image_from_array(ctx,np.zeros((256,256,256,4)).astype(np.float32),num_channels=4,mode='w')

使用功能

d_image = cl.Image(...)
event = cl.enqueue_copy(...)

1 个答案:

答案 0 :(得分:0)

我调整了cl.image_from_array()函数以便能够返回一个事件,这基本上是直截了当的:

def p_Array(queue_s, name, ary, num_channels=4, mode="w", norm_int=False,copy=True):
    q = eval(queue_s)
    if not ary.flags.c_contiguous:
        raise ValueError("array must be C-contiguous")

    dtype = ary.dtype
    if num_channels is None:

        from pyopencl.array import vec
        try:
            dtype, num_channels = vec.type_to_scalar_and_count[dtype]
        except KeyError:
            # It must be a scalar type then.
            num_channels = 1

        shape = ary.shape
        strides = ary.strides

    elif num_channels == 1:
        shape = ary.shape
        strides = ary.strides
    else:
        if ary.shape[-1] != num_channels:
            raise RuntimeError("last dimension must be equal to number of channels")

        shape = ary.shape[:-1]
        strides = ary.strides[:-1]

    if mode == "r":
        mode_flags = cl.mem_flags.READ_ONLY
    elif mode == "w":
        mode_flags = cl.mem_flags.WRITE_ONLY
    else:
        raise ValueError("invalid value '%s' for 'mode'" % mode)

    img_format = {
            1: cl.channel_order.R,
            2: cl.channel_order.RG,
            3: cl.channel_order.RGB,
            4: cl.channel_order.RGBA,
            }[num_channels]

    assert ary.strides[-1] == ary.dtype.itemsize

    if norm_int:
        channel_type = cl.DTYPE_TO_CHANNEL_TYPE_NORM[dtype]
    else:
        channel_type = cl.DTYPE_TO_CHANNEL_TYPE[dtype]

    d_image = cl.Image(ctx, mode_flags,
            cl.ImageFormat(img_format, channel_type),
            shape=shape[::-1])
    if copy:
        event = cl.enqueue_copy(q,d_image,ary,origin=(0,0,0),region=shape[::-1])
        event_list.append((event,queue_s,name))
    return d_image, event