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

前端 未结 5 1862
时光取名叫无心
时光取名叫无心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 19:28

    A different approach is to use Pyxel, an open source implementation of the TIC-80 API in Python3 (TIC-80 is the open source PICO-8).

    Here's a complete app that just draws one yellow pixel on a black background:

    import pyxel
    
    def update():
    
        """This function just maps the Q key to `pyxel.quit`,
        which works just like `sys.exit`."""
    
        if pyxel.btnp(pyxel.KEY_Q): pyxel.quit()
    
    def draw():
    
        """This function clears the screen and draws a single
        pixel, whenever the buffer needs updating. Note that
        colors are specified as palette indexes (0-15)."""
    
        pyxel.cls(0)            # clear screen (color)
        pyxel.pix(10, 10, 10)   # blit a pixel (x, y, color)
    
    pyxel.init(160, 120)        # initilize gui (width, height)
    pyxel.run(update, draw)     # run the game  (*callbacks)
    

    Note: The library only allows for up to sixteen colors, but you can change which colors, and you could probably get it to support more without too much work.

提交回复
热议问题