2

我在使用 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 的任何解决方法都会有所帮助。

4

1 回答 1

4

您在 Python 和 OpenCL 中使用的数据类型不匹配。在 numpy 中,auint8是一个 8 位无符号整数(我想这就是你所追求的)。在 OpenCL 中,auint8是 32 位无符号整数的 8 元素向量。OpenCL 中 8 位无符号整数的正确数据类型是uchar. 所以,你astype(numpy.uint8)很好,但它应该伴随着__global const uchar*OpenCL 内核中的数组。

如果您正在处理图像,我还建议您查看 OpenCL 的专用图像类型,它可以利用对处理某些硬件中可用图像的本机支持。

于 2014-04-06T18:12:41.927 回答