numpy 枚举2D数组并追加到新数组

cclgggtu  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(67)

我试图枚举一个2D NumPy数组的形状(512,512)与像素值,以输出[y_index, x_index, pixel_value]。输出数组应具有以下形状(262144,3):262144个像素来自512 x512矩阵,3个像素用于列pixel valuey coordinatex coordinate
我使用ndenumerate,但如何在数组中存储值?我最后一行的尝试是不正确的:

img = as_np_array[:, :, 0]
img = img.reshape(512, 512)
coordinates = np.empty([262,144, 3])
for index, x in np.ndenumerate(img):
    coordinates = np.append(coordinates, [[x], index[0], index[1]])

Intel Core i7 2.7GHz(4核心)需要7-10分钟。有没有更有效的方法?

fgw7neuy

fgw7neuy1#

你可以使用numpy.indices来实现。你最终想要的是image_datayx索引和相应的像素(px)。在image_data中有三列。

row, col = np.indices(img.shape)
y, x, px = row.flatten(), col.flatten(), img.flatten()
image_data = np.array([y, x, px]).T

详细示例:

img = np.arange(20).reshape(5, 4)

def process_image_data(img):
    row, col = np.indices(img.shape)
    return (row.flatten(), col.flatten(), img.flatten())

y, x, px = process_image_data(img)
yc0p9oo0

yc0p9oo02#

对我有效的解决方案是这样的:

with open('img_pixel_coor1.csv', 'w', newline='') as f:
    headernames = ['y_coord', 'x_coord', 'pixel_value']
    thewriter = csv.DictWriter(f, fieldnames=headernames)
    thewriter.writeheader()     
    for index, pix in np.ndenumerate(img):
        thewriter.writerow({'y_coord' : index[0], 'x_coord' : index[1], 'pixel_value' : pix})

相关问题