How can I convert an array of pixel colors into an image efficiently with Python?

I am working on a project that implements Numba and CUDA with Python 3.8. Currently, I create an array with the dimensions of the final image. Next, I generate an image with a CUDA kernel (incredibly fast). Then, I copy the pixel color into a Pillow Image (incredibly slow). My code:

for x in range(width):
    for y in range(height):
        if pixels[x][y] = 0:
            color = [0, 0, 0]
            # Get color from int as tuple
            color = rgb_conv(pixels[x][y]
        red = int(numpy.floor(color[0]))
        if red > 255:
            red = 255
        elif red < 0:
            red = 0

        green = int(numpy.floor(color[1]))
        if green > 255:
            green = 255
        elif green < 0:
            green = 0

        blue = int(numpy.floor(color[2]))
        if blue > 255:
            blue = 255
        elif blue < 0:
            blue = 0

        image.putpixel((x, y), (red, green, blue))

Are there any more efficient Python image libraries for this implementation? Is there a way to convert the array to an image on the GPU? Any help with direction works. Thanks!

EDIT 1: A request was made for the function rgb_conv. This is a function I found to convert a single integer into a three-wide color.

def rgb_conv(i):
    color = 255 * numpy.array(colorsys.hsv_to_rgb(i / 255.0, 1.0, 0.5))
    return tuple(color.astype(int))

However, I didn't particularly like the colors this function produces, so I removed it and began working with the following:

pixelArr = image.load()
for x in range(width):
    for y in range(height):
        color = int(numpy.floor(pixels[x][y]))
        pixelArr[x, y] = (color << 21) + (color << 10) + color * 8

This adjustment doesn't do much to the running time of the code. I am looking further into a suggestion load the image from an array rather than putting each pixel into the image.

Read more here:

Content Attribution

This content was originally published by Spencer Cain at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: