├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── bridge.jpg ├── cat.jpg ├── pyproject.toml ├── setup.py └── src └── split_image ├── __init__.py └── split.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | src/.DS_Store 132 | .DS_Store -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [2.0.1] 2 | * Fixed an issue with calculating the row and column width when the image has been resized to a square first. 3 | 4 | ## [2.0.0] 5 | * [BREAKING] Swapped the rows and cols argument bindings in the script, as they were previously set incorrectly. Now `split-image test.jpg 3 2` will split the image into 3 rows and 2 columns (it previously split it into 3 columns and two rows). You may need to change your script arguments. 6 | * Added the ability to batch process whole directories with images. Usage: `split-image image_dir 2 2` will split all images inside the `image_dir` folder. Closes #3. 7 | * Fixed an issue with the image path name when it came from a directory. 8 | 9 | ## [1.7.0] 10 | * Added the ability to set a `quiet` flag (`--quiet`), that will suppress all log messages (except errors and warnings) when running. 11 | 12 | ## [1.6.0] 13 | * Can now import the package in your Python scripts with an import like `from split_image import split_image`. 14 | * Fixed an issue with exporting squared (resized) JPG images. 15 | * Refactored the `split` process to `split_image`. 16 | 17 | ## [1.5.1] 18 | * Improved importing process for package 19 | 20 | ## [1.5.0] 21 | * Added the ability to set a custom output directory for the image tiles. Usage: `split-image test.jpg 2 2 --output-dir ` 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Minas Giannekas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # split-image 2 | 3 | [![Downloads](https://static.pepy.tech/personalized-badge/split-image?period=total&units=international_system&left_color=blue&right_color=orange&left_text=Downloads)](https://pepy.tech/project/split-image) [![Downloads](https://static.pepy.tech/personalized-badge/split-image?period=month&units=international_system&left_color=blue&right_color=yellow&left_text=Downloads%20per%20month)](https://pepy.tech/project/split-image) 4 | 5 | ## Quickly split an image into rows and columns (tiles). 6 | 7 | [split-image](https://pypi.org/project/split-image/) is a Python package that you can use from the command line to split an image into tiles. 8 | 9 |

10 | 11 |

12 | 13 | ## Installation 14 | 15 | 16 | `pip install split-image` 17 | 18 | ## Usage 19 | 20 | From the command line: 21 | 22 | ``` 23 | split-image [-h] [-s] image_path rows cols 24 | ``` 25 | 26 | As a regular module import: 27 | 28 | ```python 29 | from split_image import split_image 30 | 31 | split_image(image_path, rows, cols, should_square, should_cleanup, [output_dir]) 32 | # e.g. split_image("bridge.jpg", 2, 2, True, False) 33 | 34 | ``` 35 | 36 | 37 |

38 | 39 |

40 | 41 | ### Basic examples 42 | 43 | `split-image cat.png 2 2` 44 | 45 | This splits the `cat.png` image in 4 tiles (`2` rows and `2` columns). 46 | 47 |

48 | 49 |

50 | 51 | `split-image bridge.png 3 4 -s` 52 | 53 | This splits the `bridge.png` image in 12 tiles (`3` rows and `4` columns). The `-square` arguments resizes the image into a square before splitting it. The background color used to fill the square is determined from the image automatically. 54 | 55 |

56 | 57 |

58 | 59 | ### Other options 60 | 61 | #### Reverse split: 62 | 63 | `split-image cat.jpg 2 2 -r` 64 | 65 | Will attempt to merge similarly named image tiles to one image. So, if you have these images in the current directory: 66 | 67 | * `cat_0.jpg` 68 | * `cat_1.jpg` 69 | * `cat_2.jpg` 70 | * `cat_3.jpg` 71 | 72 | they will be merged according to their file name: 73 | 74 |

75 | 76 |

