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?
ycoord, xcoord = numpy.mgrid[0:img.shape[0],0:img.shape[1]].pixel value, and itsx&ycoordinates. Reason I need that format specifically is because I need to then save it as a CSV file to have that specific data format/structure. You haveycoord,xcoordbut I need everything in one array output.for x in range(512): for y in range(512): csv.write(x, y, img[y,x]).array2 = np.array([[1,1,1], [2,2,2], [3,3,3]]) with open('csv_test.csv', 'w', newline='') as f: thewriter = csv.writer(f) thewriter.writerow(['x_coord', 'y_coord', 'pixel_value']) for y in np.nditer(array2): for x in np.nditer(y): thewriter.writerow([x, y, array2[y,x]]), but I got the error:index 3 is out of bounds for axis 0 with size 3. Not sure why is that? Isnp.nditerthe issue or is it something else?np.nditersteps through the flattened array, which is larger than one dimension. Also, your code doesn't not reflect what I wrote. I step through the dimensions (shape) of the array; you step through the array itself, and use the values inside the to index the array:for y in np.nditer(array2): ... array2[y,x]. That's not going to work (except in some very special cases).