Search code examples
pythonimageconcatenationscikit-image

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')

Solution

  • 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"))