我在使用 PyOpenCL 制作图像副本时遇到了一些问题。我想尝试复制,因为我真的想做其他处理,但我无法理解访问每个像素的基本任务。请帮助我捕获错误以确保其正常工作。
这是程序
import pyopencl as cl
import numpy
import Image
import sys
img = Image.open(sys.argv[1])
img_arr = numpy.asarray(img).astype(numpy.uint8)
dim = img_arr.shape
host_arr = img_arr.reshape(-1)
ctx = cl.create_some_context()
queue = cl.CommandQueue(ctx)
mf = cl.mem_flags
a_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=host_arr)
dest_buf = cl.Buffer(ctx, mf.WRITE_ONLY, host_arr.nbytes)
kernel_code = """
__kernel void copyImage(__global const uint8 *a, __global uint8 *c)
{
int rowid = get_global_id(0);
int colid = get_global_id(1);
int ncols = %d;
int npix = %d; //number of pixels, 3 for RGB 4 for RGBA
int index = rowid * ncols * npix + colid * npix;
c[index + 0] = a[index + 0];
c[index + 1] = a[index + 1];
c[index + 2] = a[index + 2];
}
""" % (dim[1], dim[2])
prg = cl.Program(ctx, kernel_code).build()
prg.copyImage(queue, (dim[0], dim[1]) , None, a_buf, dest_buf)
result = numpy.empty_like(host_arr)
cl.enqueue_copy(queue, result, dest_buf)
result_reshaped = result.reshape(dim)
img2 = Image.fromarray(result_reshaped, "RGB")
img2.save("new_image_gpu.bmp")
我作为输入给出的图像是
但是,程序的输出是
我无法理解为什么会出现这些黑线。 请帮我解决这个错误。
谢谢
好的!所以我找到了解决方案。我将所有 uint8 更改为 int,并在 numpy 数组中删除了“astype(numpy.uint8)”。我不知道为什么,我只是尝试了一下,它成功了。解释为什么会有所帮助。另外,这是否意味着现在会占用更多内存? 它有效,但现在我认为它需要更多的内存。任何使用 uint8 的解决方法都会有所帮助。
最佳答案
您在 Python 和 OpenCL 中使用的数据类型不匹配。在 numpy 中,uint8
是一个 8 位无符号整数(我想这就是您想要的)。在 OpenCL 中,uint8
是 32 位无符号整数的 8 元素向量。 OpenCL 中 8 位无符号整数的正确数据类型是 uchar
。因此,您的 astype(numpy.uint8)
没问题,但它应该在 OpenCL 内核中伴随有 __global const uchar*
数组。
如果您正在处理图像,我还建议您研究 OpenCL 的专用图像类型,它可以利用某些硬件中对处理图像的 native 支持。
关于opencl - 使用 PyOpenCL 复制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893296/