SoFunction
Updated on 2024-11-19

python implement batch processing to paste an image to another image and save it

pillow is really a powerful image processing library !!!!

I have used the pillow library to implement a batch of photos from a folder to be randomly pasted onto another image and batch saved to a specified folder!!!!

Straight to the code:

from PIL import Image
import os
import random
 
 
def handle_img(imgdir,imgFlodName):
 imgs = (imgdir+imgFlodName)
 imgNum = len(imgs)
 print(imgNum)
 
 for i in range(imgNum):
  img1 = (imgdir + imgFlodName + "/" + imgs[i])
  img = ((102,102)) # Resize images to the right size
 
  oriImg = ("F:/Download/") #Open the picture
  image =  # Get image size dimensions
  # (img, (image[0]-102, image[1]-102))
 
  if image[0]<image[1]: # Determine the width and height because if left untouched, it may dip outside of the image when pasted to a random location.
   (img,((0,image[0]-102),(0,image[0]-102)))
  else:
   (img, ((0, image[1]-102), (0, image[1]-102)))
  ()
  oriImg1 = ('RGB')
  ("F:/Download/sign_data"+"/"+str(i)+".jpg")
 
 
imgdir = "F:/Download/" 
imgFlodName = "v2.0sign_picture" 
handle_img(imgdir,imgFlodName)

Next, implement pasting a random set of images under a folder onto a set of images under another folder and save it!!!! It's really just a matter of adding another for loop!!!!

Straight to the code:

from PIL import Image
import os
import random
 
 
def handle_img(imgdir,imgFlodName,img_path):
 imgs = (imgdir+imgFlodName)
 imgNum = len(imgs)
 print(imgNum)
 image_ori = (img_path)
 image_Num = len(image_ori)
 print(image_Num)
 
 for i in range(imgNum):
  img1 = (imgdir + imgFlodName + "/" + imgs[i])
  img = ((102,102))
 
  for j in range(image_Num):
 
   oriImg = (img_path + "/" + image_ori[j])
   image = 
   # (img, (image[0]-102, image[1]-102))
 
   if image[0]<image[1]:
    (img,((0,image[0]-102),(0,image[0]-102)))
   else:
    (img, ((0, image[1]-102), (0, image[1]-102)))
   ()
   oriImg1 = ('RGB')
   ("F:/Download/sign2_data"+"/"+str(i)+".jpg")
 
 
imgdir = "F:/Download/"
imgFlodName = "v2.0sign_picture"
image_path = "F:/Download/image"
handle_img(imgdir,imgFlodName,image_path)

Above this python implementation of batch processing to paste the image to another image and save is all I have shared with you, I hope to give you a reference, and I hope you support me more.