SoFunction
Updated on 2024-10-29

python to batch split each image in a folder into multiple images

I. Up front

Requirements: there is a length of 960, width of 96 pictures, the need to split it into 10 96 * 96 pictures and stored in another folder, by hand split time-consuming and not standardized, choose python to write a simple program to complete.

II. Source code

# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 18:19:09 2018
@author: Administrator
"""
 
import os
from PIL import Image
 
# Cutting pictures
def splitimage(src, rownum, colnum, dstpath):
 img = (src)
 w, h = 
 if rownum <= h and colnum <= w:
 print('Original image info: %sx%s, %s, %s' % (w, h, , ))
 print('Picture cutting')
 
 s = (src)
 if dstpath == '':
  dstpath = s[0]
 fn = s[1].split('.')
 basename = fn[0]
 ext = fn[-1]
 
 num = 0
 rowheight = h // rownum
 colwidth = w // colnum
 for r in range(rownum):
  for c in range(colnum):
  box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
  (box).save((dstpath, basename + '_' + str(num) + '.' + ext), ext)
  num = num + 1
 
 print('A total of %s of small images were generated.' % num)
 else:
 print('error')
 
# Create folders
def mkdir(path):
 # Remove first space
 path = ()
 # Remove trailing \ symbol
 path = ("\\")
 
 # Determine if a path exists
 # Existing True
 # Not available False
 isExists = (path)
 
 # Judgment results
 if not isExists:
 (path)
 print (path+' Created successfully ')
 return True
 else:
 print (path + ' Catalog already exists ')
 return False
 
 
folder = r'C:/Users/Administrator/Desktop/testresults' # The folder where the pictures are stored
path = (folder)
# print(path)
 
for each_bmp in path: # Batch operations
 first_name, second_name = (each_bmp)
 each_bmp = (folder, each_bmp)
 src = each_bmp
 print(src)
 print(first_name)
 # Define the directory to be created
 mkpath = "C:/Users/Administrator/Desktop/results/"+ first_name
 # Calling functions
 mkdir(mkpath)
 if (src):
  dstpath = mkpath
  if (dstpath == '') or (dstpath):
  row = int(1) # of rows cut
  col = int(10) # of columns cut
  if row > 0 and col > 0:
   splitimage(src, row, col, dstpath)
  else:
   print('Invalid')
  else:
  print('Image save directory %s does not exist!' % dstpath)
 else:
  print('Image file %s does not exist!' % src)

III. Writing on the back

The number of cut rows and columns is defined here:

If you need to change the size of the image, you can simply use the resize() function in the PIL library with the following code:

from PIL import Image
 
for i in range(1,100):
 img = ("C:/Users/Administrator/Desktop/test_results/"+str(i)+".png")
 img = ("L")
 img = ((960,96))
 
 ("C:/Users/Administrator/Desktop/test_results/"+str(i)+".png", "PNG")

This is the whole content of this article.