├── 4lph4bet_calligraphr_template.png ├── LICENSE ├── README.md ├── process_4lph4bet_grid_image.py └── requirements.txt /4lph4bet_calligraphr_template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/414design/4lph4bet_processor/1b6596756b385045c0e6f6c3e2d395c3232a9ad3/4lph4bet_calligraphr_template.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | including for purposes of Section 3(b); and 307 | 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public 411 | licenses. Notwithstanding, Creative Commons may elect to apply one of 412 | its public licenses to material it publishes and in those instances 413 | will be considered the “Licensor.” The text of the Creative Commons 414 | public licenses is dedicated to the public domain under the CC0 Public 415 | Domain Dedication. Except for the limited purpose of indicating that 416 | material is shared under a Creative Commons public license or as 417 | otherwise permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the 425 | public licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. 428 | 429 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 4lph4bet Processor 2 | 3 | This scripty processes a grid image generated with the [4lph4bet family of LoRAs](https://huggingface.co/collections/414design/4lph4bet-lora-collection-6679647c1ce38cec234e8204) for Stable Diffusion 1.5 for font creation using [Calligraphr](https://www.calligraphr.com/). The script `process_4lph4bet_grid_image.py` performs the following tasks: 4 | 5 | 1. Resizes the input grid image if necessary. 6 | 2. Converts the image to grayscale and applies Canny edge detection. 7 | 3. Finds and merges contours. 8 | 4. Extracts individual images from the grid, inverts colors, and saves them with a transparent background. 9 | 5. Places the extracted images onto a template for [Calligraphr](https://www.calligraphr.com/) and saves all processed glyphs individually. 10 | 11 | ## Files 12 | 13 | - `process_4lph4bet_grid_image.py`: The main script for processing the grid image. 14 | - `4lph4bet_calligraphr_template.png`: The template image onto which the extracted images are placed. 15 | - `requirements.txt`: A list of dependencies required to run the script. 16 | - `README.md`: Information on how to use the script. 17 | - `LICENSE`: License inforamtion. 18 | 19 | ## Setup Instructions 20 | 21 | ### Prerequisites 22 | 23 | - Python 3.6 or higher 24 | 25 | ### Download and Extract the Package 26 | 27 | Download the `4lph4bet_processor` folder or clone the repository. 28 | 29 | ### Setting Up the Environment 30 | 31 | 1. Open a terminal or command prompt and navigate to the extracted directory (`4lph4bet_processor`). 32 | 33 | 2. Set up a virtual environment (optional but recommended): 34 | 35 | ```bash 36 | python -m venv env 37 | ``` 38 | 39 | 3. Activate the virtual environment: 40 | 41 | - On Windows: 42 | 43 | ```bash 44 | .\env\Scripts\activate 45 | ``` 46 | 47 | - On macOS and Linux: 48 | 49 | ```bash 50 | source env/bin/activate 51 | ``` 52 | 53 | 4. Install the required packages: 54 | 55 | ```bash 56 | pip install -r requirements.txt 57 | ``` 58 | 59 | 60 | ### Running the Script 61 | 62 | Use the following command to run the script: 63 | 64 | ```bash 65 | python process_4lph4bet_grid_image.py 66 | ``` 67 | 68 | The script will ask for the absolute path to your grid image. Provide the path and press Enter. 69 | 70 | ### Recommended Image Size 71 | 72 | It is recommended (but not necessary) to upscale the grid image to 4096 by 4096 pixels for better processing results. 73 | 74 | ## Output 75 | 76 | The script will save the processed images in an `[input_filename]_intermediate_outputs` directory. This folder as well as the final processed image with a timestamp will be saved in the same directory as the input grid image. The isolated glyphs will be saved in the folder for further processing if needed. 77 | 78 | ## Notes 79 | 80 | - Ensure that the `4lph4bet_preset.png` file is in the same directory as the script. 81 | - If you encounter any issues, please ensure you have the correct versions of the required packages as listed in `requirements.txt`. 82 | - Further post processing like kerning or baseline offset might be required in Calligraphr. 83 | - The free version of Calligraphy only allows 75 characters to be exported as a font so in this case the character set needs to be reduced before export. 84 | 85 | ## License 86 | 87 | This LoRA is provided under a `CC BY-SA 4.0` license. 88 | -------------------------------------------------------------------------------- /process_4lph4bet_grid_image.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from PIL import Image, ImageDraw 4 | import os 5 | from datetime import datetime 6 | 7 | # Constants for grid cell padding 8 | top_padding = 50 9 | left_padding = 80 10 | right_padding = 120 11 | bottom_padding = 40 12 | num_rows = 10 13 | num_cols = 9 14 | 15 | # Threshold for setting background transparency 16 | transparency_threshold = 200 17 | 18 | # Function to resize and save intermediate images 19 | def save_resized_image(img, path, size=(1024, 1024)): 20 | resized_img = cv2.resize(img, size) 21 | cv2.imwrite(path, resized_img) 22 | 23 | # Function to convert white pixels to transparency with gradient 24 | def white_to_transparency_gradient(img, transparency_threshold): 25 | x = np.asarray(img.convert('RGBA')).copy() 26 | avg_intensity = x[:, :, :3].mean(axis=2) 27 | transparency = (255 - avg_intensity).astype(np.uint8) 28 | transparency[transparency < transparency_threshold] = 0 29 | x[:, :, 3] = transparency 30 | return Image.fromarray(x) 31 | 32 | # Function to check if two rectangles overlap with padding 33 | def rectangles_overlap(r1, r2, padding): 34 | (x1, y1, w1, h1) = r1 35 | (x2, y2, w2, h2) = r2 36 | return not (x1 + w1 + padding < x2 or x2 + w2 + padding < x1 or 37 | y1 + h1 + padding < y2 or y2 + h2 + padding < y1) 38 | 39 | # Ask user for input image path 40 | input_path = input("Enter the absolute path to your grid image: ").strip('"') 41 | 42 | # Load the image 43 | img = cv2.imread(input_path) 44 | 45 | # Check if the image was loaded successfully 46 | if img is None: 47 | raise FileNotFoundError(f"Image not found at {input_path}") 48 | 49 | # Check and resize the image to 4096x4096 pixels 50 | height, width, _ = img.shape 51 | if height != 4096 or width != 4096: 52 | img = cv2.resize(img, (4096, 4096)) 53 | 54 | # Extract the filename from the input path 55 | filename = os.path.basename(input_path) 56 | filename_without_extension = os.path.splitext(filename)[0] 57 | 58 | # Prepare directory for intermediate outputs 59 | output_dir = os.path.join(os.path.dirname(input_path), f'{filename_without_extension}_intermediate_outputs') 60 | os.makedirs(output_dir, exist_ok=True) 61 | 62 | # Convert the image to grayscale 63 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 64 | 65 | # Save intermediate edges image 66 | edges = cv2.Canny(gray, 50, 150) # Adjusted thresholds 67 | save_resized_image(edges, os.path.join(output_dir, 'edges_resized.png')) 68 | 69 | # Find contours 70 | contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Using RETR_TREE 71 | 72 | # Sort contours by their area in descending order 73 | contours = sorted(contours, key=cv2.contourArea, reverse=True) 74 | 75 | # Save intermediate contours image 76 | img_with_contours = img.copy() 77 | cv2.drawContours(img_with_contours, contours, -1, (0, 255, 0), 2) 78 | save_resized_image(img_with_contours, os.path.join(output_dir, 'contours_resized.png')) 79 | 80 | # Calculate grid cell dimensions 81 | cell_width = (img.shape[1] - left_padding - right_padding) // num_cols 82 | cell_height = (img.shape[0] - top_padding - bottom_padding) // num_rows 83 | 84 | # Function to calculate grid cell centers with padding 85 | def calculate_grid_centers(): 86 | grid_centers = {} 87 | for row in range(num_rows): 88 | for col in range(num_cols): 89 | center_x = left_padding + col * cell_width + cell_width // 2 90 | center_y = top_padding + row * cell_height + cell_height // 2 91 | grid_centers[(row, col)] = (center_x, center_y) 92 | return grid_centers 93 | 94 | # Calculate grid cell centers 95 | grid_centers = calculate_grid_centers() 96 | 97 | # Assign contours to grid cells based on proximity to center 98 | contours_assigned = {key: [] for key in grid_centers.keys()} 99 | for contour in contours: 100 | x, y, w, h = cv2.boundingRect(contour) 101 | contour_center_x = x + w // 2 102 | contour_center_y = y + h // 2 103 | 104 | min_distance = float('inf') 105 | closest_cell = None 106 | for grid_cell, (center_x, center_y) in grid_centers.items(): 107 | distance = np.sqrt((contour_center_x - center_x) ** 2 + (contour_center_y - center_y) ** 2) 108 | if distance < min_distance: 109 | min_distance = distance 110 | closest_cell = grid_cell 111 | 112 | contours_assigned[closest_cell].append(contour) 113 | 114 | # Merge contours in each grid cell 115 | merged_contours = [] 116 | for grid_cell, cell_contours in contours_assigned.items(): 117 | if len(cell_contours) == 0: 118 | continue 119 | 120 | if len(cell_contours) == 1: 121 | merged_contours.append(cell_contours[0]) 122 | continue 123 | 124 | # Merge contours in this cell 125 | merged_contour = np.concatenate(cell_contours) 126 | merged_contours.append(merged_contour) 127 | 128 | # Save intermediate merged contours image 129 | for idx, contour in enumerate(merged_contours): 130 | x, y, w, h = cv2.boundingRect(contour) 131 | cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) 132 | cv2.imwrite(os.path.join(output_dir, 'output_with_rectangles.png'), img) 133 | 134 | # Save sorted glyph images 135 | for idx, contour in enumerate(merged_contours): 136 | x, y, w, h = cv2.boundingRect(contour) 137 | roi = img[y:y+h, x:x+w] 138 | roi_inverted = cv2.bitwise_not(roi) 139 | bordered_image = cv2.copyMakeBorder(roi_inverted, 20, 20, 20, 20, cv2.BORDER_CONSTANT, value=[255, 255, 255]) 140 | bordered_image_rgb = cv2.cvtColor(bordered_image, cv2.COLOR_BGR2RGB) 141 | bordered_pil_image = Image.fromarray(bordered_image_rgb) 142 | bordered_pil_image_transparent = white_to_transparency_gradient(bordered_pil_image, transparency_threshold) 143 | bordered_pil_image_transparent.save(os.path.join(output_dir, f'letter_{idx}.png')) 144 | 145 | # Load the template image 146 | template_path = '4lph4bet_calligraphr_template.png' 147 | template = Image.open(template_path) 148 | 149 | # Define the coordinates for each glyph 150 | glyph_centers = { 151 | 'letter_0': (335, 675), 152 | 'letter_1': (820, 675), 153 | 'letter_2': (1300, 670), 154 | 'letter_3': (1780, 570), 155 | 'letter_4': (2250, 695), 156 | 'letter_5': (2730, 695), 157 | 'letter_6': (3225, 770), 158 | 'letter_7': (340, 1300), 159 | 'letter_8': (820, 1380), 160 | 'letter_9': (1300, 1285), 161 | 'letter_10': (1785, 1285), 162 | 'letter_11': (2270, 1285), 163 | 'letter_12': (2735, 1285), 164 | 'letter_13': (3220, 1285), 165 | 'letter_14': (335, 1900), 166 | 'letter_15': (815, 1900), 167 | 'letter_16': (1300, 1900), 168 | 'letter_17': (1780, 1900), 169 | 'letter_18': (2260, 1900), 170 | 'letter_19': (2745, 1900), 171 | 'letter_20': (3220, 1930), 172 | 'letter_21': (340, 2535), 173 | 'letter_22': (820, 2535), 174 | 'letter_23': (1300, 2535), 175 | 'letter_24': (1780, 2535), 176 | 'letter_25': (2260, 2535), 177 | 'letter_26': (2745, 2535), 178 | 'letter_27': (3220, 2535), 179 | 'letter_28': (3700, 2535), 180 | 'letter_29': (4190, 2535), 181 | 'letter_30': (4660, 2535), 182 | 'letter_31': (340, 3155), 183 | 'letter_32': (820, 3155), 184 | 'letter_33': (1300, 3155), 185 | 'letter_34': (1780, 3155), 186 | 'letter_35': (2260, 3155), 187 | 'letter_36': (2745, 3155), 188 | 'letter_37': (3220, 3155), 189 | 'letter_38': (3700, 3155), 190 | 'letter_39': (4190, 3155), 191 | 'letter_40': (4660, 3155), 192 | 'letter_41': (340, 3775), 193 | 'letter_42': (820, 3775), 194 | 'letter_43': (1300, 3775), 195 | 'letter_44': (1780, 3775), 196 | 'letter_45': (2260, 3775), 197 | 'letter_46': (2745, 3775), 198 | 'letter_47': (3220, 3775), 199 | 'letter_48': (3700, 3775), 200 | 'letter_49': (4190, 3775), 201 | 'letter_50': (4660, 3775), 202 | 'letter_51': (340, 4430), 203 | 'letter_52': (820, 4400), 204 | 'letter_53': (1300, 4430), 205 | 'letter_54': (1780, 4400), 206 | 'letter_55': (2260, 4460), 207 | 'letter_56': (2745, 4400), 208 | 'letter_57': (3220, 4400), 209 | 'letter_58': (3700, 4460), 210 | 'letter_59': (4190, 4400), 211 | 'letter_60': (4660, 4400), 212 | 'letter_61': (340, 5050), 213 | 'letter_62': (820, 5050), 214 | 'letter_63': (1300, 5050), 215 | 'letter_64': (1780, 5075), 216 | 'letter_65': (2260, 5075), 217 | 'letter_66': (2745, 5050), 218 | 'letter_67': (3220, 5050), 219 | 'letter_68': (3700, 5035), 220 | 'letter_69': (4190, 5050), 221 | 'letter_70': (4660, 5050), 222 | 'letter_71': (340, 5675), 223 | 'letter_72': (820, 5675), 224 | 'letter_73': (1300, 5700), 225 | 'letter_74': (1780, 5675), 226 | 'letter_75': (2260, 5675), 227 | 'letter_76': (2745, 5675), 228 | 'letter_77': (3220, 5635), 229 | 'letter_78': (3700, 5635), 230 | 'letter_79': (4190, 5635), 231 | 'letter_80': (4660, 5650), 232 | 'letter_81': (340, 6280), 233 | 'letter_82': (820, 6280), 234 | 'letter_83': (1300, 6280), 235 | 'letter_84': (1780, 6200), 236 | 'letter_85': (2260, 6275), 237 | 'letter_86': (2745, 6275), 238 | 'letter_87': (3220, 6275), 239 | } 240 | 241 | # Create a new image to paste the processed glyphs 242 | result_image = template.copy() 243 | 244 | # Sort glyph centers by index 245 | sorted_glyph_centers = sorted(glyph_centers.items(), key=lambda x: int(x[0].split('_')[1])) 246 | 247 | # Paste each glyph into the template in the correct order 248 | for idx, (letter_key, (center_x, center_y)) in enumerate(sorted_glyph_centers): 249 | glyph_image_path = os.path.join(output_dir, f'letter_{idx}.png') 250 | if os.path.exists(glyph_image_path): 251 | glyph_image = Image.open(glyph_image_path) 252 | glyph_w, glyph_h = glyph_image.size 253 | position = (center_x - glyph_w // 2, center_y - glyph_h // 2) 254 | result_image.paste(glyph_image, position, glyph_image) 255 | 256 | # Save the final result with a timestamp 257 | timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') 258 | final_output_path = os.path.join(os.path.dirname(input_path), f'{filename_without_extension}_processed_grid_{timestamp}.png') 259 | result_image.save(final_output_path) 260 | 261 | print(f"Processed image saved as {final_output_path}") 262 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | opencv-python 3 | pillow 4 | --------------------------------------------------------------------------------