Reputation: 425
I'm trying to save in python a stack of 10 rgb images, but i get the following error:
rgb[:,:,:, i] = img
ValueError: could not broadcast input array from shape (256,340,3) into shape (256,340,30)
I tried:
img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
rgb[:,:,:, i] = img
I also tried:
chunks = 10
step = int(math.floor((duration - chunks + 1)/(num_samples)))
dims = (256, 340, chunks * 3, num_samples)
rgb = np.zeros(shape=dims, dtype=np.float64)
for i in range(num_samples):
for j in range(chunks):
img_file = os.path.join(vid_name, 'image_{0:04d}.jpg'.format(i*step+j+1 + start_frame))
img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
img = cv2.resize(img, dims[1::-1])
rgb[:,:,(j+1)*3, i] = img
img_file keeps the path to the image, it gets it correct. I've tested it with
print("%r") % img_file
What I want to achive is 10 stacked rgb images.
Any help is appreciated. Thank you!
Upvotes: 0
Views: 2131
Reputation: 221514
Approach #1 : To make things simpler, I would suggest initializing a 5D
array instead by splitting the second last axis into two axes, keeping chunks
and 3
along them, like so -
dims = (256, 340, chunks , 3, num_samples)
To compensate for this edit, we need to make the assigning part of image into the output array inside the nested loops, like so -
rgb[:,:,j, :, i] = img
After performing all of those operations, at the end if needed, just reshape into 4D
array -
rgb.shape = (256, 340, chunks* 3, num_samples)
So, in all three edits needed.
Approach #2 : Keeping the loopy code from the question as it is, we could just do -
rgb[:,:,j*3:(j+1)*3, i] = img
Upvotes: 1