3 回答
TA贡献1906条经验 获得超3个赞
这是一种方法 -
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.shape
out = np.empty((m,n,2+r), dtype=img.dtype)
out[:,:,0] = np.arange(m)[:,None]
out[:,:,1] = np.arange(n)
out[:,:,2:] = img
out = out.reshape(m*n,-1)
TA贡献1820条经验 获得超10个赞
这是一种使用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)
TA贡献1804条经验 获得超7个赞
只是为了获得时间:
import matplotlib.image as mpimg
import numpy as np
import pandas as pd
import time
t0 = 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.shape
out = np.empty((m,n,2+r), dtype=img.dtype)
out[:,:,0] = np.arange(m)[:,None]
out[:,:,1] = np.arange(n)
out[:,:,2:] = img
out = out.reshape(m*n,-1)
print(time.time() - t0)
0.17211008071899414
0.001434326171875
0.0013523101806640625
0.0008423328399658203
最后一个变体似乎是最快的。
添加回答
举报