77 | 78 | #### Directory batch process: 79 | 80 | `split-image image_dir 4 2` 81 | 82 | Will split all images contained in the `image_dir` folder. 83 | 84 | #### Cleanup: 85 | 86 | `split-image test.jpg 4 2 --cleanup` 87 | 88 | Will delete the original image after the process. 89 | 90 | #### Large images: 91 | 92 | `split-image test.jpg 4 2 --load-large-images` 93 | 94 | When working with large images (over 178,956,970 pixels), you may get an error. Pass this flag to override this. 95 | 96 | #### Assign output folder: 97 | 98 | `split-image test.jpg 2 2 --output-dir ` 99 | 100 | Set the output directory for image tiles (e.g. 'outp/images'). Defaults to the current working directory. 101 | 102 | #### Quiet mode: 103 | 104 | `split-image test.jpg 3 4 --quiet` 105 | 106 | Will suppress all log messages (except errors and warnings) when running. 107 | 108 | ### Arguments list: 109 | 110 | ``` 111 | 112 | positional arguments: 113 | image_path The path to the image or directory with images to split. 114 | rows How many rows to split the image into (horizontal split). 115 | cols How many columns to split the image into (vertical split). 116 | 117 | optional arguments: 118 | -h, --help Show this help message and exit 119 | -s, --square If the image should be resized into a square before splitting. 120 | -r, --reverse Reverse the splitting process, i.e. merge multiple tiles of an image into one. 121 | --cleanup After splitting or merging, delete the original image/images. 122 | --load-large-images Pass this flag for use with really large images. 123 | --output-dir Set the output directory for image tiles (e.g. 'outp/images'). 124 | --quiet Run without printing any messages. 125 | ``` 126 | 127 | Cat photo by Manja Vitolic on Unsplash 128 | 129 | Bridge photo by Lance Asper on Unsplash 130 | 131 | 132 | -------------------------------------------------------------------------------- /bridge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whiplashoo/split-image/23d445bb94759ff2da49c6828945a794dabe6fef/bridge.jpg -------------------------------------------------------------------------------- /cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/whiplashoo/split-image/23d445bb94759ff2da49c6828945a794dabe6fef/cat.jpg -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r", encoding="utf-8") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="split-image", 8 | version="2.0.1", 9 | author="Minas Giannekas", 10 | author_email="contact@whidev.com", 11 | description="A package that lets you quickly split an image into rows and columns (tiles).", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/whiplashoo/split-image", 15 | project_urls={ 16 | "Bug Tracker": "https://github.com/whiplashoo/split-image/issues", 17 | }, 18 | entry_points=""" 19 | [console_scripts] 20 | split-image = split_image.split:main 21 | """, 22 | classifiers=[ 23 | "Programming Language :: Python :: 3", 24 | "License :: OSI Approved :: MIT License", 25 | "Operating System :: OS Independent", 26 | ], 27 | install_requires=[ 28 | 'Pillow', 29 | ], 30 | package_dir={"": "src"}, 31 | packages=setuptools.find_packages(where="src"), 32 | python_requires=">=3.6", 33 | ) 34 | -------------------------------------------------------------------------------- /src/split_image/__init__.py: -------------------------------------------------------------------------------- 1 | from .split import split_image, reverse_split -------------------------------------------------------------------------------- /src/split_image/split.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/env python 2 | import argparse 3 | import os 4 | import re 5 | from collections import Counter 6 | 7 | from PIL import Image 8 | 9 | 10 | def split_image(image_path, rows, cols, should_square, should_cleanup, should_quiet=False, output_dir=None): 11 | im = Image.open(image_path) 12 | im_width, im_height = im.size 13 | row_width = int(im_width / cols) 14 | row_height = int(im_height / rows) 15 | name, ext = os.path.splitext(image_path) 16 | name = os.path.basename(name) 17 | if output_dir != None: 18 | if not os.path.exists(output_dir): 19 | os.makedirs(output_dir) 20 | else: 21 | output_dir = "./" 22 | if should_square: 23 | min_dimension = min(im_width, im_height) 24 | max_dimension = max(im_width, im_height) 25 | if not should_quiet: 26 | print("Resizing image to a square...") 27 | print("Determining background color...") 28 | bg_color = determine_bg_color(im) 29 | if not should_quiet: 30 | print("Background color is... " + str(bg_color)) 31 | im_r = Image.new("RGBA" if ext == "png" else "RGB", 32 | (max_dimension, max_dimension), bg_color) 33 | offset = int((max_dimension - min_dimension) / 2) 34 | if im_width > im_height: 35 | im_r.paste(im, (0, offset)) 36 | else: 37 | im_r.paste(im, (offset, 0)) 38 | if not should_quiet: 39 | print("Exporting resized image...") 40 | outp_path = name + "_squared" + ext 41 | outp_path = os.path.join(output_dir, outp_path) 42 | im_r.save(outp_path) 43 | im = im_r 44 | row_width = int(max_dimension / cols) 45 | row_height = int(max_dimension / rows) 46 | n = 0 47 | for i in range(0, rows): 48 | for j in range(0, cols): 49 | box = (j * row_width, i * row_height, j * row_width + 50 | row_width, i * row_height + row_height) 51 | outp = im.crop(box) 52 | outp_path = name + "_" + str(n) + ext 53 | outp_path = os.path.join(output_dir, outp_path) 54 | if not should_quiet: 55 | print("Exporting image tile: " + outp_path) 56 | outp.save(outp_path) 57 | n += 1 58 | if should_cleanup: 59 | if not should_quiet: 60 | print("Cleaning up: " + image_path) 61 | os.remove(image_path) 62 | 63 | 64 | def reverse_split(paths_to_merge, rows, cols, image_path, should_cleanup, should_quiet=False): 65 | if len(paths_to_merge) == 0: 66 | print("No images to merge!") 67 | return 68 | for index, path in enumerate(paths_to_merge): 69 | path_number = int(path.split("_")[-1].split(".")[0]) 70 | if path_number != index: 71 | print("Warning: Image " + path + 72 | " has a number that does not match its index!") 73 | print("Please rename it first to match the rest of the images.") 74 | return 75 | images_to_merge = [Image.open(p) for p in paths_to_merge] 76 | image1 = images_to_merge[0] 77 | new_width = image1.size[0] * cols 78 | new_height = image1.size[1] * rows 79 | print(paths_to_merge) 80 | new_image = Image.new(image1.mode, (new_width, new_height)) 81 | if not should_quiet: 82 | print("Merging image tiles with the following layout:", end=" ") 83 | for i in range(0, rows): 84 | print("\n") 85 | for j in range(0, cols): 86 | print(paths_to_merge[i * cols + j], end=" ") 87 | print("\n") 88 | for i in range(0, rows): 89 | for j in range(0, cols): 90 | image = images_to_merge[i * cols + j] 91 | new_image.paste(image, (j * image.size[0], i * image.size[1])) 92 | if not should_quiet: 93 | print("Saving merged image: " + image_path) 94 | new_image.save(image_path) 95 | if should_cleanup: 96 | for p in paths_to_merge: 97 | if not should_quiet: 98 | print("Cleaning up: " + p) 99 | os.remove(p) 100 | 101 | 102 | def determine_bg_color(im): 103 | im_width, im_height = im.size 104 | rgb_im = im.convert('RGBA') 105 | all_colors = [] 106 | areas = [[(0, 0), (im_width, im_height / 10)], 107 | [(0, 0), (im_width / 10, im_height)], 108 | [(im_width * 9 / 10, 0), (im_width, im_height)], 109 | [(0, im_height * 9 / 10), (im_width, im_height)]] 110 | for area in areas: 111 | start = area[0] 112 | end = area[1] 113 | for x in range(int(start[0]), int(end[0])): 114 | for y in range(int(start[1]), int(end[1])): 115 | pix = rgb_im.getpixel((x, y)) 116 | all_colors.append(pix) 117 | return Counter(all_colors).most_common(1)[0][0] 118 | 119 | 120 | def main(): 121 | parser = argparse.ArgumentParser( 122 | description="Split an image into rows and columns.") 123 | parser.add_argument("image_path", nargs=1, 124 | help="The path to the image or directory with images to process.") 125 | parser.add_argument("rows", type=int, default=2, nargs='?', 126 | help="How many rows to split the image into (horizontal split).") 127 | parser.add_argument("cols", type=int, default=2, nargs='?', 128 | help="How many columns to split the image into (vertical split).") 129 | parser.add_argument("-s", "--square", action="store_true", 130 | help="If the image should be resized into a square before splitting.") 131 | parser.add_argument("-r", "--reverse", action="store_true", 132 | help="Reverse the splitting process, i.e. merge multiple tiles of an image into one.") 133 | parser.add_argument("--cleanup", action="store_true", 134 | help="After splitting or merging, delete the original image/images.") 135 | parser.add_argument("--load-large-images", action="store_true", 136 | help="Ignore the PIL decompression bomb protection and load all large files.") 137 | parser.add_argument("--output-dir", type=str, 138 | help="Set the output directory for image tiles (e.g. 'outp/images'). Defaults to current working directory.") 139 | parser.add_argument("--quiet", action="store_true", 140 | help="Run without printing any messages.") 141 | 142 | args = parser.parse_args() 143 | if args.load_large_images: 144 | Image.MAX_IMAGE_PIXELS = None 145 | image_path = args.image_path[0] 146 | if not os.path.exists(image_path): 147 | print("Error: Image path does not exist!") 148 | return 149 | if os.path.isdir(image_path): 150 | if args.reverse: 151 | print("Error: Cannot reverse split a directory of images!") 152 | return 153 | if not args.quiet: 154 | print("Splitting all images in directory: " + image_path) 155 | for file in os.listdir(image_path): 156 | if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png"): 157 | split_image(os.path.join(image_path, file), args.rows, args.cols, 158 | args.square, args.cleanup, args.quiet, args.output_dir) 159 | else: 160 | if args.reverse: 161 | if not args.quiet: 162 | print( 163 | "Reverse mode selected! Will try to merge multiple tiles of an image into one.\n") 164 | start_name, ext = os.path.splitext(image_path) 165 | # Find all files that start with the same name as the image, 166 | # followed by "_" and a number, and with the same file extension. 167 | expr = re.compile(r"^" + start_name + "_\d+" + ext + "$") 168 | paths_to_merge = sorted([f for f in os.listdir( 169 | os.getcwd()) if re.match(expr, f)], key=lambda x: int(x.split("_")[-1].split(".")[0])) 170 | reverse_split(paths_to_merge, args.rows, 171 | args.cols, image_path, args.cleanup, args.quiet) 172 | else: 173 | split_image(image_path, args.rows, args.cols, 174 | args.square, args.cleanup, args.quiet, args.output_dir) 175 | if not args.quiet: 176 | print("Done!") 177 | 178 | 179 | if __name__ == "__main__": 180 | main() 181 | --------------------------------------------------------------------------------