I want to create 200 image frames of size (100*100) and stack them in a 3-D array with final size(200 * 100 *100) where x axis represent each frame ie, (1, 100, 100) should be the first frame.
I am not able to stack them in a 3-D array. The first loop does create a (2,100,100) array by stacking the first two frames but does not work after that and results in a (2,) array
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
I need a (200,100,100)
You can use numpy.stack
for doing this. See my example
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])
output of 2nd print
[[1 2]
[3 4]]
output of 3rd print
[[10 11]
[12 13]]
Note that you have to feed tuple
of 2D arrays into numpy.stack
rather than individual 2D arrays
You can initialize an array and then fill it with the images. This tends to be more efficient than continuously stacking.
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
One approach would be to create a list of the 2-d matrices you want to stack and use np.stack(arrays, axis=0)
Example
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.