如何将逗号分隔值放入 numpy 单元格

How to put a comma separated value to a numpy cell

我有坐标值类似于 (475224.0, 4186282.0) 的地理参考图像。我的图像尺寸是 (647, 2180)。即有 647 列和 2180 行。我想将坐标值放入一个大小为 (647, 2180) 的 numpy 数组中,这样我就可以将每个像素的坐标作为数组获取。我的代码如下。

rr = rasterio.open(fname) #fname is the georefered image
col = rr.width
row = rr.height
coord = np.empty(shape=(col,row),dtype=rr.dtypes[0])

for i in range(0,col):
    for j in range(0,row):
        coord[i,j] = rr.transform*(i,j)

问题是 rr.transform*(i,j) 会给出类似 (475224.0, 4186282.0) 的值。如何将其保存到单元格中。对于上面的程序,我收到如下错误

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 3, in coord[i,j] = rr.transform*(i,j) ValueError: setting an array element with a sequence.

假设您的 rr.transform*() 输出是有效的 Python tuple 我认为您这样做比必须的要复杂一些。默认情况下,numpy 将在创建 and/or 分配给 np.array:s 时处理相等的元组和列表。因此,一个更简单的解决方案就是添加一个额外的维度并直接分配您的值:

rr = rasterio.open(fname) #fname is the georefered image
col = rr.width
row = rr.height
coord = np.empty(shape=(col,row,2)

for i in range(0,col):
    for j in range(0,row):
        coord[i,j] = rr.transform*(i,j)

如您所见,唯一的区别是我添加了额外的维度以适应 rr 的大小。在这里,我将第三维硬编码为 2。有可能从 rr 对象中动态地找到它。在一般情况下,我们不限于 tuple 两个值。