Search code examples
pythonarraysnumpyenumerationnumpy-ndarray

Enumerate 2D array and append to new array


I'm trying to enumerate a 2D NumPy array of shape (512, 512) with pixel values, to output [y_index, x_index, pixel_value]. Output array should have shape (262144, 3): 262144 pixels from 512x512 matrix and 3 for columns pixel value, y coordinate and x coordinate.

I used ndenumerate but how to store values in an array? My attempt at last line is incorrect:

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 cores) takes 7-10 minutes. Is there a more efficient way?


Solution

  • The solution that worked for me is this:

    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})