[英]Concatenate numpy arrays in for loop
我已將一幅圖像分為16個圖形以繪制回歸,現在我想將其重新合並為一個圖像。
我已經編寫了一個for循環來執行此操作,但是我無法理解先前問題的建議以及我要去哪里。 請有人解釋為什么我的輸入數組沒有相同數量的維。
from scipy import interpolate
allArrays = np.array([])
for i in range(len(a)):
fig = plt.figure()
ax = fig.add_axes([0.,0.,1.,1.])
if np.amax(a[i]) > 0:
x, y = np.where(a[i]>0)
f = interpolate.interp1d(y, x)
xnew = np.linspace(min(y), max(y), num=40)
ynew = f(xnew)
plt.plot(xnew, ynew, '-')
plt.ylim(256, 0)
plt.xlim(0,256)
fig.canvas.draw()
X = np.array(fig.canvas.renderer._renderer)
myArray = color.rgb2gray(X)
print(myArray.shape)
allArrays = np.concatenate([allArrays, myArray])
print(allArrays.shape)
else:
plt.xlim(0,256)
plt.ylim(0,256)
fig.canvas.draw()
X = np.array(fig.canvas.renderer._renderer)
myArray = color.rgb2gray(X)
print(myArray.shape)
allArrays = np.concatenate([allArrays, myArray])
print(allArrays.shape)
i += 1
輸出:myArray.shape(480,640)
錯誤消息:所有輸入數組必須具有相同的維數
我敢肯定這確實很簡單,但我無法弄清楚。 謝謝。
In [226]: allArrays = np.array([])
In [227]: allArrays.shape
Out[227]: (0,)
In [228]: allArrays.ndim
Out[228]: 1
In [229]: myArray=np.ones((480,640))
In [230]: myArray.shape
Out[230]: (480, 640)
In [231]: myArray.ndim
Out[231]: 2
在大多數情況下,1不等於2!
要在默認軸0上與myArray
串聯, allArrays
必須以np.zeros((0,640), myArray.dtype)
。 在n
次迭代之后,它將增長到(n*480, 640)
。
在鏈接的答案中,新數組均為1d,因此以形狀(0,)
開頭是可以的。 但是wim's
答案更好-將所有數組收集在一個列表中,並在最后進行一個連接。
循環中的重復連接很難正確處理(您必須了解形狀和尺寸),並且比列表追加要慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.