Edayildiz
Edayildiz

Reputation: 555

How to concatenate 1000 images vertically using for loop in python?

I want to concatenate vertically a lot of images. I used skimage to read images then in each iteration io read image and vconcat concatenate the new image on the old image vertically. The result of my code didn't concatenate the images, just combine the images. Any ideas how to make each image in each iteration concatenate vertically on each other?

I want to concatenate the first image and the second image vertically:

fist image

second image

but I got this result:

result

enter image description here

data = []
if nSpectogram < 3765:
    for k in range(0, 21):
        path = io.imread('E:\\wavelet\\spectrograms\\paz05\\'+'spec_'+isPreictal+'_'+str(nSpectogram+1)+'_'+str(k+1)+'.png')
        im_v_array = np.array(im_v)
        data.append(path)
    res = np.concatenate(data)
    plt.imshow(res, cmap='inferno', aspect='auto', interpolation='nearest')

Upvotes: 6

Views: 3734

Answers (2)

Parfait
Parfait

Reputation: 107577

Instead of skimage.io (which may be due to a version or CPU issue), consider using matplotlib.pyplot.imread with list comprehension or map. Below demonstrates with OP's two images.

import numpy as np
import matplotlib.pyplot as plt

img_paths = ["OP_Image_1.png", "OP_Image_2.png"]

data = [plt.imread(img) for img in img_paths]
# data = list(map(mpimg.imread, img_paths))

res = np.concatenate(data)
plt.imshow(res, cmap='inferno', aspect='auto', interpolation='nearest')

plt.axis('off')
plt.show()

Plot Output


Specifically, for OP's iteration of files:

import os
import numpy as np
import matplotlib.pyplot as plt

...
spec_path = r"E:\wavelet\spectrograms\paz05"                     # RAW STRING FOR BACKSLASHES
spec_file = f"spec_{isPreictal}_{str(nSpectogram+1)}_{{}}.png"   # F STRING FOR INTERPOLATION

if nSpectogram <3765:
   data = [plt.imread(os.path.join(spec_path, spec_file.format(k+1))) for k in range(21)]

   res = np.concatenate(data)
   plt.imshow(res, cmap='inferno', aspect='auto', interpolation='nearest')
   
   plt.axis('off')
   plt.savefig(os.path.join(spec_path, "Output.png"))

Upvotes: 2

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

merged_img = []
for i in range(3):
    img = io.imread('https://machinelearningblogs.com/wp-content/uploads/2018/03/849825_XL-830x400.jpg')
    merged_img.append(img)

merge = np.concatenate(merged_img)

plt.imshow(merge)

enter image description here

Just add all the images to a list in the for loop after reading them and pass the list to np.concatenate

Upvotes: 6

Related Questions