├── LICENSE ├── README.md ├── __init__.py ├── absolute_path.py ├── generate.py ├── input └── .placeholder ├── install_dependencies.py ├── install_pytorch_dependencies.py ├── output └── .placeholder ├── preview └── preview1.png ├── requirements.txt └── utils ├── architecture ├── architecture.py └── block.py ├── imgops.py └── models ├── 1x_FrankenMapGenerator-CX-Lite_215000_G.pth └── 1x_NormalMapGenerator-CX-Lite_200000_G.pth /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 | # Material Map Generator 2 | 3 | 4 | A Blender plugin to easily generate Material Maps from an Image Texture with one click using [Material-Map_generator](https://github.com/joeyballentine/Material-Map-Generator) by [Joey Ballentine](https://github.com/joeyballentine). 5 | 6 | ## Requirments: 7 | * System: Windows/Linux/MacOs 8 | * GPU: 9 | 1. Nvidia GPU with a [CUDA-capable](https://developer.nvidia.com/cuda-zone) system 10 | 2. AMD GPU with an [ROCm-capable](https://rocmdocs.amd.com/en/latest/Installation_Guide/Installation_new.html) system (Linux only) 11 | 3. Apple M1 chip 12 | * Blender version: 2.91.0+ 13 | 14 | ## Installation: 15 | 1. Download MaterialMapGenerator.zip from the [lateset release](https://github.com/YahiaAngelo/MaterialMapGenerator/releases/latest). 16 | 2. Open Blender prefrences -> Add-ons -> Install and choose the downloaded package. 17 | 3. Enable the plugin then click on: 18 | * "Install dependencies" if you have an Nvida GPU. 19 | * "Install AMD GPU dependencies" if you have an AMD GPU. 20 | * "Install Apple M1 dependencies" if you have an Apple M1 machine. 21 | 4. Go grab some coffee because the previous step will take some time (Pro tip: Click on window -> Toggle system console to see the progress). 22 | 23 | ## Usage: 24 | 25 | 1. Go to your shader editor and click on your Image Texture node with an image then click on "node" menu and choose "Generate Material Maps". 26 | 2. Wait for a couple of seconds and Boom! you have Material Maps! 27 | ![Preview1](https://github.com/YahiaAngelo/MaterialMapGenerator/blob/master/preview/preview1.png?raw=true) 28 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | bl_info = { 2 | "name": "Material Map Generator", 3 | "author": "YahiaAngelo", 4 | "version": (1, 0, 2), 5 | "blender": (2, 91, 0), 6 | "location": "Shader Editor > node > Generate Material Maps", 7 | "description": "Extracts Material Maps from Image Textures", 8 | "warning": "Requires installation of dependencies", 9 | "tracker_url": "https://github.com/YahiaAngelo/MaterialMapGenerator/issues", 10 | "support": "COMMUNITY", 11 | "category": "Shader Editor"} 12 | 13 | 14 | import bpy 15 | from .absolute_path import absolute_path, path_iterator, delete_files_in_path 16 | from .install_dependencies import install_pip, install_and_import_requirements 17 | from .install_pytorch_dependencies import install_pytorch_modules, install_pytorch_amd_modules, install_pytorch_apple_modules 18 | import os 19 | import subprocess 20 | import shutil 21 | 22 | def main(operator, context): 23 | space = context.space_data 24 | node_tree = space.node_tree 25 | node_active = context.active_node 26 | node_selected = context.selected_nodes 27 | 28 | # now we have the context, perform a simple operation 29 | if node_active in node_selected: 30 | node_selected.remove(node_active) 31 | if len(node_selected) > 1: 32 | operator.report({'ERROR'}, "1 node must be selected") 33 | return 34 | 35 | if node_active.name != 'Image Texture': 36 | operator.report({'ERROR'}, "Please select an Image Texture") 37 | return 38 | 39 | if node_active.image.filepath == "": 40 | operator.report({'ERROR'}, "Please add an image") 41 | return 42 | #Copy the image from ImageTexture to plugin input folder 43 | shutil.copy2(node_active.image.filepath, absolute_path("input")) 44 | 45 | import site 46 | site.addsitedir(absolute_path('.python_dependencies')) 47 | from .generate import GenerateMaterialMap 48 | generate = GenerateMaterialMap() 49 | generate.start() 50 | 51 | images = [] 52 | originalPath = os.path.dirname(node_active.image.filepath) 53 | for imgPath in path_iterator(absolute_path("output")): 54 | fullPath = os.path.join(absolute_path("output"), imgPath) 55 | shutil.copy2(fullPath, originalPath) 56 | newImage = bpy.data.images.load(os.path.join(originalPath, imgPath)) 57 | images.append(newImage) 58 | 59 | new_nodes = [] 60 | for image in images: 61 | node_new = node_tree.nodes.new(node_active.bl_idname) 62 | for key, input in enumerate(node_active.inputs): 63 | node_new.inputs[key].default_value = input.default_value 64 | node_new.image = image 65 | new_nodes.append(node_new) 66 | 67 | #Delete all images processed 68 | delete_files_in_path(absolute_path("input")) 69 | delete_files_in_path(absolute_path("output")) 70 | 71 | return new_nodes 72 | 73 | 74 | 75 | class NodeOperator(bpy.types.Operator): 76 | """Tooltip""" 77 | bl_idname = "node.material_mapper" 78 | bl_label = "Generate Material Maps" 79 | 80 | @classmethod 81 | def poll(cls, context): 82 | space = context.space_data 83 | return space.type == 'NODE_EDITOR' 84 | 85 | def execute(self, context): 86 | main(self, context) 87 | return {'FINISHED'} 88 | 89 | 90 | def menu_func(self, context): 91 | self.layout.operator(NodeOperator.bl_idname, text=NodeOperator.bl_label) 92 | 93 | 94 | dependencies_installed = False 95 | 96 | class InstallDependenciesOT(bpy.types.Operator): 97 | bl_idname = "material_mapper.install_dependencies" 98 | bl_label = "Install dependencies" 99 | bl_description = ("Downloads and installs the required python packages for this add-on. " 100 | "Internet connection is required. Blender may have to be started with " 101 | "elevated permissions in order to install the package") 102 | bl_options = {"REGISTER", "INTERNAL"} 103 | 104 | #@classmethod 105 | #def poll(self, context): 106 | # # Deactivate when dependencies have been installed 107 | # return not dependencies_installed 108 | 109 | def execute(self, context): 110 | try: 111 | install_pip() 112 | install_and_import_requirements(absolute_path("requirements.txt"), absolute_path('.python_dependencies')) 113 | install_pytorch_modules(absolute_path('.python_dependencies')) 114 | except (subprocess.CalledProcessError, ImportError) as err: 115 | self.report({"ERROR"}, str(err)) 116 | return {"CANCELLED"} 117 | 118 | global dependencies_installed 119 | dependencies_installed = True 120 | 121 | return {"FINISHED"} 122 | 123 | class InstallAmdDependenciesOT(bpy.types.Operator): 124 | bl_idname = "material_mapper.install_amd_dependencies" 125 | bl_label = "Install AMD GPU dependencies" 126 | bl_description = ("Please click on this instead if you have an AMD GPU (Linux only)") 127 | bl_options = {"REGISTER", "INTERNAL"} 128 | 129 | #@classmethod 130 | #def poll(self, context): 131 | # # Deactivate when dependencies have been installed 132 | # return not dependencies_installed 133 | 134 | def execute(self, context): 135 | try: 136 | install_pip() 137 | install_and_import_requirements(absolute_path("requirements.txt"), absolute_path('.python_dependencies')) 138 | install_pytorch_amd_modules(absolute_path('.python_dependencies')) 139 | except (subprocess.CalledProcessError, ImportError) as err: 140 | self.report({"ERROR"}, str(err)) 141 | return {"CANCELLED"} 142 | 143 | global dependencies_installed 144 | dependencies_installed = True 145 | 146 | return {"FINISHED"} 147 | 148 | class InstallAppleDependenciesOT(bpy.types.Operator): 149 | bl_idname = "material_mapper.install_apple_dependencies" 150 | bl_label = "Install Apple M1 dependencies" 151 | bl_description = ("Please click on this instead if you have an Apple M1 machine") 152 | bl_options = {"REGISTER", "INTERNAL"} 153 | 154 | def execute(self, context): 155 | try: 156 | install_pip() 157 | install_and_import_requirements(absolute_path("requirements.txt"), absolute_path('.python_dependencies')) 158 | install_pytorch_apple_modules(absolute_path('.python_dependencies')) 159 | except (subprocess.CalledProcessError, ImportError) as err: 160 | self.report({"ERROR"}, str(err)) 161 | return {"CANCELLED"} 162 | 163 | global dependencies_installed 164 | dependencies_installed = True 165 | 166 | return {"FINISHED"} 167 | 168 | 169 | class Prefrences(bpy.types.AddonPreferences): 170 | bl_idname = __name__ 171 | 172 | def draw(self, context): 173 | layout = self.layout 174 | layout.operator(InstallDependenciesOT.bl_idname, icon="CONSOLE") 175 | layout.operator(InstallAmdDependenciesOT.bl_idname, icon="CONSOLE") 176 | layout.operator(InstallAppleDependenciesOT.bl_idname, icon="CONSOLE") 177 | 178 | 179 | 180 | preference_classes = (InstallDependenciesOT, 181 | InstallAmdDependenciesOT, 182 | InstallAppleDependenciesOT, 183 | Prefrences) 184 | 185 | 186 | def register(): 187 | for cls in preference_classes: 188 | bpy.utils.register_class(cls) 189 | 190 | bpy.utils.register_class(NodeOperator) 191 | bpy.types.NODE_MT_node.append(menu_func) 192 | 193 | 194 | def unregister(): 195 | for cls in preference_classes: 196 | bpy.utils.unregister_class(cls) 197 | 198 | bpy.utils.unregister_class(NodeOperator) 199 | bpy.types.NODE_MT_node.remove(menu_func) 200 | 201 | 202 | if __name__ == "__main__": 203 | register() 204 | -------------------------------------------------------------------------------- /absolute_path.py: -------------------------------------------------------------------------------- 1 | import os, bpy, shutil 2 | 3 | def absolute_path(component): 4 | return os.path.join(os.path.dirname(os.path.realpath(__file__)), component) 5 | 6 | def path_iterator(folder_path): 7 | for fp in os.listdir(folder_path): 8 | if fp.endswith( tuple( bpy.path.extensions_image ) ): 9 | yield fp 10 | 11 | def delete_files_in_path(folder_path): 12 | for filename in os.listdir(folder_path): 13 | file_path = os.path.join(folder_path, filename) 14 | try: 15 | if os.path.isfile(file_path) or os.path.islink(file_path): 16 | os.unlink(file_path) 17 | elif os.path.isdir(file_path): 18 | shutil.rmtree(file_path) 19 | except Exception as e: 20 | print('Failed to delete %s. Reason: %s' % (file_path, e)) -------------------------------------------------------------------------------- /generate.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | 4 | import cv2 5 | import numpy as np 6 | import torch 7 | import sys 8 | 9 | from .utils.imgops import crop_seamless, esrgan_launcher_split_merge 10 | from .utils.architecture.architecture import RRDB_Net 11 | from .absolute_path import absolute_path 12 | 13 | class GenerateMaterialMap: 14 | 15 | def __init__(self): 16 | 17 | self.parser = argparse.ArgumentParser() 18 | self.parser.add_argument('--input', default=absolute_path("input"), help='Input folder') 19 | self.parser.add_argument('--output', default=absolute_path("output"), help='Output folder') 20 | self.parser.add_argument('--reverse', help='Reverse Order', action="store_true") 21 | self.parser.add_argument('--tile_size', default=512, 22 | help='Tile size for splitting', type=int) 23 | self.parser.add_argument('--seamless', action='store_true', 24 | help='Seamless upscaling') 25 | self.parser.add_argument('--mirror', action='store_true', 26 | help='Mirrored seamless upscaling') 27 | self.parser.add_argument('--replicate', action='store_true', 28 | help='Replicate edge pixels for padding') 29 | self.parser.add_argument('--cpu', action='store_true', 30 | help='Use CPU instead of CUDA') 31 | self.parser.add_argument('--ishiiruka', action='store_true', 32 | help='Save textures in the format used in Ishiiruka Dolphin material map texture packs') 33 | self.parser.add_argument('--ishiiruka_texture_encoder', action='store_true', 34 | help='Save textures in the format used by Ishiiruka Dolphin\'s Texture Encoder tool') 35 | self.args = self.parser.parse_args() 36 | 37 | if not os.path.exists(self.args.input): 38 | print('Error: Folder [{:s}] does not exist.'.format(self.args.input)) 39 | sys.exit(1) 40 | elif os.path.isfile(self.args.input): 41 | print('Error: Folder [{:s}] is a file.'.format(self.args.input)) 42 | sys.exit(1) 43 | elif os.path.isfile(self.args.output): 44 | print('Error: Folder [{:s}] is a file.'.format(self.args.output)) 45 | sys.exit(1) 46 | elif not os.path.exists(self.args.output): 47 | os.mkdir(self.args.output) 48 | 49 | isCudaAvailable = torch.cuda.is_available() 50 | if not isCudaAvailable: 51 | print("Warning: Couldn't find available CUDA devices, using cpu instead") 52 | 53 | self.device = torch.device('cpu' if self.args.cpu or not isCudaAvailable else 'cuda') 54 | 55 | if torch.backends.mps.is_available(): 56 | print("Info: Found Apple Metal chip, using MPS") 57 | self.device = torch.device('mps') 58 | 59 | self.input_folder = os.path.normpath(self.args.input) 60 | self.output_folder = os.path.normpath(self.args.output) 61 | 62 | self.NORMAL_MAP_MODEL = absolute_path('utils/models/1x_NormalMapGenerator-CX-Lite_200000_G.pth') 63 | self.OTHER_MAP_MODEL = absolute_path('utils/models/1x_FrankenMapGenerator-CX-Lite_215000_G.pth') 64 | 65 | def process(self, img, model): 66 | img = img * 1. / np.iinfo(img.dtype).max 67 | img = img[:, :, [2, 1, 0]] 68 | img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float() 69 | img_LR = img.unsqueeze(0) 70 | img_LR = img_LR.to(self.device) 71 | 72 | output = model(img_LR).data.squeeze( 73 | 0).float().cpu().clamp_(0, 1).numpy() 74 | output = output[[2, 1, 0], :, :] 75 | output = np.transpose(output, (1, 2, 0)) 76 | output = (output * 255.).round() 77 | return output 78 | 79 | def load_model(self, model_path): 80 | global device 81 | state_dict = torch.load(model_path) 82 | model = RRDB_Net(3, 3, 32, 12, gc=32, upscale=1, norm_type=None, act_type='leakyrelu', 83 | mode='CNA', res_scale=1, upsample_mode='upconv') 84 | model.load_state_dict(state_dict, strict=True) 85 | del state_dict 86 | model.eval() 87 | for k, v in model.named_parameters(): 88 | v.requires_grad = False 89 | return model.to(self.device) 90 | 91 | def start(self): 92 | images=[] 93 | for root, _, files in os.walk(self.input_folder): 94 | for file in sorted(files, reverse=self.args.reverse): 95 | if file.split('.')[-1].lower() in ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'tga']: 96 | images.append(os.path.join(root, file)) 97 | models = [ 98 | # NORMAL MAP 99 | self.load_model(self.NORMAL_MAP_MODEL), 100 | # ROUGHNESS/DISPLACEMENT MAPS 101 | self.load_model(self.OTHER_MAP_MODEL) 102 | ] 103 | for idx, path in enumerate(images, 1): 104 | base = os.path.splitext(os.path.relpath(path, self.input_folder))[0] 105 | output_dir = os.path.dirname(os.path.join(self.output_folder, base)) 106 | os.makedirs(output_dir, exist_ok=True) 107 | print(idx, base) 108 | # read image 109 | try: 110 | img = cv2.imread(path, cv2.cv2.IMREAD_COLOR) 111 | except: 112 | img = cv2.imread(path, cv2.IMREAD_COLOR) 113 | 114 | # Seamless modes 115 | if self.args.seamless: 116 | img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_WRAP) 117 | elif self.args.mirror: 118 | img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_REFLECT_101) 119 | elif self.args.replicate: 120 | img = cv2.copyMakeBorder(img, 16, 16, 16, 16, cv2.BORDER_REPLICATE) 121 | 122 | img_height, img_width = img.shape[:2] 123 | 124 | # Whether or not to perform the split/merge action 125 | do_split = img_height > self.args.tile_size or img_width > self.args.tile_size 126 | 127 | if do_split: 128 | rlts = esrgan_launcher_split_merge(img, self.process, models, scale_factor=1, tile_size=self.args.tile_size) 129 | else: 130 | rlts = [self.process(img, model) for model in models] 131 | 132 | if self.args.seamless or self.args.mirror or self.args.replicate: 133 | rlts = [crop_seamless(rlt) for rlt in rlts] 134 | 135 | normal_map = rlts[0] 136 | roughness = rlts[1][:, :, 1] 137 | displacement = rlts[1][:, :, 0] 138 | 139 | if self.args.ishiiruka_texture_encoder: 140 | r = 255 - roughness 141 | g = normal_map[:, :, 1] 142 | b = displacement 143 | a = normal_map[:, :, 2] 144 | output = cv2.merge((b, g, r, a)) 145 | cv2.imwrite(os.path.join(self.output_folder, '{:s}.mat.png'.format(base)), output) 146 | else: 147 | normal_name = '{:s}.nrm.png'.format(base) if self.args.ishiiruka else '{:s}_Normal.png'.format(base) 148 | cv2.imwrite(os.path.join(self.output_folder, normal_name), normal_map) 149 | 150 | rough_name = '{:s}.spec.png'.format(base) if self.args.ishiiruka else '{:s}_Roughness.png'.format(base) 151 | rough_img = 255 - roughness if self.args.ishiiruka else roughness 152 | cv2.imwrite(os.path.join(self.output_folder, rough_name), rough_img) 153 | 154 | displ_name = '{:s}.bump.png'.format(base) if self.args.ishiiruka else '{:s}_Displacement.png'.format(base) 155 | cv2.imwrite(os.path.join(self.output_folder, displ_name), displacement) 156 | -------------------------------------------------------------------------------- /input/.placeholder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YahiaAngelo/MaterialMapGenerator/74d510811213e86d76bc6795401ca3d07703cd5d/input/.placeholder -------------------------------------------------------------------------------- /install_dependencies.py: -------------------------------------------------------------------------------- 1 | import bpy 2 | import os 3 | import sys 4 | import subprocess 5 | import importlib 6 | 7 | def import_module(module_name, global_name=None, reload=True): 8 | """ 9 | Import a module. 10 | :param module_name: Module to import. 11 | :param global_name: (Optional) Name under which the module is imported. If None the module_name will be used. 12 | This allows to import under a different name with the same effect as e.g. "import numpy as np" where "np" is 13 | the global_name under which the module can be accessed. 14 | :raises: ImportError and ModuleNotFoundError 15 | """ 16 | if global_name is None: 17 | global_name = module_name 18 | 19 | if global_name in globals(): 20 | importlib.reload(globals()[global_name]) 21 | else: 22 | # Attempt to import the module and assign it to globals dictionary. This allow to access the module under 23 | # the given name, just like the regular import would. 24 | globals()[global_name] = importlib.import_module(module_name) 25 | 26 | 27 | def install_pip(): 28 | """ 29 | Installs pip if not already present. Please note that ensurepip.bootstrap() also calls pip, which adds the 30 | environment variable PIP_REQ_TRACKER. After ensurepip.bootstrap() finishes execution, the directory doesn't exist 31 | anymore. However, when subprocess is used to call pip, in order to install a package, the environment variables 32 | still contain PIP_REQ_TRACKER with the now nonexistent path. This is a problem since pip checks if PIP_REQ_TRACKER 33 | is set and if it is, attempts to use it as temp directory. This would result in an error because the 34 | directory can't be found. Therefore, PIP_REQ_TRACKER needs to be removed from environment variables. 35 | :return: 36 | """ 37 | 38 | try: 39 | # Check if pip is already installed 40 | subprocess.run([sys.executable, "-m", "pip", "--version"], check=True) 41 | except subprocess.CalledProcessError: 42 | import ensurepip 43 | 44 | ensurepip.bootstrap() 45 | os.environ.pop("PIP_REQ_TRACKER", None) 46 | 47 | 48 | def install_and_import_requirements(requirements, target): 49 | """ 50 | Installs the package through pip and attempts to import the installed module. 51 | :param module_name: Module to import. 52 | :param package_name: (Optional) Name of the package that needs to be installed. If None it is assumed to be equal 53 | to the module_name. 54 | :param global_name: (Optional) Name under which the module is imported. If None the module_name will be used. 55 | This allows to import under a different name with the same effect as e.g. "import numpy as np" where "np" is 56 | the global_name under which the module can be accessed. 57 | :raises: subprocess.CalledProcessError and ImportError 58 | """ 59 | 60 | # Create a copy of the environment variables and modify them for the subprocess call 61 | environ_copy = dict(os.environ) 62 | environ_copy["PYTHONNOUSERSITE"] = "1" 63 | 64 | subprocess.run([sys.executable, "-m", "pip", "install", "-r", requirements, "--no-cache-dir", "--target", target], check=True, env=environ_copy) 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /install_pytorch_dependencies.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import subprocess 4 | 5 | 6 | def install_pytorch_modules(target): 7 | environ_copy = dict(os.environ) 8 | environ_copy["PYTHONNOUSERSITE"] = "1" 9 | 10 | subprocess.run([sys.executable, "-m", "pip", "install", "torch", "torchvision", "--extra-index-url", "https://download.pytorch.org/whl/cu116", "--no-cache-dir", "--target", target], check=True, env=environ_copy) 11 | 12 | 13 | def install_pytorch_amd_modules(target): 14 | environ_copy = dict(os.environ) 15 | environ_copy["PYTHONNOUSERSITE"] = "1" 16 | 17 | subprocess.run([sys.executable, "-m", "pip", "install", "torch", "torchvision", "--extra-index-url", "https://download.pytorch.org/whl/rocm5.2/", "--no-cache-dir", "--target", target], check=True, env=environ_copy) 18 | 19 | 20 | def install_pytorch_apple_modules(target): 21 | environ_copy = dict(os.environ) 22 | environ_copy["PYTHONNOUSERSITE"] = "1" 23 | 24 | subprocess.run([sys.executable, "-m", "pip", "install", "torch", "torchvision", "--extra-index-url", "https://download.pytorch.org/whl/nightly/cpu", "--no-cache-dir", "--target", target], check=True, env=environ_copy) 25 | -------------------------------------------------------------------------------- /output/.placeholder: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YahiaAngelo/MaterialMapGenerator/74d510811213e86d76bc6795401ca3d07703cd5d/output/.placeholder -------------------------------------------------------------------------------- /preview/preview1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YahiaAngelo/MaterialMapGenerator/74d510811213e86d76bc6795401ca3d07703cd5d/preview/preview1.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | opencv-python==4.6.0.66 3 | -------------------------------------------------------------------------------- /utils/architecture/architecture.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch.nn as nn 3 | from .block import RRDB, ShortcutBlock, conv_block, upconv_blcok, pixelshuffle_block, sequential 4 | 5 | #################### 6 | # Generator 7 | #################### 8 | 9 | class RRDB_Net(nn.Module): 10 | def __init__(self, in_nc, out_nc, nf, nb, gc=32, upscale=4, norm_type=None, act_type='leakyrelu', \ 11 | mode='CNA', res_scale=1, upsample_mode='upconv'): 12 | super(RRDB_Net, self).__init__() 13 | n_upscale = int(math.log(upscale, 2)) 14 | if upscale == 3: 15 | n_upscale = 1 16 | 17 | fea_conv = conv_block(in_nc, nf, kernel_size=3, norm_type=None, act_type=None) 18 | rb_blocks = [RRDB(nf, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \ 19 | norm_type=norm_type, act_type=act_type, mode='CNA') for _ in range(nb)] 20 | LR_conv = conv_block(nf, nf, kernel_size=3, norm_type=norm_type, act_type=None, mode=mode) 21 | 22 | if upsample_mode == 'upconv': 23 | upsample_block = upconv_blcok 24 | elif upsample_mode == 'pixelshuffle': 25 | upsample_block = pixelshuffle_block 26 | else: 27 | raise NotImplementedError('upsample mode [%s] is not found' % upsample_mode) 28 | if upscale == 3: 29 | upsampler = upsample_block(nf, nf, 3, act_type=act_type) 30 | else: 31 | upsampler = [upsample_block(nf, nf, act_type=act_type) for _ in range(n_upscale)] 32 | HR_conv0 = conv_block(nf, nf, kernel_size=3, norm_type=None, act_type=act_type) 33 | HR_conv1 = conv_block(nf, out_nc, kernel_size=3, norm_type=None, act_type=None) 34 | 35 | self.model = sequential(fea_conv, ShortcutBlock(sequential(*rb_blocks, LR_conv)),\ 36 | *upsampler, HR_conv0, HR_conv1) 37 | 38 | def forward(self, x): 39 | x = self.model(x) 40 | return x -------------------------------------------------------------------------------- /utils/architecture/block.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | import torch 3 | import torch.nn as nn 4 | 5 | #################### 6 | # Basic blocks 7 | #################### 8 | 9 | 10 | def act(act_type, inplace=True, neg_slope=0.2, n_prelu=1): 11 | # helper selecting activation 12 | # neg_slope: for leakyrelu and init of prelu 13 | # n_prelu: for p_relu num_parameters 14 | act_type = act_type.lower() 15 | if act_type == 'relu': 16 | layer = nn.ReLU(inplace) 17 | elif act_type == 'leakyrelu': 18 | layer = nn.LeakyReLU(neg_slope, inplace) 19 | elif act_type == 'prelu': 20 | layer = nn.PReLU(num_parameters=n_prelu, init=neg_slope) 21 | else: 22 | raise NotImplementedError('activation layer [{:s}] is not found'.format(act_type)) 23 | return layer 24 | 25 | 26 | def norm(norm_type, nc): 27 | # helper selecting normalization layer 28 | norm_type = norm_type.lower() 29 | if norm_type == 'batch': 30 | layer = nn.BatchNorm2d(nc, affine=True) 31 | elif norm_type == 'instance': 32 | layer = nn.InstanceNorm2d(nc, affine=False) 33 | else: 34 | raise NotImplementedError('normalization layer [{:s}] is not found'.format(norm_type)) 35 | return layer 36 | 37 | 38 | def pad(pad_type, padding): 39 | # helper selecting padding layer 40 | # if padding is 'zero', do by conv layers 41 | pad_type = pad_type.lower() 42 | if padding == 0: 43 | return None 44 | if pad_type == 'reflect': 45 | layer = nn.ReflectionPad2d(padding) 46 | elif pad_type == 'replicate': 47 | layer = nn.ReplicationPad2d(padding) 48 | else: 49 | raise NotImplementedError('padding layer [{:s}] is not implemented'.format(pad_type)) 50 | return layer 51 | 52 | 53 | def get_valid_padding(kernel_size, dilation): 54 | kernel_size = kernel_size + (kernel_size - 1) * (dilation - 1) 55 | padding = (kernel_size - 1) // 2 56 | return padding 57 | 58 | 59 | class ConcatBlock(nn.Module): 60 | # Concat the output of a submodule to its input 61 | def __init__(self, submodule): 62 | super(ConcatBlock, self).__init__() 63 | self.sub = submodule 64 | 65 | def forward(self, x): 66 | output = torch.cat((x, self.sub(x)), dim=1) 67 | return output 68 | 69 | def __repr__(self): 70 | tmpstr = 'Identity .. \n|' 71 | modstr = self.sub.__repr__().replace('\n', '\n|') 72 | tmpstr = tmpstr + modstr 73 | return tmpstr 74 | 75 | 76 | class ShortcutBlock(nn.Module): 77 | #Elementwise sum the output of a submodule to its input 78 | def __init__(self, submodule): 79 | super(ShortcutBlock, self).__init__() 80 | self.sub = submodule 81 | 82 | def forward(self, x): 83 | output = x + self.sub(x) 84 | return output 85 | 86 | def __repr__(self): 87 | tmpstr = 'Identity + \n|' 88 | modstr = self.sub.__repr__().replace('\n', '\n|') 89 | tmpstr = tmpstr + modstr 90 | return tmpstr 91 | 92 | 93 | class ShortcutBlockSPSR(nn.Module): 94 | #Elementwise sum the output of a submodule to its input 95 | def __init__(self, submodule): 96 | super(ShortcutBlockSPSR, self).__init__() 97 | self.sub = submodule 98 | 99 | def forward(self, x): 100 | return x, self.sub 101 | 102 | def __repr__(self): 103 | tmpstr = 'Identity + \n|' 104 | modstr = self.sub.__repr__().replace('\n', '\n|') 105 | tmpstr = tmpstr + modstr 106 | return tmpstr 107 | 108 | 109 | def sequential(*args): 110 | # Flatten Sequential. It unwraps nn.Sequential. 111 | if len(args) == 1: 112 | if isinstance(args[0], OrderedDict): 113 | raise NotImplementedError('sequential does not support OrderedDict input.') 114 | return args[0] # No sequential is needed. 115 | modules = [] 116 | for module in args: 117 | if isinstance(module, nn.Sequential): 118 | for submodule in module.children(): 119 | modules.append(submodule) 120 | elif isinstance(module, nn.Module): 121 | modules.append(module) 122 | return nn.Sequential(*modules) 123 | 124 | 125 | def conv_block(in_nc, out_nc, kernel_size, stride=1, dilation=1, groups=1, bias=True, \ 126 | pad_type='zero', norm_type=None, act_type='relu', mode='CNA'): 127 | ''' 128 | Conv layer with padding, normalization, activation 129 | mode: CNA --> Conv -> Norm -> Act 130 | NAC --> Norm -> Act --> Conv (Identity Mappings in Deep Residual Networks, ECCV16) 131 | ''' 132 | assert mode in ['CNA', 'NAC', 'CNAC'], 'Wrong conv mode [{:s}]'.format(mode) 133 | padding = get_valid_padding(kernel_size, dilation) 134 | p = pad(pad_type, padding) if pad_type and pad_type != 'zero' else None 135 | padding = padding if pad_type == 'zero' else 0 136 | 137 | c = nn.Conv2d(in_nc, out_nc, kernel_size=kernel_size, stride=stride, padding=padding, \ 138 | dilation=dilation, bias=bias, groups=groups) 139 | a = act(act_type) if act_type else None 140 | if 'CNA' in mode: 141 | n = norm(norm_type, out_nc) if norm_type else None 142 | return sequential(p, c, n, a) 143 | elif mode == 'NAC': 144 | if norm_type is None and act_type is not None: 145 | a = act(act_type, inplace=False) 146 | # Important! 147 | # input----ReLU(inplace)----Conv--+----output 148 | # |________________________| 149 | # inplace ReLU will modify the input, therefore wrong output 150 | n = norm(norm_type, in_nc) if norm_type else None 151 | return sequential(n, a, p, c) 152 | 153 | 154 | #################### 155 | # Useful blocks 156 | #################### 157 | 158 | 159 | class ResNetBlock(nn.Module): 160 | ''' 161 | ResNet Block, 3-3 style 162 | with extra residual scaling used in EDSR 163 | (Enhanced Deep Residual Networks for Single Image Super-Resolution, CVPRW 17) 164 | ''' 165 | 166 | def __init__(self, in_nc, mid_nc, out_nc, kernel_size=3, stride=1, dilation=1, groups=1, \ 167 | bias=True, pad_type='zero', norm_type=None, act_type='relu', mode='CNA', res_scale=1): 168 | super(ResNetBlock, self).__init__() 169 | conv0 = conv_block(in_nc, mid_nc, kernel_size, stride, dilation, groups, bias, pad_type, \ 170 | norm_type, act_type, mode) 171 | if mode == 'CNA': 172 | act_type = None 173 | if mode == 'CNAC': # Residual path: |-CNAC-| 174 | act_type = None 175 | norm_type = None 176 | conv1 = conv_block(mid_nc, out_nc, kernel_size, stride, dilation, groups, bias, pad_type, \ 177 | norm_type, act_type, mode) 178 | # if in_nc != out_nc: 179 | # self.project = conv_block(in_nc, out_nc, 1, stride, dilation, 1, bias, pad_type, \ 180 | # None, None) 181 | # print('Need a projecter in ResNetBlock.') 182 | # else: 183 | # self.project = lambda x:x 184 | self.res = sequential(conv0, conv1) 185 | self.res_scale = res_scale 186 | 187 | def forward(self, x): 188 | res = self.res(x).mul(self.res_scale) 189 | return x + res 190 | 191 | 192 | class ResidualDenseBlock_5C(nn.Module): 193 | ''' 194 | Residual Dense Block 195 | style: 5 convs 196 | The core module of paper: (Residual Dense Network for Image Super-Resolution, CVPR 18) 197 | ''' 198 | 199 | def __init__(self, nc, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \ 200 | norm_type=None, act_type='leakyrelu', mode='CNA'): 201 | super(ResidualDenseBlock_5C, self).__init__() 202 | # gc: growth channel, i.e. intermediate channels 203 | self.conv1 = conv_block(nc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \ 204 | norm_type=norm_type, act_type=act_type, mode=mode) 205 | self.conv2 = conv_block(nc+gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \ 206 | norm_type=norm_type, act_type=act_type, mode=mode) 207 | self.conv3 = conv_block(nc+2*gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \ 208 | norm_type=norm_type, act_type=act_type, mode=mode) 209 | self.conv4 = conv_block(nc+3*gc, gc, kernel_size, stride, bias=bias, pad_type=pad_type, \ 210 | norm_type=norm_type, act_type=act_type, mode=mode) 211 | if mode == 'CNA': 212 | last_act = None 213 | else: 214 | last_act = act_type 215 | self.conv5 = conv_block(nc+4*gc, nc, 3, stride, bias=bias, pad_type=pad_type, \ 216 | norm_type=norm_type, act_type=last_act, mode=mode) 217 | 218 | def forward(self, x): 219 | x1 = self.conv1(x) 220 | x2 = self.conv2(torch.cat((x, x1), 1)) 221 | x3 = self.conv3(torch.cat((x, x1, x2), 1)) 222 | x4 = self.conv4(torch.cat((x, x1, x2, x3), 1)) 223 | x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) 224 | return x5.mul(0.2) + x 225 | 226 | 227 | class RRDB(nn.Module): 228 | ''' 229 | Residual in Residual Dense Block 230 | (ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks) 231 | ''' 232 | 233 | def __init__(self, nc, kernel_size=3, gc=32, stride=1, bias=True, pad_type='zero', \ 234 | norm_type=None, act_type='leakyrelu', mode='CNA'): 235 | super(RRDB, self).__init__() 236 | self.RDB1 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \ 237 | norm_type, act_type, mode) 238 | self.RDB2 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \ 239 | norm_type, act_type, mode) 240 | self.RDB3 = ResidualDenseBlock_5C(nc, kernel_size, gc, stride, bias, pad_type, \ 241 | norm_type, act_type, mode) 242 | 243 | def forward(self, x): 244 | out = self.RDB1(x) 245 | out = self.RDB2(out) 246 | out = self.RDB3(out) 247 | return out.mul(0.2) + x 248 | 249 | 250 | #################### 251 | # Upsampler 252 | #################### 253 | 254 | 255 | def pixelshuffle_block(in_nc, out_nc, upscale_factor=2, kernel_size=3, stride=1, bias=True, \ 256 | pad_type='zero', norm_type=None, act_type='relu'): 257 | ''' 258 | Pixel shuffle layer 259 | (Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional 260 | Neural Network, CVPR17) 261 | ''' 262 | conv = conv_block(in_nc, out_nc * (upscale_factor ** 2), kernel_size, stride, bias=bias, \ 263 | pad_type=pad_type, norm_type=None, act_type=None) 264 | pixel_shuffle = nn.PixelShuffle(upscale_factor) 265 | 266 | n = norm(norm_type, out_nc) if norm_type else None 267 | a = act(act_type) if act_type else None 268 | return sequential(conv, pixel_shuffle, n, a) 269 | 270 | 271 | def upconv_blcok(in_nc, out_nc, upscale_factor=2, kernel_size=3, stride=1, bias=True, \ 272 | pad_type='zero', norm_type=None, act_type='relu', mode='nearest'): 273 | # Up conv 274 | # described in https://distill.pub/2016/deconv-checkerboard/ 275 | upsample = nn.Upsample(scale_factor=upscale_factor, mode=mode) 276 | conv = conv_block(in_nc, out_nc, kernel_size, stride, bias=bias, \ 277 | pad_type=pad_type, norm_type=norm_type, act_type=act_type) 278 | return sequential(upsample, conv) 279 | -------------------------------------------------------------------------------- /utils/imgops.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import math 3 | 4 | def crop_seamless(img): 5 | img_height, img_width = img.shape[:2] 6 | y, x = 16, 16 7 | h, w = img_height - 32, img_width - 32 8 | img = img[y:y+h, x:x+w] 9 | return img 10 | 11 | # from https://github.com/ata4/esrgan-launcher/blob/master/upscale.py 12 | def esrgan_launcher_split_merge(input_image, upscale_function, models, scale_factor=4, tile_size=512, tile_padding=0.125): 13 | width, height, depth = input_image.shape 14 | output_width = width * scale_factor 15 | output_height = height * scale_factor 16 | output_shape = (output_width, output_height, depth) 17 | 18 | # start with black image 19 | output_images = [np.zeros(output_shape, np.uint8) for i in range(len(models))] 20 | 21 | tile_padding = math.ceil(tile_size * tile_padding) 22 | tile_size = math.ceil(tile_size / scale_factor) 23 | 24 | tiles_x = math.ceil(width / tile_size) 25 | tiles_y = math.ceil(height / tile_size) 26 | 27 | for y in range(tiles_y): 28 | for x in range(tiles_x): 29 | # extract tile from input image 30 | ofs_x = x * tile_size 31 | ofs_y = y * tile_size 32 | 33 | # input tile area on total image 34 | input_start_x = ofs_x 35 | input_end_x = min(ofs_x + tile_size, width) 36 | 37 | input_start_y = ofs_y 38 | input_end_y = min(ofs_y + tile_size, height) 39 | 40 | # input tile area on total image with padding 41 | input_start_x_pad = max(input_start_x - tile_padding, 0) 42 | input_end_x_pad = min(input_end_x + tile_padding, width) 43 | 44 | input_start_y_pad = max(input_start_y - tile_padding, 0) 45 | input_end_y_pad = min(input_end_y + tile_padding, height) 46 | 47 | # input tile dimensions 48 | input_tile_width = input_end_x - input_start_x 49 | input_tile_height = input_end_y - input_start_y 50 | 51 | input_tile = input_image[input_start_x_pad:input_end_x_pad, input_start_y_pad:input_end_y_pad] 52 | 53 | for idx, model in enumerate(models): 54 | 55 | # upscale tile 56 | output_tile = upscale_function(input_tile, model) 57 | 58 | # output tile area on total image 59 | output_start_x = input_start_x * scale_factor 60 | output_end_x = input_end_x * scale_factor 61 | 62 | output_start_y = input_start_y * scale_factor 63 | output_end_y = input_end_y * scale_factor 64 | 65 | # output tile area without padding 66 | output_start_x_tile = (input_start_x - input_start_x_pad) * scale_factor 67 | output_end_x_tile = output_start_x_tile + input_tile_width * scale_factor 68 | 69 | output_start_y_tile = (input_start_y - input_start_y_pad) * scale_factor 70 | output_end_y_tile = output_start_y_tile + input_tile_height * scale_factor 71 | 72 | # put tile into output image 73 | output_images[idx][output_start_x:output_end_x, output_start_y:output_end_y] = \ 74 | output_tile[output_start_x_tile:output_end_x_tile, output_start_y_tile:output_end_y_tile] 75 | 76 | return output_images -------------------------------------------------------------------------------- /utils/models/1x_FrankenMapGenerator-CX-Lite_215000_G.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YahiaAngelo/MaterialMapGenerator/74d510811213e86d76bc6795401ca3d07703cd5d/utils/models/1x_FrankenMapGenerator-CX-Lite_215000_G.pth -------------------------------------------------------------------------------- /utils/models/1x_NormalMapGenerator-CX-Lite_200000_G.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YahiaAngelo/MaterialMapGenerator/74d510811213e86d76bc6795401ca3d07703cd5d/utils/models/1x_NormalMapGenerator-CX-Lite_200000_G.pth --------------------------------------------------------------------------------