I have a folder which has multiple images lets say images names are----
AB_1.jpg,
AB_2.jpg,
AB_3.jpg,
AB_4.jpg,
AB_5.jpg,
AB_6.jpg,
AB_7.jpg,
AB_8.jpg,
BC_1.jpg,
BC_2.jpg,
BC_3.jpg,
CA_1.jpg,
CA_2.jpg
Here my objective is to concatenate all the images till _5 or less than _5 as one image....
So basically what I am saying is that---
AB_1.jpg,
AB_2.jpg,
AB_3.jpg,
AB_4.jpg,
AB_5.jpg
will get concatenated vertically and file name lets say will be AB_Concat.jpg
_6,_7,_8 are skipped because we want to concatenate only images till _5 as one....
Similarly,,
BC_1.jpg,
BC_2.jpg,
BC_3.jpg
will get concatenated vertically and file name lets say will be BC_Concat.jpg as you can see here BC_3 is last one which is less than _5 so all will be concatenated vertically.....
So if anyone have any idea on how to achieve the same please help....
This question is not similar to the once where two images are concatenated since here we are concatenating images on the basis of value after underscore in a image....
This is something which I tried---
import cv2
import shutil
import numpy as np
import os
from PIL import Image
path = r"D:split"
out = r"D:concat_test"
os.makedirs(out,exist_ok=True)
imag_name =[]
imag_name1 = []
for img in os.listdir(path):
folder = img.rsplit("_",1)[0]
imag_name1.append((folder,img))
images = cv2.imread(os.path.join(path,img),0)
imag_name.append((folder,images))
# to create a folder for multiple images contain same name
for image,name in zip(imag_name,imag_name1):
if image[0] == name[0]:
folder_n = os.path.join(out,name[0])
final_fldr = os.path.join(folder_n,name[1])
os.makedirs(folder_n,exist_ok=True)
cv2.imwrite(final_fldr,image[1])
# to concatinate the images
for root,dirs,files in os.walk(out):
np_images = [cv2.imread(os.path.join(root,file),0) for file in files]
np_name = list(set([file.rsplit("_",1)[0] for file in files]))
if len(np_images) != 0:
print(np_name)
concat = cv2.vconcat(np_images)
concatinated_images = os.path.join(out,"concatinated_images")
os.makedirs(concatinated_images,exist_ok=True)
cv2.imwrite(os.path.join(concatinated_images,*np_name)+".tif",concat)
#to remove the unwanted folder
for remove_folder in os.listdir(out):
if remove_folder != "concatinated_images":
folders_to_remove = os.path.join(out,remove_folder)
shutil.rmtree(folders_to_remove)
'''
See Question&Answers more detail:
os