What is the fastest way to draw an image from discrete pixel values in Python?

前端 未结 5 1860
时光取名叫无心
时光取名叫无心 2020-12-07 18:41

I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it

5条回答
  •  臣服心动
    2020-12-07 19:22

    Requirements

    For this example, install Numpy and Pillow.

    Example

    The goal is to first represent the image you want to create as an array arrays of sets of 3 (RGB) numbers - use Numpy's array(), for performance and simplicity:

    import numpy
    
    data = numpy.zeros((1024, 1024, 3), dtype=numpy.uint8)
    

    Now, set the middle 3 pixels' RGB values to red, green, and blue:

    data[512, 511] = [255, 0, 0]
    data[512, 512] = [0, 255, 0]
    data[512, 513] = [0, 0, 255]
    

    Then, use Pillow's Image.fromarray() to generate an Image from the array:

    from PIL import Image
    
    image = Image.fromarray(data)
    

    Now, "show" the image (on OS X, this will open it as a temp-file in Preview):

    image.show()
    

    Note

    This answer was inspired by BADCODE's answer, which was too out of date to use and too different to simply update without completely rewriting.

提交回复
热议问题