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

前端 未结 5 1863
时光取名叫无心
时光取名叫无心 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:26

    If you have numpy and scipy available (and if you are manipulating large arrays in Python, I would recommend them), then the scipy.misc.pilutil.toimage function is very handy. A simple example:

    import numpy as np
    import scipy.misc as smp
    
    # Create a 1024x1024x3 array of 8 bit unsigned integers
    data = np.zeros( (1024,1024,3), dtype=np.uint8 )
    
    data[512,512] = [254,0,0]       # Makes the middle pixel red
    data[512,513] = [0,0,255]       # Makes the next pixel blue
    
    img = smp.toimage( data )       # Create a PIL image
    img.show()                      # View in default viewer
    

    The nice thing is toimage copes with different data types very well, so a 2D array of floating-point numbers gets sensibly converted to grayscale etc.

    You can download numpy and scipy from here. Or using pip:

    pip install numpy scipy
    

提交回复
热议问题