How to make a checkerboard in numpy?

后端 未结 24 1268
小鲜肉
小鲜肉 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:16

    Here's a numpy solution with some checking to make sure that the width and height are evenly divisible by the square size.

    def make_checkerboard(w, h, sq, fore_color, back_color):
        """
        Creates a checkerboard pattern image
        :param w: The width of the image desired
        :param h: The height of the image desired
        :param sq: The size of the square for the checker pattern
        :param fore_color: The foreground color
        :param back_color: The background color
        :return:
        """
        w_rem = np.mod(w, sq)
        h_rem = np.mod(w, sq)
        if w_rem != 0 or h_rem != 0:
            raise ValueError('Width or height is not evenly divisible by square '
                             'size.')
        img = np.zeros((h, w, 3), dtype='uint8')
        x_divs = w // sq
        y_divs = h // sq
        fore_tile = np.ones((sq, sq, 3), dtype='uint8')
        fore_tile *= np.array([[fore_color]], dtype='uint8')
        back_tile = np.ones((sq, sq, 3), dtype='uint8')
        back_tile *= np.array([[back_color]], dtype='uint8')
        for y in np.arange(y_divs):
            if np.mod(y, 2):
                b = back_tile
                f = fore_tile
            else:
                b = fore_tile
                f = back_tile
            for x in np.arange(x_divs):
                if np.mod(x, 2) == 0:
                    img[y * sq:y * sq + sq, x * sq:x * sq + sq] = f
                else:
                    img[y * sq:y * sq + sq, x * sq:x * sq + sq] = b
        return img
    

提交回复
热议问题