在2个给定坐标之间更改数组项的值

时间:2018-09-26 10:25:24

标签: python

matrix = [[1, 1, 1, 1, 1, 1, 1, 1],
          [0, 1, 1, 1, 1, 0, 1, 1],
          [1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 1, 1, 1],
          [1, 1, 1, 1, 1, 0, 1, 1]]

def connect_nodes(node1, node2):
    y_distance = node2[0] - node1[0]
    x_distance = node2[1] - node1[1]

    print('distance between', node1, "and", node2, "is", y_distance, "on Y-axis and", x_distance, "on X-axis")

    if y_distance == 0:
        if x_distance > 0:
            for i in range(node1[1]+1, node1[1]+x_distance, 1):
                matrix[node1[0]][i] = 0
        if x_distance < 0:
            for i in range(node1[1]+x_distance+1, node1[1], 1):
                matrix[node1[0]][i] = 0

    if x_distance == 0:
        if y_distance > 0:
            for i in range(node1[0]+1, node1[0]+y_distance, 1):
                matrix[i][node1[1]] = 0
        if y_distance < 0:
            for i in range(node1[0]+y_distance+1, node1[0], 1):
                matrix[i][node1[1]] = 0

connect_nodes([1,0], [1,5])
connect_nodes([1,5], [5,5])

for m in matrix:
    print(m)

我得到两个坐标,它们是2D数组的两项。然后,我需要在2个给定的坐标之间画一条线-编辑特定行或列上项目的值。上面是我为解决此问题而编写的一些代码。但是我想知道是否有更优雅的方法可以做到这一点? 附言如果坐标不在同一条线上(垂直或水平)怎么办?如何在[1,1]和[9,3]之间画一条线?

1 个答案:

答案 0 :(得分:1)

您可以为此使用PIL:

from PIL import Image, ImageDraw
import numpy as np

matrix = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
                   [0, 1, 1, 1, 1, 0, 1, 1],
                   [1, 1, 1, 1, 1, 1, 1, 1],
                   [1, 1, 1, 1, 1, 1, 1, 1],
                   [1, 1, 1, 1, 1, 1, 1, 1],
                   [1, 1, 1, 1, 1, 0, 1, 1]])

# Load matrix into image
im = Image.fromarray(matrix, mode='I')

# Draw line from (1,1) to (9,3) with color 0
draw = ImageDraw.Draw(im)
draw.line((1, 1, 9,3), fill=0)

转换回numpy数组:

np.array(im)

>>> array([[1, 1, 1, 1, 1, 1, 1, 1],
           [0, 0, 0, 1, 1, 0, 1, 1],
           [1, 1, 1, 0, 0, 0, 0, 1],
           [1, 1, 1, 1, 1, 1, 1, 0],
           [1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 0, 1, 1]])

请注意,坐标是0索引的,所以左上角是(0,0)

了解更多:

https://pillow.readthedocs.io/en/3.0.x/reference/Image.html https://pillow.readthedocs.io/en/3.0.x/reference/ImageDraw.html