How to make a checkerboard in numpy?

后端 未结 24 1328
小鲜肉
小鲜肉 2020-11-30 07:52

I\'m using numpy to initialize a pixel array to a gray checkerboard (the classic representation for \"no pixels\", or transparent). It seems like there ought to be a whizzy

24条回答
  •  佛祖请我去吃肉
    2020-11-30 08:28

    Very very late, but I needed a solution that allows for a non-unit checker size on an arbitrarily sized checkerboard. Here's a simple and fast solution:

    import numpy as np
    
    def checkerboard(shape, dw):
        """Create checkerboard pattern, each square having width ``dw``.
    
        Returns a numpy boolean array.
        """
        # Create individual block
        block = np.zeros((dw * 2, dw * 2), dtype=bool)
        block[dw:, :dw] = 1
        block[:dw, dw:] = 1
    
        # Tile until we exceed the size of the mask, then trim
        repeat = (np.array(shape) + dw * 2) // np.array(block.shape)
        trim = tuple(slice(None, s) for s in shape)
        checkers = np.tile(block, repeat)[trim]
    
        assert checkers.shape == shape
        return checkers
    

    To convert the checkerboard squares to colors, you could do:

    checkers = checkerboard(shape, dw)
    img = np.empty_like(checkers, dtype=np.uint8)
    img[checkers] = 0xAA
    img[~checkers] = 0x99
    

提交回复
热议问题