-
一只名叫tom的猫
这是一种方法 -m,n = img.shape[:2]r,c = np.mgrid[:m,:n]out = np.column_stack((r.ravel(), c.ravel(), img.reshape(-1,img.shape[2])))替代获得r,c:r,c = np.indices(img.shape[:2])另一个带有数组分配的 -m,n,r = img.shapeout = np.empty((m,n,2+r), dtype=img.dtype)out[:,:,0] = np.arange(m)[:,None]out[:,:,1] = np.arange(n)out[:,:,2:] = imgout = out.reshape(m*n,-1)
-
拉莫斯之舞
这是一种使用np.indices,转置以匹配您的循环并重新整形以获得二维数组的方法。ix = np.transpose(np.indices(img.shape[:2]), (1,2,0))image = np.concatenate((ix, img), axis=2).reshape(-1, image.shape[2] + 2)
-
三国纷争
只是为了获得时间:import matplotlib.image as mpimgimport numpy as npimport pandas as pdimport timet0 = time.time()image_orig = []for i in range(img.shape[0]): for j in range(img.shape[1]): image_orig.append([i, j] + img[i, j].tolist())image_orig = np.array(image_orig)print(time.time() - t0)t0 = time.time()ix = np.transpose(np.indices(img.shape[:2]), (1,2,0))image = np.concatenate((ix, img), axis=2).reshape(-1, img.shape[2] + 2)print(time.time() - t0)t0 = time.time()m,n = img.shape[:2]r,c = np.indices(img.shape[:2])out = np.column_stack((r.ravel(), c.ravel(), img.reshape(-1,img.shape[2])))print(time.time() - t0)t0 = time.time()m,n,r = img.shapeout = np.empty((m,n,2+r), dtype=img.dtype)out[:,:,0] = np.arange(m)[:,None]out[:,:,1] = np.arange(n)out[:,:,2:] = imgout = out.reshape(m*n,-1)print(time.time() - t0)0.172110080718994140.0014343261718750.00135231018066406250.0008423328399658203最后一个变体似乎是最快的。