opencl - 使用 PyOpenCL 复制图像

标签 opencl python-imaging-library pyopencl

我在使用 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")

我作为输入给出的图像是 enter image description here

但是,程序的输出是 enter image description here

我无法理解为什么会出现这些黑线。 请帮我解决这个错误。

谢谢

好的!所以我找到了解决方案。我将所有 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/

相关文章:

coding-style - 如何构建大型 OpenCL 内核?

c++ - OpenCL 内核浮点除法给出不同的结果

python - PyOpenCL 多维数组

python - pyopencl 示例设备错误

architecture - AMD 设备上的物理内存 : local vs private

data-structures - 在 opencl 中使用自定义结构

python - 将图像转换为 numpy 数组,然后立即将其转换回图像会产生两种不同的结果

python - pip 无法安装 PIL 或 Pillow 并出现 mt.exe 错误

python - 在 Jupyter 笔记本中使用 Pillow 读取图像失败

performance - 编译警告 OpenCL 矩阵乘法