├── .gitignore ├── LICENSE ├── README.md ├── screenshot_1.png ├── screenshot_2.png └── scripts ├── crop_utils.py ├── ei_utils.py ├── enhanced_img2img.py └── multi_frame_rendering.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Image Sequence Toolkit 2 | 3 | This is an extension for [AUTOMATIC111's WebUI](https://github.com/AUTOMATIC1111/stable-diffusion-webui), which supports batch processing and better inpainting. 4 | 5 | ## Install 6 | 7 | Please refer to the [official wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Extensions) for installation instructions. 8 | 9 | ## Usage 10 | 11 | ### Enhanced img2img 12 | 13 | To use Enhanced img2img, switch to the **"img2img"** tab and select **"enhanced img2img"** under the **"script"** column. 14 | 15 | ![](screenshot_1.png) 16 | 17 | - **Input directory**: The folder that contains all the images you want to process. 18 | - **Output directory**: The folder where you want to save the output images. 19 | - **Mask directory**: The folder containing all the masks. This is not essential. 20 | - **Use input image's alpha channel as mask**: If your original images are in PNG format with transparent backgrounds, you can use this option to create outputs with transparent backgrounds. Note: when this option is selected, the masks in the "**mask directory**" will not be used. 21 | - **Use another image as mask**: Use masks in the "**mask directory**" to inpaint images. Note: if the relevant masks are blank images or no mask is provided, the original images will not be processed. 22 | - **Use mask as output alpha channel**: Add the mask as an output alpha channel. Note: when the "**use input image's alpha channel as mask**" option is selected, this option is automatically activated. 23 | - **Zoom in masked area**: crop and resize the masked area to square images; this will give better results when the masked area is relatively small compared to the original images. 24 | - **Alpha threshold**: The alpha value to determine background and foreground. 25 | - **Rotate images (clockwise)**: This can improve AI's performance when the original images are upside down. 26 | - **Process given file(s) under the input folder, separated by comma**: Process certain image(s) from the text box to the right to it. If this option is not checked, all the images under the folder will be processed. 27 | - **Files to process**: Filenames of the images you want to process. It is recommended to name your images with a digit suffix (e.g. `000233.png, 000234.png, 000235.png, ...` or `image_233.jpg, image_234.jpg, image_235.jpg, ...`). This way, you can use `233,234,235` or simply `233-235` to assign these files. Otherwise, you need to give the full filenames like `image_a.webp,image_b.webp,image_c.webp`. 28 | - **Use deepbooru prompt**: Use DeepDanbooru to predict image tags. If you have input some prompts in the prompt area, it will append to the end of the prompts. 29 | - **Using contextual information**: This can improve accuracy (maybe) if tags are present in both current and next frames' prediction results. 30 | - **Loopback**: Similar to the loopback script, this will run input images img2img twice to enhance AI's creativity. 31 | - **Firstpass width** and **firstpass height**: AI tends to be more creative when the firstpass size is smaller. 32 | - **Denoising strength**: The denoising strength for the first pass. It's better to keep it no higher than 0.4. 33 | - **Read tags from text files**: This will read tags from text files with the same filename as the current input image. 34 | - **Text files directory**: Optional. It will load from the input directory if not specified. 35 | - **Use csv prompt list** and **input file path**: Use a `.csv` file as prompts for each image. One line for one image. 36 | 37 | ### Multi-frame rendering 38 | 39 | To use Multi-frame rendering, switch to the **"img2img"** tab and select **"multi-frame rendering"** under the **"script"** column. This should be used with ControlNet. For more information, see [the original post](https://xanthius.itch.io/multi-frame-rendering-for-stablediffusion). 40 | 41 | ![](screenshot_2.png) 42 | 43 | - **Input directory**: The folder that contains all the images you want to process. 44 | - **Output directory**: The folder where you want to save the output images. 45 | - **Initial denoise strength**: The denoising strength of the first frame. You can set the noise reduction strength of the first frame and the rest of the frames separately. The noise reduction strength of the rest of the frames is controlled through the img2img main interface. 46 | - **Append interrogated prompt at each iteration**: Use CLIP or DeepDanbooru to predict image tags. If you have input some prompts in the prompt area, it will append to the end of the prompts. 47 | - **Third column (reference) image**: The image used to be put at the third column. 48 | - None: use only two images, the previous frame and the current frame, without a third reference image. 49 | - FirstGen: Use the **processed** first frame as the reference image. 50 | - OriginalImg: Use the **original** first frame as the reference image. 51 | - Historical: Use the second-to-last frame before the current frame as the reference image. 52 | - **Enable color correction**: Use color correction based on the loopback image. When using a non-FirstGen image as the reference image, turn on to reduce color fading. 53 | - **Unfreeze Seed**: Once checked, the basic seed value will be incremented by 1 automatically each time an image is generated. 54 | - **Loopback Source**: The images in the second column. 55 | - Previous: Generates the frame from the previous generated frame. 56 | - Currrent: Generates the frame from the current frame. 57 | - First: Generates the frame from the first generated frame. 58 | - **Read tags from text files**: This will read tags from text files with the same filename as the current input image. 59 | - **Text files directory**: Optional. It will load from the input directory if not specified. 60 | - **Use csv prompt list** and **input file path**: Use a `.csv` file as prompts for each image. One line for one image. 61 | 62 | ## Tutorial video (in Chinese) 63 | 64 | 65 | 66 | 67 | 68 | ## Credit 69 | 70 | AUTOMATIC1111's WebUI - https://github.com/AUTOMATIC1111/stable-diffusion-webui 71 | 72 | Multi-frame Rendering - https://xanthius.itch.io/multi-frame-rendering-for-stablediffusion 73 | -------------------------------------------------------------------------------- /screenshot_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OedoSoldier/sd-webui-image-sequence-toolkit/f64a9a9c7a6dc40c780179fb06332c96c0507794/screenshot_1.png -------------------------------------------------------------------------------- /screenshot_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OedoSoldier/sd-webui-image-sequence-toolkit/f64a9a9c7a6dc40c780179fb06332c96c0507794/screenshot_2.png -------------------------------------------------------------------------------- /scripts/crop_utils.py: -------------------------------------------------------------------------------- 1 | # Author: OedoSoldier [大江户战士] 2 | # https://space.bilibili.com/55123 3 | 4 | from PIL import Image, ImageFilter 5 | import numpy as np 6 | 7 | 8 | class CropUtils(object): 9 | """ 10 | This class provides utility functions for cropping and restoring images. 11 | 12 | The `crop_img()` function takes an image and a corresponding mask, and uses the mask to 13 | crop the image to the minimum bounding box that includes the non-zero pixels in the mask. 14 | If the width and height of the resulting image are not equal, the image is scaled up to a 15 | square image using zero padding. The function returns the cropped image, the cropped mask, 16 | and the bounding box and image size as a tuple. 17 | 18 | The `restore_by_file()` function takes a raw image, a cropped image, a reference image, 19 | and a blur mask, and uses these images to restore the cropped image to the raw image. 20 | The reference image is used to determine the bounding box of the cropped image, and the 21 | blur mask is used to apply a gaussian blur to the alpha channel of the cropped image. 22 | The function returns the restored image. 23 | """ 24 | 25 | def crop_img(self, img, mask, threshold=50): 26 | """ 27 | Crop the given image using the given mask. 28 | 29 | Args: 30 | img: The image to be cropped, as a PIL.Image object. 31 | mask: The mask to be used for cropping, as a PIL.Image object. 32 | threshold: The threshold to use for converting the mask to binary. Pixels in the mask 33 | with a value greater than the threshold will be considered as part of the 34 | mask, and will be included in the cropped image. Pixels with a value less 35 | than or equal to the threshold will be ignored. (default: 50) 36 | 37 | Returns: 38 | A tuple containing the cropped image, the cropped mask, and a tuple with the bounding 39 | box and image size. If the mask is empty, the function returns (img, None, None). 40 | """ 41 | 42 | # Code for cropping the image using the mask 43 | 44 | mask = mask.resize(img.size) if img.size[0] != mask.size[0] else mask 45 | 46 | bbox = mask.convert('L').point( 47 | lambda x: 255 if x > threshold else 0, 48 | mode='1').getbbox() 49 | 50 | if bbox: 51 | img, mask = img.crop(bbox), mask.crop(bbox) 52 | size = img.size 53 | if size[0] != size[1]: 54 | bigside = size[0] if size[0] > size[1] else size[1] 55 | 56 | img_np = np.zeros((bigside, bigside, 4), dtype=np.uint8) 57 | mask_np = np.zeros((bigside, bigside, 4), dtype=np.uint8) 58 | 59 | offset = ( 60 | round( 61 | (bigside - size[0]) / 2), 62 | round( 63 | (bigside - size[1]) / 2)) 64 | 65 | img_np[offset[1]:offset[1] + size[1], 66 | offset[0]:offset[0] + size[0]] = img 67 | mask_np[offset[1]:offset[1] + size[1], 68 | offset[0]:offset[0] + size[0]] = mask 69 | 70 | img = Image.fromarray(img_np) 71 | mask = Image.fromarray(mask_np) 72 | 73 | return img, mask, bbox + size 74 | 75 | return img, None, None 76 | 77 | def restore_by_file( 78 | self, 79 | raw, 80 | img, 81 | ref_img, 82 | blur_mask, 83 | info, 84 | mask_blur=0.5): 85 | """ 86 | Restore the given cropped image to the given raw image. 87 | 88 | Args: 89 | raw: The raw image, as a PIL.Image object. 90 | img: The cropped image, as a PIL.Image object. 91 | ref_img: The reference image, as a PIL.Image object. This image is used to determine 92 | the bounding box of the cropped image. 93 | blur_mask: The blur mask, as a PIL.Image object. This mask is used to apply a gaussian 94 | blur to the alpha channel of the cropped image. 95 | info: A tuple containing the bounding box of the cropped image. This tuple should have 96 | the form (upper_left_x, upper_left_y, lower_right_x, lower_right_y). 97 | mask_blur: The sigma value to use for the gaussian blur. Higher values result in a 98 | stronger blur. (default: 0.5) 99 | 100 | Returns: 101 | The restored image, as a PIL.Image object. 102 | """ 103 | 104 | # Code for restoring the cropped image 105 | 106 | raw_size = raw.size 107 | ref_size = ref_img.size 108 | 109 | upper_left_x = info[0] 110 | upper_left_y = info[1] 111 | 112 | img = img.resize(ref_size).convert('RGBA') 113 | blur_mask = blur_mask.resize(ref_size).convert('RGBA') 114 | raw = raw.convert('RGBA') 115 | 116 | bbox = ref_img.split( 117 | )[-1].convert('L').point(lambda x: 255 if x > 0 else 0, mode='1').getbbox() 118 | bbox = list(bbox) 119 | w, h = bbox[2] - bbox[0], bbox[3] - bbox[1] 120 | 121 | img = img.crop(bbox) 122 | blur_mask = blur_mask.crop(bbox) 123 | 124 | blur_img = np.zeros((raw_size[1], raw_size[0], 4), dtype=np.uint8) 125 | blur_img[upper_left_y:upper_left_y + 126 | h, upper_left_x:upper_left_x + 127 | w, :] = np.array(blur_mask) 128 | blur_img = Image.fromarray(blur_img, 'RGBA') 129 | blur_img = blur_img.filter(ImageFilter.GaussianBlur(mask_blur)) 130 | 131 | new_img = np.zeros((raw_size[1], raw_size[0], 4), dtype=np.uint8) 132 | new_img[upper_left_y:upper_left_y + 133 | h, upper_left_x:upper_left_x + 134 | w, :] = np.array(img) 135 | new_img = Image.fromarray(new_img, 'RGBA') 136 | 137 | new_img = Image.alpha_composite(raw, new_img) 138 | new_img.putalpha(blur_img.split()[-1].convert('L')) 139 | new_img = Image.alpha_composite(raw, new_img) 140 | 141 | return new_img 142 | -------------------------------------------------------------------------------- /scripts/ei_utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | import pandas as pd 3 | from modules.processing import StableDiffusionProcessingImg2Img 4 | 5 | def gr_show(visible=True): 6 | return {"visible": visible, "__type__": "update"} 7 | 8 | 9 | def gr_show_value_none(visible=True): 10 | return {"value": None, "visible": visible, "__type__": "update"} 11 | 12 | 13 | def gr_show_and_load(value=None, visible=True): 14 | if value: 15 | if value.orig_name.endswith('.csv'): 16 | value = pd.read_csv(value.name) 17 | else: 18 | value = pd.read_excel(value.name) 19 | else: 20 | visible = False 21 | return {"value": value, "visible": visible, "__type__": "update"} 22 | 23 | 24 | def gr_set_value(value=None, visible=True): 25 | return {"value": value, "visible": visible, "__type__": "update"} 26 | 27 | 28 | def sort_images(lst): 29 | pattern = re.compile(r"\d+(?=\.)(?!.*\d)") 30 | return sorted(lst, key=lambda x: int(re.search(pattern, x).group())) 31 | 32 | 33 | def I2I_Generator_Create(p, i2i_sample, i2i_mask_blur, full_res_inpainting, inpainting_padding, init_image, denoise, cfg, steps, width, height, tiling, scripts, scripts_list, alwaysonscripts_list, script_args, positive, negative): 34 | i2i = StableDiffusionProcessingImg2Img( 35 | init_images = [init_image], 36 | resize_mode = 0, 37 | denoising_strength = 0, 38 | mask = None, 39 | mask_blur= i2i_mask_blur, 40 | inpainting_fill = 1, 41 | inpaint_full_res = full_res_inpainting, 42 | inpaint_full_res_padding= inpainting_padding, 43 | inpainting_mask_invert= 0, 44 | sd_model=p.sd_model, 45 | outpath_samples=p.outpath_samples, 46 | outpath_grids=p.outpath_grids, 47 | restore_faces=p.restore_faces, 48 | prompt='', 49 | negative_prompt='', 50 | styles=p.styles, 51 | seed=p.seed, 52 | subseed=p.subseed, 53 | subseed_strength=p.subseed_strength, 54 | seed_resize_from_h=p.seed_resize_from_h, 55 | seed_resize_from_w=p.seed_resize_from_w, 56 | sampler_name=i2i_sample, 57 | n_iter=1, 58 | batch_size=1, 59 | steps=steps, 60 | cfg_scale=cfg, 61 | width=width, 62 | height=height, 63 | tiling=tiling, 64 | ) 65 | i2i.denoising_strength = denoise 66 | i2i.do_not_save_grid = True 67 | i2i.do_not_save_samples = True 68 | i2i.override_settings = {} 69 | i2i.override_settings_restore_afterwards = {} 70 | i2i.scripts = scripts 71 | i2i.scripts.scripts = scripts_list.copy() 72 | i2i.scripts.alwayson_scripts = alwaysonscripts_list.copy() 73 | i2i.script_args = script_args 74 | i2i.prompt = positive 75 | i2i.negative_prompt = negative 76 | 77 | return i2i -------------------------------------------------------------------------------- /scripts/enhanced_img2img.py: -------------------------------------------------------------------------------- 1 | # Author: OedoSoldier [大江户战士] 2 | # https://space.bilibili.com/55123 3 | 4 | import math 5 | import os 6 | import sys 7 | import traceback 8 | import copy 9 | import pandas as pd 10 | import piexif 11 | 12 | import modules.scripts as scripts 13 | import gradio as gr 14 | 15 | from scripts.crop_utils import CropUtils 16 | from scripts.ei_utils import * 17 | 18 | from modules.processing import Processed, process_images, create_infotext 19 | from PIL import Image, ImageFilter, PngImagePlugin 20 | from modules.shared import opts, cmd_opts, state 21 | from modules.script_callbacks import ImageSaveParams, before_image_saved_callback 22 | from modules.sd_hijack import model_hijack 23 | if cmd_opts.deepdanbooru: 24 | import modules.deepbooru as deepbooru 25 | 26 | import re 27 | 28 | re_findidx = re.compile( 29 | r'(?=\S)(\d+)\.(?:[P|p][N|n][G|g]?|[J|j][P|p][G|g]?|[J|j][P|p][E|e][G|g]?|[W|w][E|e][B|b][P|p]?)\b') 30 | re_findname = re.compile(r'[\w-]+?(?=\.)') 31 | 32 | 33 | # def module_from_file(module_name, file_path): 34 | # spec = importlib.util.spec_from_file_location(module_name, file_path) 35 | # module = importlib.util.module_from_spec(spec) 36 | # spec.loader.exec_module(module) 37 | # return module 38 | 39 | 40 | class Script(scripts.Script): 41 | def title(self): 42 | return 'Enhanced img2img' 43 | 44 | def description(self): 45 | return 'Process multiple images with masks' 46 | 47 | # def show(self, is_img2img): 48 | # return scripts.AlwaysVisible # is_img2img 49 | 50 | def ui(self, is_img2img): 51 | # if not is_img2img: 52 | # return None 53 | self.is_img2img = is_img2img 54 | self.max_models = opts.data.get("control_net_max_models_num", 1) 55 | 56 | with gr.Row(): 57 | input_dir = gr.Textbox(label='Input directory', lines=1) 58 | use_mask = gr.Checkbox( 59 | label='Use input image\'s alpha channel as mask', visible=self.is_img2img) 60 | 61 | output_dir = gr.Textbox(label='Output directory', lines=1) 62 | 63 | with gr.Row(): 64 | use_cn_inpaint = gr.Checkbox( 65 | label='Use Control Net inpaint model') 66 | cn_inpaint_num = gr.Dropdown( 67 | [f"Control Model - {i}" for i in range(self.max_models)], label="ControlNet inpaint model index", visible=False) 68 | 69 | with gr.Row(): 70 | use_cn_reference = gr.Checkbox( 71 | label='Use Control Net reference only mode') 72 | cn_reference_num = gr.Dropdown( 73 | [f"Control Model - {i}" for i in range(self.max_models)], label="ControlNet reference only index", visible=False) 74 | cn_reference_source = gr.Dropdown( 75 | ["First", "Previous", "Current"], label="Reference loopback source", visible=False) 76 | 77 | with gr.Row(visible=False) as mask_options: 78 | mask_dir = gr.Textbox(label='Mask directory', lines=1) 79 | as_output_alpha = gr.Checkbox( 80 | label='Use mask as output alpha channel', visible=self.is_img2img) 81 | 82 | with gr.Row(): 83 | use_img_mask = gr.Checkbox(label='Use another image as mask', visible=self.is_img2img) 84 | is_crop = gr.Checkbox(label='Zoom in masked area', visible=self.is_img2img) 85 | use_cn = gr.Checkbox(label='Use another image as ControlNet input', visible=self.is_img2img) 86 | 87 | with gr.Row(visible=(False or not self.is_img2img)) as cn_options: 88 | cn_dirs = [] 89 | with gr.Group(): 90 | with gr.Tabs(): 91 | for i in range(self.max_models): 92 | with gr.Tab(f"ControlNet-{i}", open=False): 93 | cn_dirs.append(gr.Textbox(label='ControlNet input directory', lines=1)) 94 | 95 | with gr.Row(): 96 | alpha_threshold = gr.Slider( 97 | minimum=0, 98 | maximum=255, 99 | step=1, 100 | label='Alpha threshold', 101 | value=50, 102 | visible=self.is_img2img) 103 | 104 | with gr.Row(): 105 | rotate_img = gr.Radio( 106 | label='Rotate images (clockwise)', choices=[ 107 | '0', '-90', '180', '90'], value='0') 108 | 109 | with gr.Row(): 110 | given_file = gr.Checkbox( 111 | label='Process given file(s) under the input folder, seperate by comma') 112 | specified_filename = gr.Textbox( 113 | label='Files to process', lines=1, visible=False) 114 | 115 | with gr.Row(): 116 | process_deepbooru = gr.Checkbox( 117 | label='Use deepbooru prompt', 118 | visible=cmd_opts.deepdanbooru) 119 | deepbooru_prev = gr.Checkbox( 120 | label='Using contextual information', 121 | visible=False) 122 | 123 | with gr.Row(visible=self.is_img2img): 124 | is_rerun = gr.Checkbox(label='Loopback') 125 | 126 | with gr.Row(visible=False) as rerun_options: 127 | rerun_width = gr.Slider( 128 | minimum=64.0, 129 | maximum=2048.0, 130 | step=64.0, 131 | label='Firstpass width', 132 | value=512.0) 133 | rerun_height = gr.Slider( 134 | minimum=64.0, 135 | maximum=2048.0, 136 | step=64.0, 137 | label='Firstpass height', 138 | value=512.0) 139 | rerun_strength = gr.Slider( 140 | minimum=0.0, 141 | maximum=1.0, 142 | step=0.01, 143 | label='Denoising strength', 144 | value=0.2) 145 | 146 | with gr.Row(): 147 | use_txt = gr.Checkbox(label='Read tags from text files') 148 | 149 | with gr.Row(): 150 | txt_path = gr.Textbox( 151 | label='Text files directory (optional, will load from input dir if not specified)', 152 | lines=1) 153 | 154 | with gr.Row(): 155 | use_csv = gr.Checkbox(label='Read tabular commands') 156 | csv_path = gr.File( 157 | label='.csv or .xlsx', 158 | file_types=['file'], 159 | visible=False) 160 | 161 | with gr.Row(): 162 | with gr.Column(): 163 | table_content = gr.Dataframe(visible=False, wrap=True) 164 | 165 | use_img_mask.change( 166 | fn=lambda x: gr_show(x), 167 | inputs=[use_img_mask], 168 | outputs=[mask_options], 169 | ) 170 | use_cn_inpaint.change( 171 | fn=lambda x: [gr_set_value(x), gr_set_value(x)], 172 | inputs=[use_cn_inpaint], 173 | outputs=[use_img_mask, use_cn], 174 | ) 175 | use_cn.change( 176 | fn=lambda x: gr_show(x), 177 | inputs=[use_cn], 178 | outputs=[cn_options], 179 | ) 180 | given_file.change( 181 | fn=lambda x: gr_show(x), 182 | inputs=[given_file], 183 | outputs=[specified_filename], 184 | ) 185 | process_deepbooru.change( 186 | fn=lambda x: gr_show(x), 187 | inputs=[process_deepbooru], 188 | outputs=[deepbooru_prev], 189 | ) 190 | use_csv.change( 191 | fn=lambda x: [gr_show_value_none(x), gr_show_value_none(False)], 192 | inputs=[use_csv], 193 | outputs=[csv_path, table_content], 194 | ) 195 | csv_path.change( 196 | fn=lambda x: gr_show_and_load(x), 197 | inputs=[csv_path], 198 | outputs=[table_content], 199 | ) 200 | is_rerun.change( 201 | fn=lambda x: gr_show(x), 202 | inputs=[is_rerun], 203 | outputs=[rerun_options], 204 | ) 205 | use_cn_inpaint.change( 206 | fn=lambda x: [gr_show(x), gr_show(x), gr_show(x)], 207 | inputs=[use_cn_inpaint], 208 | outputs=[use_mask, use_img_mask, cn_inpaint_num], 209 | ) 210 | use_cn_reference.change( 211 | fn=lambda x: [gr_show(x), gr_show(x)], 212 | inputs=[use_cn_reference], 213 | outputs=[cn_reference_num, cn_reference_source], 214 | ) 215 | 216 | return [ 217 | input_dir, 218 | output_dir, 219 | mask_dir, 220 | use_mask, 221 | use_img_mask, 222 | as_output_alpha, 223 | is_crop, 224 | use_cn, 225 | alpha_threshold, 226 | rotate_img, 227 | given_file, 228 | specified_filename, 229 | process_deepbooru, 230 | deepbooru_prev, 231 | use_txt, 232 | txt_path, 233 | use_csv, 234 | table_content, 235 | is_rerun, 236 | rerun_width, 237 | rerun_height, 238 | rerun_strength, 239 | use_cn_inpaint, 240 | cn_inpaint_num, 241 | use_cn_reference, 242 | cn_reference_num, 243 | cn_reference_source, 244 | *cn_dirs,] 245 | 246 | def run( 247 | self, 248 | p, 249 | input_dir, 250 | output_dir, 251 | mask_dir, 252 | use_mask, 253 | use_img_mask, 254 | as_output_alpha, 255 | is_crop, 256 | use_cn, 257 | alpha_threshold, 258 | rotate_img, 259 | given_file, 260 | specified_filename, 261 | process_deepbooru, 262 | deepbooru_prev, 263 | use_txt, 264 | txt_path, 265 | use_csv, 266 | table_content, 267 | is_rerun, 268 | rerun_width, 269 | rerun_height, 270 | rerun_strength, 271 | use_cn_inpaint, 272 | cn_inpaint_num, 273 | use_cn_reference, 274 | cn_reference_num, 275 | cn_reference_source, 276 | *cn_dirs): 277 | 278 | mask_flag = self.is_img2img or (use_cn_inpaint and not self.is_img2img) 279 | 280 | if use_cn_reference or use_cn_inpaint: 281 | use_cn = True 282 | 283 | # crop_util = module_from_file( 284 | # 'util', 'extensions/enhanced-img2img/scripts/util.py').CropUtils() 285 | 286 | rotation_dict = { 287 | '-90': Image.Transpose.ROTATE_90, 288 | '180': Image.Transpose.ROTATE_180, 289 | '90': Image.Transpose.ROTATE_270} 290 | 291 | if use_mask and mask_flag: 292 | mask_dir = input_dir 293 | use_img_mask = True 294 | as_output_alpha = True 295 | 296 | if is_rerun and self.is_img2img: 297 | original_strength = copy.deepcopy(p.denoising_strength) 298 | original_size = (copy.deepcopy(p.width), copy.deepcopy(p.height)) 299 | 300 | if process_deepbooru: 301 | deepbooru.model.start() 302 | 303 | if use_csv: 304 | prompt_list = [i[0] for i in table_content.values.tolist()] 305 | prompt_list.insert(0, prompt_list.pop()) 306 | init_prompt = p.prompt 307 | if init_prompt != "": 308 | init_prompt = init_prompt.rstrip( 309 | ', ') + ', ' if not init_prompt.rstrip().endswith(',') else init_prompt.rstrip() + ' ' 310 | 311 | initial_info = None 312 | start_img = None 313 | reference_img = None 314 | images_in_folder = [os.path.join( 315 | input_dir, 316 | f) for f in os.listdir(input_dir) if re.match( 317 | r'.+\.(jpg|png)$', 318 | f)] 319 | if given_file: 320 | if specified_filename == '': 321 | images = [os.path.join( 322 | input_dir, 323 | f) for f in os.listdir(input_dir) if re.match( 324 | r'.+\.(jpg|png)$', 325 | f)] 326 | else: 327 | images = [] 328 | try: 329 | images_idx = [int(re.findall(re_findidx, j)[0]) 330 | for j in images_in_folder] 331 | except BaseException: 332 | images_idx = [re.findall(re_findname, j)[0] 333 | for j in images_in_folder] 334 | images_in_folder_dict = dict(zip(images_idx, images_in_folder)) 335 | sep = ',' if ',' in specified_filename else ' ' 336 | for i in specified_filename.split(sep): 337 | if i in images_in_folder: 338 | images.append(i) 339 | start = end = i 340 | else: 341 | try: 342 | match = re.search(r'(^\d*)-(\d*$)', i) 343 | if match: 344 | start, end = match.groups() 345 | if start == '': 346 | start = images_idx[0] 347 | if end == '': 348 | end = images_idx[-1] 349 | images += [images_in_folder_dict[j] 350 | for j in list(range(int(start), int(end) + 1))] 351 | except BaseException: 352 | images.append(images_in_folder_dict[int(i)]) 353 | 354 | if len(images) == 0: 355 | raise FileNotFoundError 356 | 357 | else: 358 | images = [ 359 | file for file in [ 360 | os.path.join( 361 | input_dir, 362 | x) for x in os.listdir(input_dir)] if os.path.isfile(file)] 363 | images = [f for f in images if re.match(r'.+\.(jpg|png)$', f)] 364 | # images = sorted(images) 365 | images = sort_images(images) 366 | images_in_folder = sort_images(images_in_folder) 367 | start_img = images_in_folder[0] 368 | if use_cn_reference: 369 | if cn_reference_source == "First": 370 | reference_img = [images_in_folder[0] for i in images] 371 | elif cn_reference_source == "Previous": 372 | img_idx = [images_in_folder.index(i) for i in images] 373 | reference_img = [images_in_folder[max(0, i - 1)] for i in img_idx] 374 | elif cn_reference_source == "Current": 375 | reference_img = images 376 | if cn_reference_source != "Current": 377 | reference_img = [os.path.join(output_dir, os.path.basename(i)) for i in reference_img] 378 | print(f'Will process following files: {", ".join(images)}') 379 | 380 | if use_txt: 381 | if txt_path == "": 382 | files = [ 383 | re.sub( 384 | r'\.(jpg|png|jpeg|webp)$', 385 | '.txt', 386 | path) for path in images] 387 | else: 388 | files = [ 389 | os.path.join( 390 | txt_path, 391 | os.path.basename( 392 | re.sub( 393 | r'\.(jpg|png|jpeg|webp)$', 394 | '.txt', 395 | path))) for path in images] 396 | prompt_list = [open(file, 'r').read().rstrip('\n') 397 | for file in files] 398 | 399 | if use_img_mask and mask_flag: 400 | masks_in_folder = [ 401 | file for file in [ 402 | os.path.join( 403 | mask_dir, 404 | x) for x in os.listdir(mask_dir)] if os.path.isfile(file)] 405 | masks_in_folder = [f for f in masks_in_folder if re.match(r'.+\.(jpg|png)$', f)] 406 | try: 407 | masks = [ 408 | re.findall( 409 | re_findidx, 410 | file)[0] for file in masks_in_folder if os.path.isfile(file)] 411 | except BaseException: 412 | masks = [ 413 | re.findall( 414 | re_findname, 415 | file)[0] for file in masks_in_folder if os.path.isfile(file)] 416 | 417 | masks_in_folder_dict = dict(zip(masks, masks_in_folder)) 418 | 419 | else: 420 | masks = images 421 | 422 | if use_cn or not self.is_img2img: 423 | cn_in_folder_dicts = [] 424 | for cn_dir in cn_dirs: 425 | if cn_dir == '': 426 | cn_dir = input_dir 427 | 428 | cn_in_folder = [ 429 | file for file in [ 430 | os.path.join( 431 | cn_dir, 432 | x) for x in os.listdir(cn_dir)] if os.path.isfile(file)] 433 | cn_in_folder = [f for f in cn_in_folder if re.match(r'.+\.(jpg|png)$', f)] 434 | 435 | try: 436 | cn_images_ = [ 437 | re.findall( 438 | re_findidx, 439 | file)[0] for file in cn_in_folder if os.path.isfile(file)] 440 | except BaseException: 441 | cn_images_ = [ 442 | re.findall( 443 | re_findname, 444 | file)[0] for file in cn_in_folder if os.path.isfile(file)] 445 | 446 | cn_in_folder_dict = dict(zip(cn_images_, cn_in_folder)) 447 | cn_in_folder_dicts.append(cn_in_folder_dict) 448 | 449 | p.img_len = 1 450 | p.do_not_save_grid = True 451 | p.do_not_save_samples = True 452 | 453 | state.job_count = 1 454 | 455 | if process_deepbooru and deepbooru_prev: 456 | prev_prompt = [''] 457 | 458 | frame = 0 459 | 460 | img_len = len(images) 461 | if is_rerun: 462 | state.job_count *= 2 * len(images) 463 | else: 464 | state.job_count *= len(images) 465 | 466 | def set_reference(p, idx, enabled=False): 467 | import importlib 468 | external_code = importlib.import_module('extensions.sd-webui-controlnet.scripts.external_code', 'external_code') 469 | 470 | cn_units = external_code.get_all_units_in_processing(p) 471 | cn_units[idx].enabled = enabled 472 | external_code.update_cn_script_in_processing(p, cn_units) 473 | 474 | for idx, path in enumerate(images): 475 | if state.interrupted: 476 | break 477 | batch_images = [] 478 | batched_raw = [] 479 | cropped, mask, crop_info, cropped_cns, cn_images = None, None, None, None, None 480 | print(f'Processing: {path}') 481 | try: 482 | img = Image.open(path) 483 | try: 484 | to_process = re.findall(re_findidx, path)[0] 485 | except BaseException: 486 | to_process = re.findall(re_findname, path)[0] 487 | if use_cn or not self.is_img2img: 488 | cn_images = [Image.open(cn_in_folder_dict[to_process]) for cn_in_folder_dict in cn_in_folder_dicts] 489 | if use_cn_reference and path != start_img: 490 | cn_images[int(cn_reference_num[-1])] = Image.open(reference_img[idx]) 491 | if rotate_img != '0': 492 | img = img.transpose(rotation_dict[rotate_img]) 493 | if use_cn: 494 | cn_images = [cn_image.transpose(rotation_dict[rotate_img]) for cn_image in cn_images] 495 | if use_img_mask and mask_flag: 496 | try: 497 | mask = Image.open(masks_in_folder_dict[to_process]) 498 | a = mask.split()[-1].convert('L').point( 499 | lambda x: 255 if x > alpha_threshold else 0) 500 | mask = Image.merge('RGBA', (a, a, a, a.convert('L'))) 501 | except BaseException: 502 | print( 503 | f'Mask of {os.path.basename(path)} is not found, output original image!') 504 | img.save( 505 | os.path.join( 506 | output_dir, 507 | os.path.basename(path))) 508 | continue 509 | if rotate_img != '0': 510 | mask = mask.transpose( 511 | rotation_dict[rotate_img]) 512 | if is_crop: 513 | original_mask = mask.copy() 514 | cropped, mask, crop_info = CropUtils.crop_img( 515 | img.copy(), mask, alpha_threshold) 516 | if use_cn: 517 | cropped_cns = [i[0] for i in [CropUtils.crop_img(cn_image.copy(), original_mask, alpha_threshold) for cn_image in cn_images]] 518 | if not mask: 519 | print( 520 | f'Mask of {os.path.basename(path)} is blank, output original image!') 521 | img.save( 522 | os.path.join( 523 | output_dir, 524 | os.path.basename(path))) 525 | continue 526 | batched_raw.append(img.copy()) 527 | img = cropped if cropped is not None else img 528 | if use_cn: 529 | cn_images = cropped_cns if cropped_cns is not None else cn_images 530 | batch_images.append((img, path)) 531 | 532 | except BaseException: 533 | print(f'Error processing {path}:', file=sys.stderr) 534 | print(traceback.format_exc(), file=sys.stderr) 535 | 536 | if len(batch_images) == 0: 537 | print('No images will be processed.') 538 | break 539 | 540 | if process_deepbooru: 541 | deepbooru_prompt = deepbooru.model.tag_multi( 542 | batch_images[0][0]) 543 | if deepbooru_prev: 544 | deepbooru_prompt = deepbooru_prompt.split(', ') 545 | common_prompt = list( 546 | set(prev_prompt) & set(deepbooru_prompt)) 547 | p.prompt = init_prompt + ', '.join(common_prompt) + ', '.join( 548 | [i for i in deepbooru_prompt if i not in common_prompt]) 549 | prev_prompt = deepbooru_prompt 550 | else: 551 | if len(init_prompt) > 0: 552 | init_prompt += ', ' 553 | p.prompt = init_prompt + deepbooru_prompt 554 | 555 | if use_csv or use_txt: 556 | p.prompt = init_prompt + prompt_list[frame] 557 | 558 | state.job = f'{idx} out of {img_len}: {batch_images[0][1]}' 559 | if self.is_img2img: 560 | p.init_images = [x[0] for x in batch_images] 561 | 562 | if mask is not None and (use_mask or use_img_mask) and self.is_img2img: 563 | p.image_mask = mask 564 | 565 | if cn_images is not None and (use_cn or not self.is_img2img): 566 | p.control_net_input_image = cn_images 567 | if use_cn_reference: 568 | if path == start_img and cn_reference_source != 'Current': 569 | set_reference(p, int(cn_reference_num[-1]), False) 570 | else: 571 | set_reference(p, int(cn_reference_num[-1]), True) 572 | 573 | if use_cn_inpaint: 574 | inpaint_idx = int(cn_inpaint_num[-1]) 575 | p.control_net_input_image[inpaint_idx] = {"image": p.control_net_input_image[inpaint_idx], "mask": mask.convert("L")} 576 | 577 | def process_images_with_size(p, size, strength): 578 | p.width, p.height, = size 579 | p.strength = strength 580 | return process_images(p) 581 | 582 | if is_rerun and self.is_img2img: 583 | proc = process_images_with_size( 584 | p, (rerun_width, rerun_height), rerun_strength) 585 | p_2 = p 586 | p_2.init_images = proc.images 587 | proc = process_images_with_size( 588 | p_2, original_size, original_strength) 589 | else: 590 | proc = process_images(p) 591 | 592 | if initial_info is None: 593 | initial_info = proc.info 594 | for output, (input_img, path) in zip(proc.images, batch_images): 595 | filename = os.path.basename(path) 596 | if use_img_mask and self.is_img2img: 597 | if as_output_alpha: 598 | output.putalpha( 599 | p.image_mask.resize( 600 | output.size).convert('L')) 601 | 602 | if rotate_img != '0': 603 | output = output.transpose( 604 | rotation_dict[str(-int(rotate_img))]) 605 | 606 | if is_crop and self.is_img2img: 607 | output = CropUtils.restore_by_file( 608 | batched_raw[0], 609 | output, 610 | batch_images[0][0], 611 | mask, 612 | crop_info, 613 | p.mask_blur + 1) 614 | 615 | comments = {} 616 | if len(model_hijack.comments) > 0: 617 | for comment in model_hijack.comments: 618 | comments[comment] = 1 619 | 620 | info = create_infotext( 621 | p, 622 | p.all_prompts, 623 | p.all_seeds, 624 | p.all_subseeds, 625 | comments, 626 | 0, 627 | 0) 628 | pnginfo = {} 629 | if info is not None: 630 | pnginfo['parameters'] = info 631 | 632 | params = ImageSaveParams(output, p, filename, pnginfo) 633 | before_image_saved_callback(params) 634 | fullfn_without_extension, extension = os.path.splitext( 635 | filename) 636 | 637 | if is_rerun and self.is_img2img: 638 | params.pnginfo['loopback_params'] = f'Firstpass size: {rerun_width}x{rerun_height}, Firstpass strength: {original_strength}' 639 | 640 | info = params.pnginfo.get('parameters', None) 641 | 642 | def exif_bytes(): 643 | return piexif.dump({ 644 | 'Exif': { 645 | piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(info or '', encoding='unicode') 646 | }, 647 | }) 648 | 649 | if extension.lower() == '.png': 650 | pnginfo_data = PngImagePlugin.PngInfo() 651 | for k, v in params.pnginfo.items(): 652 | pnginfo_data.add_text(k, str(v)) 653 | 654 | output.save( 655 | os.path.join( 656 | output_dir, 657 | filename), 658 | pnginfo=pnginfo_data) 659 | 660 | elif extension.lower() in ('.jpg', '.jpeg', '.webp'): 661 | output.save(os.path.join(output_dir, filename)) 662 | 663 | if opts.enable_pnginfo and info is not None: 664 | piexif.insert( 665 | exif_bytes(), os.path.join( 666 | output_dir, filename)) 667 | else: 668 | output.save(os.path.join(output_dir, filename)) 669 | 670 | frame += 1 671 | 672 | if process_deepbooru: 673 | deepbooru.model.stop() 674 | 675 | return Processed(p, [], p.seed, initial_info) 676 | -------------------------------------------------------------------------------- /scripts/multi_frame_rendering.py: -------------------------------------------------------------------------------- 1 | # Original Xanthius (https://xanthius.itch.io/multi-frame-rendering-for-stablediffusion) 2 | # Modified OedoSoldier [大江户战士] (https://space.bilibili.com/55123) 3 | 4 | import numpy as np 5 | from tqdm import trange 6 | from PIL import Image, ImageSequence, ImageDraw, ImageFilter, PngImagePlugin 7 | 8 | import modules.scripts as scripts 9 | import gradio as gr 10 | 11 | from scripts.ei_utils import * 12 | 13 | from modules import processing, shared, sd_samplers, images 14 | from modules.processing import Processed 15 | from modules.sd_samplers import samplers 16 | from modules.shared import opts, cmd_opts, state 17 | from modules import deepbooru 18 | from modules.script_callbacks import ImageSaveParams, before_image_saved_callback 19 | from modules.shared import opts, cmd_opts, state 20 | from modules.sd_hijack import model_hijack 21 | 22 | import pandas as pd 23 | 24 | import piexif 25 | import piexif.helper 26 | 27 | import os 28 | import re 29 | 30 | re_findidx = re.compile( 31 | r'(?=\S)(\d+)\.(?:[P|p][N|n][G|g]?|[J|j][P|p][G|g]?|[J|j][P|p][E|e][G|g]?|[W|w][E|e][B|b][P|p]?)\b') 32 | re_findname = re.compile(r'[\w-]+?(?=\.)') 33 | 34 | class Script(scripts.Script): 35 | def title(self): 36 | return "Multi-frame rendering" 37 | 38 | def show(self, is_img2img): 39 | return is_img2img 40 | 41 | def ui(self, is_img2img): 42 | with gr.Row(): 43 | input_dir = gr.Textbox(label='Input directory', lines=1) 44 | output_dir = gr.Textbox(label='Output directory', lines=1) 45 | # reference_imgs = gr.UploadButton(label="Upload Guide Frames", file_types = ['.png','.jpg','.jpeg'], live=True, file_count = "multiple") 46 | 47 | with gr.Row(): 48 | mask_dir = gr.Textbox(label='Mask directory', placeholder="Keep blank if you don't have mask", lines=1) 49 | 50 | first_denoise = gr.Slider( 51 | minimum=0, 52 | maximum=1, 53 | step=0.05, 54 | label='Initial denoising strength', 55 | value=1, 56 | elem_id=self.elem_id("first_denoise")) 57 | append_interrogation = gr.Dropdown( 58 | label="Append interrogated prompt at each iteration", choices=[ 59 | "None", "CLIP", "DeepBooru"], value="None") 60 | third_frame_image = gr.Dropdown( 61 | label="Third column (reference) image", 62 | choices=[ 63 | "None", 64 | "FirstGen", 65 | "OriginalImg", 66 | "Historical"], 67 | value="FirstGen") 68 | color_correction_enabled = gr.Checkbox( 69 | label="Enable color correction", 70 | value=False, 71 | elem_id=self.elem_id("color_correction_enabled")) 72 | unfreeze_seed = gr.Checkbox( 73 | label="Unfreeze seed", 74 | value=False, 75 | elem_id=self.elem_id("unfreeze_seed")) 76 | loopback_source = gr.Dropdown( 77 | label="Loopback source", 78 | choices=[ 79 | "Previous", 80 | "Current", 81 | "First"], 82 | value="Current") 83 | 84 | with gr.Row(): 85 | given_file = gr.Checkbox( 86 | label='Process given file(s) under the input folder, seperate by comma') 87 | specified_filename = gr.Textbox( 88 | label='Files to process', lines=1, visible=False) 89 | 90 | self.max_models = opts.data.get("control_net_max_models_num", 1) 91 | 92 | with gr.Row(): 93 | use_cn_inpaint = gr.Checkbox( 94 | label='Use Control Net inpaint model') 95 | cn_inpaint_num = gr.Dropdown( 96 | [f"Control Model - {i}" for i in range(self.max_models)], label="ControlNet inpaint model index", visible=False) 97 | 98 | use_cn = gr.Checkbox(label='Use another image as ControlNet input') 99 | with gr.Row(visible=False) as cn_options: 100 | cn_dirs = [] 101 | with gr.Group(): 102 | with gr.Tabs(): 103 | for i in range(self.max_models): 104 | with gr.Tab(f"ControlNet-{i}", open=False): 105 | cn_dirs.append(gr.Textbox(label='ControlNet input directory', lines=1)) 106 | 107 | with gr.Row(): 108 | use_txt = gr.Checkbox(label='Read tags from text files') 109 | 110 | with gr.Row(): 111 | txt_path = gr.Textbox( 112 | label='Text files directory (Optional, will load from input dir if not specified)', 113 | lines=1) 114 | 115 | with gr.Row(): 116 | use_csv = gr.Checkbox(label='Read tabular commands') 117 | csv_path = gr.File( 118 | label='.csv or .xlsx', 119 | file_types=['file'], 120 | visible=False) 121 | 122 | with gr.Row(): 123 | with gr.Column(): 124 | table_content = gr.Dataframe(visible=False, wrap=True) 125 | 126 | use_csv.change( 127 | fn=lambda x: [gr_show_value_none(x), gr_show_value_none(False)], 128 | inputs=[use_csv], 129 | outputs=[csv_path, table_content], 130 | ) 131 | csv_path.change( 132 | fn=lambda x: gr_show_and_load(x), 133 | inputs=[csv_path], 134 | outputs=[table_content], 135 | ) 136 | given_file.change( 137 | fn=lambda x: gr_show(x), 138 | inputs=[given_file], 139 | outputs=[specified_filename], 140 | ) 141 | use_cn_inpaint.change( 142 | fn=lambda x: gr_show(x), 143 | inputs=[use_cn_inpaint], 144 | outputs=[cn_inpaint_num] 145 | ) 146 | use_cn.change( 147 | fn=lambda x: gr_show(x), 148 | inputs=[use_cn], 149 | outputs=[cn_options], 150 | ) 151 | 152 | return [ 153 | append_interrogation, 154 | input_dir, 155 | output_dir, 156 | mask_dir, 157 | first_denoise, 158 | third_frame_image, 159 | color_correction_enabled, 160 | unfreeze_seed, 161 | loopback_source, 162 | use_csv, 163 | table_content, 164 | given_file, 165 | specified_filename, 166 | use_txt, 167 | txt_path, 168 | use_cn_inpaint, 169 | cn_inpaint_num, 170 | use_cn, 171 | *cn_dirs,] 172 | 173 | def run( 174 | self, 175 | p, 176 | append_interrogation, 177 | input_dir, 178 | output_dir, 179 | mask_dir, 180 | first_denoise, 181 | third_frame_image, 182 | color_correction_enabled, 183 | unfreeze_seed, 184 | loopback_source, 185 | use_csv, 186 | table_content, 187 | given_file, 188 | specified_filename, 189 | use_txt, 190 | txt_path, 191 | use_cn_inpaint, 192 | cn_inpaint_num, 193 | use_cn, 194 | *cn_dirs,): 195 | freeze_seed = not unfreeze_seed 196 | 197 | if use_csv: 198 | prompt_list = [i[0] for i in table_content.values.tolist()] 199 | prompt_list.insert(0, prompt_list.pop()) 200 | 201 | history_imgs = None 202 | if given_file: 203 | if specified_filename == '': 204 | images = [os.path.join( 205 | input_dir, 206 | f) for f in os.listdir(input_dir) if re.match( 207 | r'.+\.(jpg|png)$', 208 | f)] 209 | else: 210 | images = [] 211 | masks = [] 212 | images_in_folder = [os.path.join( 213 | input_dir, 214 | f) for f in os.listdir(input_dir) if re.match( 215 | r'.+\.(jpg|png)$', 216 | f)] 217 | try: 218 | images_idx = [int(re.findall(re_findidx, j)[0]) 219 | for j in images_in_folder] 220 | except BaseException: 221 | images_idx = [re.findall(re_findname, j)[0] 222 | for j in images_in_folder] 223 | images_in_folder_dict = dict(zip(images_idx, images_in_folder)) 224 | sep = ',' if ',' in specified_filename else ' ' 225 | for i in specified_filename.split(sep): 226 | if i in images_in_folder: 227 | images.append(i) 228 | start = end = i 229 | else: 230 | try: 231 | match = re.search(r'(^\d*)-(\d*$)', i) 232 | if match: 233 | start, end = match.groups() 234 | if start == '': 235 | start = images_idx[0] 236 | if end == '': 237 | end = images_idx[-1] 238 | images += [images_in_folder_dict[j] 239 | for j in list(range(int(start), int(end) + 1))] 240 | except BaseException: 241 | images.append(images_in_folder_dict[int(i)]) 242 | if len(images) == 0: 243 | raise FileNotFoundError 244 | reference_imgs = [images_in_folder_dict[images_idx[0]], images_in_folder_dict[max(0, int(start) - 1)]] + images 245 | history_imgs = [images_in_folder_dict[images_idx[0]], images_in_folder_dict[max(images_idx[0], int(start) - 2)], images_in_folder_dict[max(0, int(start) - 1)]] 246 | history_imgs = [images_in_folder_dict[images_idx[0]]] + [os.path.join(output_dir, os.path.basename(f)) for f in history_imgs] 247 | else: 248 | reference_imgs = [ 249 | os.path.join( 250 | input_dir, 251 | f) for f in os.listdir(input_dir) if re.match( 252 | r'.+\.(jpg|png)$', 253 | f)] 254 | reference_imgs = sort_images(reference_imgs) 255 | print(f'Will process following files: {", ".join(reference_imgs)}') 256 | 257 | if use_txt: 258 | if txt_path == "": 259 | files = [re.sub(r'\.(jpg|png)$', '.txt', path) 260 | for path in reference_imgs] 261 | else: 262 | files = [ 263 | os.path.join( 264 | txt_path, 265 | os.path.basename( 266 | re.sub( 267 | r'\.(jpg|png)$', 268 | '.txt', 269 | path))) for path in reference_imgs] 270 | prompt_list = [open(file, 'r').read().rstrip('\n') 271 | for file in files] 272 | 273 | if use_cn: 274 | cn_dirs = [input_dir if cn_dir=="" else cn_dir for cn_dir in cn_dirs] 275 | cn_images = [[os.path.join( 276 | cn_dir, 277 | os.path.basename(path)) for path in reference_imgs] for cn_dir in cn_dirs] 278 | 279 | loops = len(reference_imgs) 280 | 281 | processing.fix_seed(p) 282 | batch_count = p.n_iter 283 | 284 | p.batch_size = 1 285 | p.n_iter = 1 286 | 287 | output_images, info = None, None 288 | initial_seed = None 289 | initial_info = None 290 | 291 | initial_width = p.width 292 | initial_img = reference_imgs[0] # p.init_images[0] 293 | p.init_images = [ 294 | Image.open(initial_img).resize( 295 | (initial_width, p.height), Image.ANTIALIAS)] 296 | 297 | # grids = [] 298 | # all_images = [] 299 | # original_init_image = p.init_images 300 | original_prompt = p.prompt 301 | if original_prompt != "": 302 | original_prompt = original_prompt.rstrip( 303 | ', ') + ', ' if not original_prompt.rstrip().endswith(',') else original_prompt.rstrip() + ' ' 304 | original_denoise = p.denoising_strength 305 | state.job_count = (loops - 2) * batch_count if given_file else loops * batch_count 306 | 307 | initial_color_corrections = [ 308 | processing.setup_color_correction( 309 | p.init_images[0])] 310 | 311 | # for n in range(batch_count): 312 | history = None 313 | # frames = [] 314 | third_image = None 315 | third_image_index = 0 316 | frame_color_correction = None 317 | 318 | # Reset to original init image at the start of each batch 319 | p.width = initial_width 320 | p.control_net_resize_mode = "Just Resize" 321 | 322 | for i in range(loops): 323 | if state.interrupted: 324 | break 325 | if given_file and i < 2: 326 | p.init_images[0] = Image.open( 327 | history_imgs[-1]).resize( 328 | (initial_width, p.height), Image.ANTIALIAS) 329 | history = p.init_images[0] 330 | if third_frame_image != "None": 331 | if third_frame_image == "FirstGen" and i == 0: 332 | third_image = Image.open( 333 | history_imgs[1]).resize( 334 | (initial_width, p.height), Image.ANTIALIAS) 335 | third_image_index = 0 336 | elif third_frame_image == "OriginalImg" and i == 0: 337 | third_image = Image.open( 338 | history_imgs[0]).resize( 339 | (initial_width, p.height), Image.ANTIALIAS) 340 | third_image_index = 0 341 | elif third_frame_image == "Historical": 342 | third_image = Image.open( 343 | history_imgs[2]).resize( 344 | (initial_width, p.height), Image.ANTIALIAS) 345 | third_image_index = (i - 1) 346 | continue 347 | filename = os.path.basename(reference_imgs[i]) 348 | print(f'Processing: {reference_imgs[i]}') 349 | p.n_iter = 1 350 | p.batch_size = 1 351 | p.do_not_save_grid = True 352 | p.control_net_input_image = Image.open( 353 | reference_imgs[i]).resize( 354 | (initial_width, p.height), Image.ANTIALIAS) 355 | 356 | if(i > 0): 357 | loopback_image = p.init_images[0] 358 | if loopback_source == "Current": 359 | loopback_image = p.control_net_input_image 360 | elif loopback_source == "First": 361 | loopback_image = history 362 | 363 | if third_frame_image != "None": 364 | p.width = initial_width * 3 365 | img = Image.new("RGB", (initial_width * 3, p.height)) 366 | img.paste(p.init_images[0], (0, 0)) 367 | # img.paste(p.init_images[0], (initial_width, 0)) 368 | img.paste(loopback_image, (initial_width, 0)) 369 | if i == 1: 370 | third_image = p.init_images[0] 371 | img.paste(third_image, (initial_width * 2, 0)) 372 | p.init_images = [img] 373 | if color_correction_enabled: 374 | p.color_corrections = [ 375 | processing.setup_color_correction(img)] 376 | 377 | if use_cn: 378 | msk = [] 379 | for cn_image in cn_images: 380 | m = Image.new("RGB", (initial_width * 3, p.height)) 381 | m.paste(Image.open(cn_image[i - 1]).resize( 382 | (initial_width, p.height), Image.ANTIALIAS), (0, 0)) 383 | m.paste(Image.open(cn_image[i]).resize( 384 | (initial_width, p.height), Image.ANTIALIAS), (initial_width, 0)) 385 | m.paste(Image.open(cn_image[third_image_index]).resize( 386 | (initial_width, p.height), Image.ANTIALIAS), (initial_width * 2, 0)) 387 | msk.append(m) 388 | else: 389 | msk = Image.new("RGB", (initial_width * 3, p.height)) 390 | msk.paste(Image.open(reference_imgs[i - 1]).resize( 391 | (initial_width, p.height), Image.ANTIALIAS), (0, 0)) 392 | msk.paste(p.control_net_input_image, (initial_width, 0)) 393 | msk.paste(Image.open(reference_imgs[third_image_index]).resize( 394 | (initial_width, p.height), Image.ANTIALIAS), (initial_width * 2, 0)) 395 | p.control_net_input_image = msk 396 | latent_mask = Image.new( 397 | "RGB", (initial_width * 3, p.height), "black") 398 | if mask_dir == '': 399 | latent_draw = ImageDraw.Draw(latent_mask) 400 | latent_draw.rectangle( 401 | (initial_width, 0, initial_width * 2, p.height), fill="white") 402 | else: 403 | latent_mask.paste(Image.open(os.path.join(mask_dir, os.path.basename(filename))).resize( 404 | (initial_width, p.height), Image.ANTIALIAS).convert("L"), (initial_width, 0)) 405 | p.image_mask = latent_mask 406 | p.denoising_strength = original_denoise 407 | else: 408 | p.width = initial_width * 2 409 | img = Image.new("RGB", (initial_width * 2, p.height)) 410 | img.paste(p.init_images[0], (0, 0)) 411 | # img.paste(p.init_images[0], (initial_width, 0)) 412 | img.paste(loopback_image, (initial_width, 0)) 413 | p.init_images = [img] 414 | if color_correction_enabled: 415 | p.color_corrections = [ 416 | processing.setup_color_correction(img)] 417 | 418 | if use_cn: 419 | msk = [] 420 | for cn_image in cn_images: 421 | m = Image.new("RGB", (initial_width * 2, p.height)) 422 | m.paste(Image.open(cn_image[i - 1]).resize( 423 | (initial_width, p.height), Image.ANTIALIAS), (0, 0)) 424 | m.paste(Image.open(cn_image[i]).resize( 425 | (initial_width, p.height), Image.ANTIALIAS), (initial_width, 0)) 426 | else: 427 | msk = Image.new("RGB", (initial_width * 2, p.height)) 428 | msk.paste(Image.open(reference_imgs[i - 1]).resize( 429 | (initial_width, p.height), Image.ANTIALIAS), (0, 0)) 430 | msk.paste(p.control_net_input_image, (initial_width, 0)) 431 | p.control_net_input_image = msk 432 | # frames.append(msk) 433 | 434 | # latent_mask = Image.new("RGB", (initial_width*2, p.height), "white") 435 | # latent_draw = ImageDraw.Draw(latent_mask) 436 | # latent_draw.rectangle((0,0,initial_width,p.height), fill="black") 437 | latent_mask = Image.new( 438 | "RGB", (initial_width * 2, p.height), "black") 439 | if mask_dir == '': 440 | latent_draw = ImageDraw.Draw(latent_mask) 441 | latent_draw.rectangle( 442 | (initial_width, 0, initial_width * 2, p.height), fill="white") 443 | else: 444 | latent_mask.paste(Image.open(os.path.join(mask_dir, os.path.basename(filename))).resize( 445 | (initial_width, p.height), Image.ANTIALIAS).convert("L"), (initial_width, 0)) 446 | 447 | # p.latent_mask = latent_mask 448 | p.image_mask = latent_mask 449 | p.denoising_strength = original_denoise 450 | else: 451 | p.init_images = [p.init_images[0].resize((initial_width, p.height), Image.ANTIALIAS)] 452 | if mask_dir == '': 453 | latent_mask = Image.new( 454 | "RGB", (initial_width, p.height), "white") 455 | else: 456 | latent_mask = Image.open(os.path.join(mask_dir, os.path.basename(filename))).resize( 457 | (initial_width, p.height), Image.ANTIALIAS).convert("L") 458 | # p.latent_mask = latent_mask 459 | p.image_mask = latent_mask 460 | p.denoising_strength = first_denoise 461 | if use_cn: 462 | p.control_net_input_image = [Image.open(cn_image[0]).resize((initial_width, p.height), Image.ANTIALIAS) for cn_image in cn_images] 463 | else: 464 | p.control_net_input_image = p.control_net_input_image.resize((initial_width, p.height), Image.ANTIALIAS) 465 | # frames.append(p.control_net_input_image) 466 | 467 | # if opts.img2img_color_correction: 468 | # p.color_corrections = initial_color_corrections 469 | 470 | if append_interrogation != "None": 471 | p.prompt = original_prompt 472 | if append_interrogation == "CLIP": 473 | p.prompt += shared.interrogator.interrogate( 474 | p.init_images[0]) 475 | elif append_interrogation == "DeepBooru": 476 | p.prompt += deepbooru.model.tag(p.init_images[0]) 477 | 478 | if use_csv or use_txt: 479 | p.prompt = original_prompt + prompt_list[i] 480 | 481 | # state.job = f"Iteration {i + 1}/{loops}, batch {n + 1}/{batch_count}" 482 | if use_cn_inpaint: 483 | p.control_net_input_image = [p.control_net_input_image] * self.max_models 484 | p.control_net_input_image[int(cn_inpaint_num[-1])] = {"image": p.init_images[0], "mask": p.image_mask.convert("L")} 485 | 486 | processed = processing.process_images(p) 487 | 488 | if initial_seed is None: 489 | initial_seed = processed.seed 490 | initial_info = processed.info 491 | 492 | init_img = processed.images[0] 493 | if(i > 0): 494 | init_img = init_img.crop( 495 | (initial_width, 0, initial_width * 2, p.height)) 496 | 497 | comments = {} 498 | if len(model_hijack.comments) > 0: 499 | for comment in model_hijack.comments: 500 | comments[comment] = 1 501 | 502 | info = processing.create_infotext( 503 | p, 504 | p.all_prompts, 505 | p.all_seeds, 506 | p.all_subseeds, 507 | comments, 508 | 0, 509 | 0) 510 | pnginfo = {} 511 | if info is not None: 512 | pnginfo['parameters'] = info 513 | 514 | params = ImageSaveParams(init_img, p, filename, pnginfo) 515 | before_image_saved_callback(params) 516 | fullfn_without_extension, extension = os.path.splitext( 517 | filename) 518 | 519 | info = params.pnginfo.get('parameters', None) 520 | 521 | def exif_bytes(): 522 | return piexif.dump({ 523 | 'Exif': { 524 | piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(info or '', encoding='unicode') 525 | }, 526 | }) 527 | 528 | if extension.lower() == '.png': 529 | pnginfo_data = PngImagePlugin.PngInfo() 530 | for k, v in params.pnginfo.items(): 531 | pnginfo_data.add_text(k, str(v)) 532 | 533 | init_img.save( 534 | os.path.join( 535 | output_dir, 536 | filename), 537 | pnginfo=pnginfo_data) 538 | 539 | elif extension.lower() in ('.jpg', '.jpeg', '.webp'): 540 | init_img.save(os.path.join(output_dir, filename)) 541 | 542 | if opts.enable_pnginfo and info is not None: 543 | piexif.insert( 544 | exif_bytes(), os.path.join( 545 | output_dir, filename)) 546 | else: 547 | init_img.save(os.path.join(output_dir, filename)) 548 | 549 | if third_frame_image != "None": 550 | if third_frame_image == "FirstGen" and i == 0: 551 | third_image = init_img 552 | third_image_index = 0 553 | elif third_frame_image == "OriginalImg" and i == 0: 554 | third_image = initial_img[0] 555 | third_image_index = 0 556 | elif third_frame_image == "Historical": 557 | third_image = processed.images[0].crop( 558 | (0, 0, initial_width, p.height)) 559 | third_image_index = (i - 1) 560 | 561 | p.init_images = [init_img] 562 | if(freeze_seed): 563 | p.seed = processed.seed 564 | else: 565 | p.seed = processed.seed + 1 566 | # p.seed = processed.seed 567 | if i == 0: 568 | history = init_img 569 | # history.append(processed.images[0]) 570 | # frames.append(processed.images[0]) 571 | 572 | # grid = images.image_grid(history, rows=1) 573 | # if opts.grid_save: 574 | # images.save_image(grid, p.outpath_grids, "grid", initial_seed, p.prompt, opts.grid_format, info=info, short_filename=not opts.grid_extended_filename, grid=True, p=p) 575 | 576 | # grids.append(grid) 577 | # # all_images += history + frames 578 | # all_images += history 579 | 580 | # p.seed = p.seed+1 581 | 582 | # if opts.return_grid: 583 | # all_images = grids + all_images 584 | 585 | processed = Processed(p, [], initial_seed, initial_info) 586 | 587 | return processed 588 | --------------------------------------------------------------------------------