python 如何在numpy中制作棋盘格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2169478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:57:59  来源:igfitidea点击:

How to make a checkerboard in numpy?

pythonnumpy

提问by Ned Batchelder

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 way to do it with numpy's amazing array assignment/slicing/dicing operations, but this is the best I've come up with:

我正在使用 numpy 将像素数组初始化为灰色棋盘格(“无像素”或透明的经典表示)。似乎应该有一种奇特的方法来使用 numpy 惊人的数组分配/切片/切块操作,但这是我想出的最好的方法:

w, h = 600, 800
sq = 15    # width of each checker-square
self.pix = numpy.zeros((w, h, 3), dtype=numpy.uint8)
# Make a checkerboard
row = [[(0x99,0x99,0x99),(0xAA,0xAA,0xAA)][(i//sq)%2] for i in range(w)]
self.pix[[i for i in range(h) if (i//sq)%2 == 0]] = row
row = [[(0xAA,0xAA,0xAA),(0x99,0x99,0x99)][(i//sq)%2] for i in range(w)]
self.pix[[i for i in range(h) if (i//sq)%2 == 1]] = row

It works, but I was hoping for something simpler.

它有效,但我希望有更简单的东西。

回答by Falko

I'd use the Kronecker productkron:

我会使用Kronecker 产品kron

np.kron([[1, 0] * 4, [0, 1] * 4] * 4, np.ones((10, 10)))

The checkerboard in this example has 2*4=8 fields of size 10x10 in each direction.

本例中的棋盘格在每个方向上有 2*4=8 个大小为 10x10 的字段。

回答by doug

this ought to do it

这应该这样做

any size checkerboard you want (just pass in width and height, as w, h); also i have hard-coded cell height/width to 1, though of course this could also be parameterized so that an arbitrary value is passed in:

您想要的任何尺寸的棋盘格(只需传入宽度和高度,如 w、h);我也将单元格高度/宽度硬编码为 1,当然这也可以参数化,以便传入任意值:

>>> import numpy as NP

>>> def build_checkerboard(w, h) :
      re = NP.r_[ w*[0,1] ]              # even-numbered rows
      ro = NP.r_[ w*[1,0] ]              # odd-numbered rows
      return NP.row_stack(h*(re, ro))


>>> checkerboard = build_checkerboard(5, 5)

>>> checkerboard
 Out[3]: array([[0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
               [1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
               [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
               [1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
               [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
               [1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
               [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
               [1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
               [0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
               [1, 0, 1, 0, 1, 0, 1, 0, 1, 0]])

with this 2D array, it's simple to render an image of a checkerboard, like so:

使用这个二维数组,渲染棋盘格的图像很简单,如下所示:

>>> import matplotlib.pyplot as PLT

>>> fig, ax = PLT.subplots()
>>> ax.imshow(checkerboard, cmap=PLT.cm.gray, interpolation='nearest')
>>> PLT.show()

回答by Eelco Hoogendoorn

def checkerboard(shape):
    return np.indices(shape).sum(axis=0) % 2

Most compact, probably the fastest, and also the only solution posted that generalizes to n-dimensions.

最紧凑,可能是最快的,也是发布的唯一可推广到 n 维的解决方案。

回答by unutbu

Here's another way to do it using ogridwhich is a bit faster:

这是另一种使用ogrid速度更快的方法:

import numpy as np
import Image

w, h = 600, 800
sq = 15
color1 = (0xFF, 0x80, 0x00)
color2 = (0x80, 0xFF, 0x00)

def use_ogrid():
    coords = np.ogrid[0:w, 0:h]
    idx = (coords[0] // sq + coords[1] // sq) % 2
    vals = np.array([color1, color2], dtype=np.uint8)
    img = vals[idx]
    return img

def use_fromfunction():
    img = np.zeros((w, h, 3), dtype=np.uint8)
    c = np.fromfunction(lambda x, y: ((x // sq) + (y // sq)) % 2, (w, h))
    img[c == 0] = color1
    img[c == 1] = color2
    return img

if __name__ == '__main__':
    for f in (use_ogrid, use_fromfunction):
        img = f()
        pilImage = Image.fromarray(img, 'RGB')
        pilImage.save('{0}.png'.format(f.func_name))

Here are the timeit results:

以下是时间结果:

% python -mtimeit -s"import test" "test.use_fromfunction()"
10 loops, best of 3: 307 msec per loop
% python -mtimeit -s"import test" "test.use_ogrid()"
10 loops, best of 3: 129 msec per loop

回答by Ben Kirwin

Late, but for posterity:

晚了,但为了后代:

def check(w, h, c0, c1, blocksize):
  tile = np.array([[c0,c1],[c1,c0]]).repeat(blocksize, axis=0).repeat(blocksize, axis=1)
  grid = np.tile(tile, ( h/(2*blocksize)+1, w/(2*blocksize)+1, 1))
  return grid[:h,:w]

回答by Ned Batchelder

I'm not sure if this is better than what I had:

我不确定这是否比我拥有的更好:

c = numpy.fromfunction(lambda x,y: ((x//sq) + (y//sq)) % 2, (w,h))
self.chex = numpy.array((w,h,3))
self.chex[c == 0] = (0xAA, 0xAA, 0xAA)
self.chex[c == 1] = (0x99, 0x99, 0x99)

回答by telliott99

Can't you use hstack and vstack? See here. Like this:

你不能用hstack和vstack吗?见这里。像这样:

>>> import numpy as np
>>> b = np.array([0]*4)
>>> b.shape = (2,2)
>>> w = b + 0xAA
>>> r1 = np.hstack((b,w,b,w,b,w,b))
>>> r2 = np.hstack((w,b,w,b,w,b,w))
>>> board = np.vstack((r1,r2,r1,r2,r1,r2,r1))

回答by priya_03

import numpy as np
x = np.ones((3,3))
print("Checkerboard pattern:")
x = np.zeros((8,8),dtype=int)
# (odd_rows, even_columns)
x[1::2,::2] = 1
# (even_rows, odd_columns)
x[::2,1::2] = 1
print(x)

回答by pranjul gupta

Numpy's Tile function to get checkerboard array of size n*n

Numpy 的 Tile 函数获取大小为 n*n 的棋盘数组

import numpy

n = 4

list_0_1 = [ [ 0, 1], [ 1, 0] ]

checkerboard = numpy.tile( list_0_1, ( n//2, n//2) ) 

print( checkerboard)

[[0 1 0 1]
 [1 0 1 0]
 [0 1 0 1]
 [1 0 1 0]]

回答by Geoff Langenderfer

import numpy as np

a=np.array(([1,0]*4+[0,1]*4)*4).reshape((8,8))
print(a)


[[1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]]