我想创建200个大小为(100 * 100)的图像帧,并将它们堆叠在最终大小为(200 * 100 * 100)的3-D数组中,其中x轴表示每个帧,即(1,100,100 )应该是第一帧。
我无法将它们堆叠为3-D阵列。第一个循环通过堆叠前两帧创建了一个(2,100,100)数组,但此后不起作用,并导致了一个(2,)数组
import numpy as np
import random
def createCircle(width,height , rad ):
w = random.randint(1, height)
h = random.randint(1, height)
center = [int(w), int(h)]
radius = rad
Y, X = np.ogrid[:height, :width]
dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
mask = dist_from_center <= radius
return mask
def addCircle(test_image):
m = createCircle(width = 100, height = 100 , rad = 8 )
masked_img = test_image.copy()
masked_img[m] = 0
return masked_img
img = np.zeros([100,100],dtype=np.uint8)
img.fill(20)
img_test = img
def noise(image):
row,col= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col))
gauss = gauss.reshape(row,col)
noisy = image + gauss #adding gauss noise
s1 = np.sin(8) #adding sin fill
noisy += s1
return noisy
#creates 1st frame
for i in range(4):
im_first = addCircle(test_image=img_test)
im_first = noise(im_first)
for i in range(200):
for j in range(4):
img_test = addCircle(test_image=img_test)
im1 = noise(img_test)
img_test = img
im_first = np.array([im_first, im1])#stacks every new frame (im1)#error in this
我需要一个(200,100,100)
答案 0 :(得分:0)
您可以使用numpy.stack
进行此操作。看看我的例子
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[10,11],[12,13]])
c = np.stack((a,b))
print(c.shape) #prints (2,2,2)
print(c[0])
print(c[1])
第二张打印输出
[[1 2]
[3 4]]
第三次打印的输出
[[10 11]
[12 13]]
请注意,您必须将tuple
个2D数组而不是单个2D数组馈入numpy.stack
答案 1 :(得分:0)
您可以初始化一个数组,然后用图像填充它。这往往比连续堆叠更有效率。
ims = np.zeros((200, 100, 100)) # initialize your array
for i in range(200):
for j in range(4):
img_test = addCircle(test_image=img_test)
im1 = noise(img_test)
ims[i, ...] = im1 # add the image to our initialized array
答案 2 :(得分:0)
一种方法是创建要堆叠并使用arrays = [np.random.randn(100, 100) for _ in range(200)] #each matrix is of shape (100,100)
stacked_array = np.stack(arrays, axis=0) #stacked_array.shape is (200,100,100)
的二维矩阵的列表。
示例
{{1}}