问题
I want to construct an OpenCL 3D RGBA image from a numpy array, using pyopencl. I know about the cl.image_from_array()
function, that basically does exactly that, but doesn't give any control about command queues or events, that is exposed by cl.enqueue_copy()
. So I really would like to use the latter function, to transfer a 3D RGBA image from host to device, but I seem to not being able getting the syntax of the image constructor right.
So in this environment
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)
I would like to do something analog to
d_colortest = cl.image_from_array(ctx,np.zeros((256,256,256,4)).astype(np.float32),num_channels=4,mode='w')
Using the functions
d_image = cl.Image(...)
event = cl.enqueue_copy(...)
回答1:
I adapted the cl.image_from_array()
function to be able to return an event, which was basically straightforward:
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
来源:https://stackoverflow.com/questions/39533635/pyopencl-3d-rgba-image-from-numpy-array