【问题标题】:The same code is working outside a function, but not within a function相同的代码在函数外工作,但不在函数内
【发布时间】:2021-07-23 20:55:20
【问题描述】:

我有这个修改数组的功能:

import numpy as np
import skimage.draw as dw
import skimage.segmentation as seg

def draw_territories(map_file,system_list,color_dict):
    for size in range(0,120,1):
        for system in system_list:
            rr,cc = dw.circle_perimeter(system.x_coord,system.y_coord,size, method="andres", shape=(map_file.shape))
            map_file[rr,cc] = np.where(map_file[rr,cc]==(255,255,255),color_dict[system.owner_ID],map_file[rr,cc])

    ## This is where I want to add code ##

    borders = (seg.find_boundaries(map_file[:,:,0],mode='thick')) 
    map_file[borders] = 0
    return None

map_file 数组表示一个 4000x4000 的地图,第三维是 RGB 中的颜色。它通过在地图上占据的位置(来自system_list)周围绘制越来越大的彩色圆圈(通过循环)来工作,颜色取决于字典color_dict。然后它在领土周围绘制边界。所有这些都被证实有效。

我现在正在尝试在上述代码块中的哈希值处添加以下行。

    map_file = np.where(map_file==[254,254,254],[255,255,255],map_file)

[254,254,254] 是未占用点的替代颜色,我想在绘制边框之前将其恢复为背景白色。

由于某种原因,添加的行在函数中根本没有执行任何操作,并且以下两行也停止工作。然而,如果我在函数外部而不是函数内部运行它们,所有三个都按预期工作。为什么会发生这种情况,我应该如何解决?

【问题讨论】:

标签: python function scope numpy-ndarray scikit-image


【解决方案1】:

您正在分配给局部变量,而不是调用者的变量。

如果您想就地覆盖数组,请分配给map_file[...]

map_file[...] = np.where(map_file==[254,254,254],[255,255,255],map_file)

https://stackoverflow.com/a/48196246/1491895

但您可以改用return map_file 而不是return None。然后更改调用者以将结果分配给他们作为第一个参数传递的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2022-01-26
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多