问题描述
我想使用pyopencl从一个numpy数组构造一个OpenCL 3D RGBA图像.我知道 cl.image_from_array()
函数,基本上可以做到这一点,但是并没有提供对由 cl.enqueue_copy()<.因此,我真的很想使用后者的功能,将3D RGBA图像从主机传输到设备,但是我似乎无法正确获取图像构造函数的语法.
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.
所以在这种环境下
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(...)
推荐答案
我修改了 cl.image_from_array()
函数,使其能够返回事件,该过程基本上很简单:
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
这篇关于来自numpy数组的PyopenCL 3D RGBA图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!