├── .github └── workflows │ └── publish_action.yml ├── LICENSE ├── README.md ├── README_CN.md ├── __init__.py ├── examples ├── Route_Selection.png ├── batch_workflow.png └── single_workflow.png ├── flow_control.py ├── mask_split.py ├── pyproject.toml ├── requirements.txt ├── tools.py └── web └── node └── dynamicnode.js /.github/workflows/publish_action.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | paths: 8 | - "pyproject.toml" 9 | 10 | permissions: 11 | issues: write 12 | 13 | jobs: 14 | publish-node: 15 | name: Publish Custom Node to registry 16 | runs-on: ubuntu-latest 17 | if: ${{ github.repository_owner == 'WainWong' }} 18 | steps: 19 | - name: Check out code 20 | uses: actions/checkout@v4 21 | - name: Publish Custom Node 22 | uses: Comfy-Org/publish-node-action@v1 23 | with: 24 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI Loop Image 2 | 3 | [English](README.md) | [简体中文](README_CN.md) 4 | 5 | --- 6 | ## Latest Update (2025-01-25) 7 | Enhanced the batch processing capabilities with a new feedback loop feature: 8 | - Added `pass_back` option in BatchImageLoopClose to enable passing processed images back to the loop start 9 | - BatchImageLoopOpen now automatically expands single images to match mask batch size 10 | 11 | 12 | ## Update (2025-01-19) 13 | Added a new route selection workflow example demonstrating advanced Loop Index Switch usage. Located in "examples/Route_Selection", this workflow showcases path selection based on iteration count using lazy loading features: 14 | - First iteration (0): Executes Flux Redux workflow 15 | - Second iteration (1): Executes Flux Pulid workflow 16 | 17 | See example files for detailed implementation. 18 | 19 | --- 20 | 21 | ## Introduction 22 | ComfyUI Loop Image is a node package specifically designed for image loop processing. It provides two main processing modes: Batch Image Processing and Single Image Processing, along with supporting image segmentation and merging functions. 23 | 24 | ## Differences between Batch and Single Processing 25 | 26 | ### Batch Image Processing 27 | - Suitable for scenarios requiring simultaneous processing of multiple different regions 28 | - Uses Mask Segmentation node to divide images into multiple parts 29 | - Processes one segmented region per iteration 30 | - Merges results through Mask Merge after all regions are processed 31 | 32 | ### Single Image Processing 33 | - Suitable for scenarios requiring multiple processing passes on the same image 34 | - Uses the result of the previous iteration as input for the next 35 | - Enables progressive image modification 36 | - Ideal for iterative optimization tasks 37 | 38 | ## Node Documentation 39 | 40 | ### 1. Batch Processing Nodes 41 | 42 | #### Mask Segmentation🐰 43 | - **Functionality** 44 | - Automatically segments a mask containing multiple independent regions into separate mask sequences 45 | - Each segmented mask corresponds to an independent region in the original image 46 | - Segmentation based on connected component analysis 47 | 48 | - **Segmentation Rules** 49 | - Independent regions are identified as separate parts 50 | - Regions with holes are properly processed, maintaining hole structure 51 | 52 | - **Sequence Rules** 53 | - Masks are arranged from left to right, then top to bottom 54 | - Sorting based on leftmost pixel position, then topmost pixel position 55 | - This order determines subsequent processing sequence 56 | - Example: In a mask with three regions, leftmost region is iteration 0, middle is 1, rightmost is 2 57 | 58 | #### Batch Image Loop Open🐰 59 | - **Input/Output Details** 60 | - Inputs: 61 | - segmented_images: Image sequence from Mask Segmentation 62 | - segmented_masks: Mask sequence from Mask Segmentation 63 | - Outputs: 64 | - current_image: Currently processed image portion 65 | - current_mask: Current iteration mask 66 | - max_iterations: Total iteration count (equals number of segmented regions) 67 | - iteration_count: Current iteration number (starts from 0) 68 | 69 | - **Usage Notes** 70 | - current_image and current_mask can be used directly for subsequent processing 71 | - iteration_count can connect to Loop Index Switch for different processing parameters 72 | - max_iterations used for loop control, usually doesn't need manual handling 73 | 74 | #### Batch Image Loop Close🐰 75 | - **Input/Output Details** 76 | - Inputs: 77 | - flow_control: Control signal from Loop Open 78 | - current_image: Currently processed image 79 | - current_mask: Current processed mask 80 | - max_iterations: Total iteration count from Loop Open 81 | - Outputs: 82 | - result_images: All processed image sequences 83 | - result_masks: All processed mask sequences 84 | 85 | #### Mask Merge🐰 86 | - **Functionality** 87 | - Merges multiple processed image regions back into the original image 88 | - Uses masks to ensure each processed region is correctly placed 89 | - Maintains original content in unprocessed areas 90 | 91 | - **Usage Tips** 92 | - original_image: Use original input image 93 | - processed_images: Connect to result_images output from Loop Close 94 | - masks: Connect to result_masks output from Loop Close 95 | 96 | This batch processing system allows you to apply different processing methods to different regions of an image, particularly suitable for scenarios requiring differentiated processing of various image parts. 97 | 98 | ### 2. Single Image Processing Nodes 99 | 100 | #### Single Image Loop Open🐰 101 | - **Functionality** 102 | - Performs multiple iterations of processing on a single image 103 | - Uses the result of each iteration as input for the next 104 | - Suitable for progressive enhancement or multiple optimization scenarios 105 | 106 | - **Input Parameters** 107 | - **Required Inputs**: 108 | - image: Original image to process 109 | - max_iterations: Maximum iteration count (1-100) 110 | - **Optional Inputs**: 111 | - mask: Optional processing area mask 112 | 113 | - **Output Parameters** 114 | - current_image: Current iteration image (original image for first iteration, previous result for subsequent iterations) 115 | - current_mask: Current mask (if provided) 116 | - max_iterations: Set maximum iterations 117 | - iteration_count: Current iteration number (starts from 0) 118 | 119 | #### Single Image Loop Close🐰 120 | - **Input Parameters** 121 | - **Required Inputs**: 122 | - flow_control: Control signal from Loop Open 123 | - current_image: Currently processed image 124 | - max_iterations: Maximum iterations from Loop Open 125 | - **Optional Inputs**: 126 | - current_mask: Processed mask (if using mask) 127 | 128 | - **Output Parameters** 129 | - final_image: Final image after all iterations 130 | - final_mask: Final mask (if using mask) 131 | 132 | #### Single Image Processing Features and Applications 133 | 1. **Progressive Processing** 134 | - Each iteration builds on previous results 135 | - Enables cumulative effects 136 | - Suitable for scenarios requiring fine-tuning 137 | 138 | 2. **Use Case Examples** 139 | - Progressive image enhancement 140 | - Iterative style transfer 141 | - Multiple denoising passes 142 | - Gradual detail optimization 143 | 144 | ### 3. Special Function Node 145 | - **Loop Index Switch🐰** 146 | - Function: Select different inputs based on current iteration count 147 | - Usage: 148 | 1. Right-click node and select "Add Loop Input" 149 | 2. Enter desired iteration number (0-99) 150 | 3. Connect corresponding inputs 151 | 4. Use "Remove Loop Input" to delete unwanted inputs 152 | - Note: Only inputs corresponding to current iteration are computed, others are skipped for efficiency 153 | 154 | ## Usage Recommendations 155 | 1. Use batch processing for scenarios requiring different processing in different image regions 156 | 2. Use single image processing for scenarios requiring multiple optimization iterations 157 | 3. Utilize Loop Index Switch to implement different parameters for different iterations 158 | 4. Control iteration count to avoid over-processing 159 | 160 | ## Example Workflows 161 | 162 | **Batch Processing Workflow** 163 | 164 | ![Batch Processing Workflow](examples/batch_workflow.png) 165 | 166 | **Single Processing Workflow** 167 | 168 | ![Single Processing Workflow](examples/single_workflow.png) 169 | 170 | ## Acknowledgments 171 | This project references the following excellent open source projects: 172 | - [ComfyUI-Easy-Use](https://github.com/yolain/ComfyUI-Easy-Use/) - Provided excellent node design ideas and implementation references 173 | - [execution-inversion-demo-comfyui](https://github.com/BadCafeCode/execution-inversion-demo-comfyui) - Provided core implementation ideas for loop control 174 | - [cozy_ex_dynamic](https://github.com/cozy-comfyui/cozy_ex_dynamic) - Provided implementation reference for dynamic input nodes 175 | 176 | Special thanks to the authors of these projects for their contributions to the ComfyUI community! 177 | 178 | ## About 179 | For more ComfyUI tutorials and updates, visit: 180 | - Bilibili: [CyberEve](https://space.bilibili.com/16993154) 181 | - Content includes: 182 | - ComfyUI node development tutorials 183 | - Workflow usage tutorials 184 | - Latest feature updates 185 | - AI drawing tips 186 | 187 | If you find this project helpful, please follow the author's Bilibili account for more resources! 188 | 189 | --- 190 | 191 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | # ComfyUI Loop Image 2 | 3 | [English](README.md) | [简体中文](README_CN.md) 4 | 5 | --- 6 | ## 最新更新 (2025-01-25) 7 | 增强了批处理功能,新增图像反馈循环特性: 8 | - 在BatchImageLoopClose中添加了`pass_back`选项,支持将处理后的图片传回循环开始处 9 | - BatchImageLoopOpen现可自动将单张图片扩展至与蒙版批次相同大小 10 | 11 | 12 | ## 更新 (2025-01-19) 13 | 新增路径选择示例工作流,展示了Loop Index Switch的高级用法。该示例位于"examples/Route_Selection",通过懒加载特性实现基于迭代次数的路径选择: 14 | - 第一次迭代(0):执行Flux Redux工作流 15 | - 第二次迭代(1):执行Flux Pulid工作流 16 | 17 | 详细实现请查看示例文件。 18 | 19 | --- 20 | 21 | ## 简介 22 | ComfyUI Loop Image是一个专门用于处理图像循环操作的节点包。它提供了两种主要的循环处理模式:批量图像处理(Batch)和单图像重复处理(Single),以及配套的图像分割与合并功能。 23 | 24 | 25 | ## 批量处理与单图处理的区别 26 | 27 | ### 批量图像处理 28 | - 适用于需要同时处理多个不同区域的场景 29 | - 通过Mask Segmentation节点将图像分割成多个部分 30 | - 每次循环处理一个分割区域 31 | - 所有区域处理完成后通过Mask Merge合并结果 32 | 33 | ### 单图像处理 34 | - 适用于需要对同一图像进行多次处理的场景 35 | - 每次循环使用上一次的处理结果作为输入 36 | - 可以实现渐进式的图像修改 37 | - 适合迭代优化类的任务 38 | 39 | 40 | ## 节点说明 41 | 42 | 43 | ### 1. 批量处理节点详解 44 | 45 | 46 | #### Mask Segmentation🐰 (遮罩分割) 47 | - **功能说明** 48 | - 将一个包含多个独立区域的遮罩图自动分割成独立的遮罩序列 49 | - 每个分割后的遮罩对应原图中的一个独立区域 50 | - 分割基于连通区域分析,即相互不连接的区域会被分为不同部分 51 | 52 | - **分割规则** 53 | - 相互独立的区域会被识别为不同的部分 54 | - 包含孔洞的区域会被正确处理,保持孔洞结构 55 | 56 | - **顺序规则** 57 | - 分割后的遮罩按照从左到右排列,若左右位置相等,再按照从上到下的顺序 58 | - 排序依据是每个区域最左边的像素点的位置,再按照最上边的像素点的位置 59 | - 这个顺序决定了后续循环处理的顺序 60 | - 例如:如果遮罩中有三个区域,最左边的区域将是第0次迭代,中间的是第1次,最右边的是第2次 61 | 62 | 63 | #### Batch Image Loop Open🐰 (批量循环开始) 64 | - **输入输出详解** 65 | - 输入: 66 | - segmented_images: 来自Mask Segmentation的图像序列 67 | - segmented_masks: 来自Mask Segmentation的遮罩序列 68 | - 输出: 69 | - current_image: 当前迭代处理的图像部分 70 | - current_mask: 当前迭代的遮罩 71 | - max_iterations: 总迭代次数(等于分割区域的数量) 72 | - iteration_count: 当前迭代次数(从0开始) 73 | 74 | - **使用说明** 75 | - current_image和current_mask可以直接用于后续处理 76 | - iteration_count可以连接到Loop Index Switch来选择不同的处理参数 77 | - max_iterations用于循环控制,一般不需要手动使用 78 | 79 | 80 | #### Batch Image Loop Close🐰 (批量循环结束) 81 | - **输入输出详解** 82 | - 输入: 83 | - flow_control: 来自Loop Open的控制信号 84 | - current_image: 处理后的当前图像 85 | - current_mask: 处理后的当前遮罩 86 | - max_iterations: 来自Loop Open的总迭代次数 87 | - 输出: 88 | - result_images: 所有处理完成的图像序列 89 | - result_masks: 所有处理完成的遮罩序列 90 | 91 | 92 | #### Mask Merge🐰 (遮罩合并) 93 | - **功能说明** 94 | - 将循环处理后的多个图像区域合并回原始图像 95 | - 使用遮罩确保每个处理过的区域正确放回原位 96 | - 保持未处理区域的原始内容不变 97 | 98 | - **使用技巧** 99 | - original_image: 使用原始输入图像 100 | - processed_images: 连接Loop Close的result_images输出 101 | - masks: 连接Loop Close的result_masks输出 102 | 103 | 这样的批量处理系统允许你对图像的不同区域应用不同的处理方法,特别适合需要对图像不同部分进行差异化处理的场景。 104 | 105 | 106 | ### 2. 单图处理节点详解 107 | 108 | #### Single Image Loop Open🐰 (单图循环开始) 109 | - **功能说明** 110 | - 对同一张图像进行多次迭代处理 111 | - 每次迭代都使用上一次的处理结果作为输入 112 | - 适合需要渐进式改善或多次优化的场景 113 | 114 | - **输入参数详解** 115 | - **必需输入**: 116 | - image: 需要处理的原始图像 117 | - max_iterations: 最大迭代次数(1-100) 118 | - **可选输入**: 119 | - mask: 可选的处理区域遮罩 120 | 121 | - **输出参数详解** 122 | - current_image: 当前迭代的图像(第一次是原始图像,之后是上一次处理的结果) 123 | - current_mask: 当前使用的遮罩(如果提供了遮罩) 124 | - max_iterations: 设定的最大迭代次数 125 | - iteration_count: 当前迭代次数(从0开始) 126 | 127 | 128 | #### Single Image Loop Close🐰 (单图循环结束) 129 | - **输入参数详解** 130 | - **必需输入**: 131 | - flow_control: 来自Loop Open的控制信号 132 | - current_image: 当前迭代处理后的图像 133 | - max_iterations: 来自Loop Open的最大迭代次数 134 | - **可选输入**: 135 | - current_mask: 处理后的遮罩(如果使用了遮罩) 136 | 137 | - **输出参数详解** 138 | - final_image: 所有迭代完成后的最终图像 139 | - final_mask: 最终的遮罩(如果使用了遮罩) 140 | 141 | 142 | #### 单图处理的特点和应用场景 143 | 1. **渐进式处理** 144 | - 每次迭代都基于上一次的结果 145 | - 可以实现累积效果 146 | - 适合需要多次微调的场景 147 | 148 | 2. **使用场景示例** 149 | - 图像渐进式增强 150 | - 迭代式风格转换 151 | - 多次降噪处理 152 | - 逐步细节优化 153 | 154 | 155 | ### 与Loop Index Switch的配合使用 156 | - 可以使用Loop Index Switch根据iteration_count选择不同的处理参数 157 | 158 | 这种单图循环处理方式特别适合需要精细调整或渐进式改善的场景,通过多次迭代可以达到更理想的处理效果。配合Loop Index Switch,还可以实现更复杂的参数控制策略。 159 | 160 | 161 | ### 3. 特殊功能节点 162 | - **Loop Index Switch🐰** 163 | - 功能:根据当前循环次数选择不同的输入 164 | - 使用方法: 165 | 1. 右键点击节点选择"Add Loop Input" 166 | 2. 输入想要添加的循环序号(0-99) 167 | 3. 连接对应的输入 168 | 4. 可以通过"Remove Loop Input"删除不需要的输入 169 | - 注意:只有当前迭代次数对应的输入会被计算,其他输入会被跳过,提高效率 170 | 171 | 172 | ## 使用建议 173 | 1. 批量处理适合需要在图像不同区域应用不同处理的场景 174 | 2. 单图处理适合需要多次迭代优化的场景 175 | 3. 合理使用Loop Index Switch节点可以实现在不同迭代次数使用不同参数 176 | 4. 注意控制循环次数,避免过度处理 177 | 178 | 179 | ## 示例工作流 180 | 181 | **批量图片工作流** 182 | 183 | ![Batch Processing Workflow](examples/batch_workflow.png) 184 | 185 | **单图片工作流** 186 | 187 | ![Single Processing Workflow](examples/single_workflow.png) 188 | 189 | 190 | ## 致谢 191 | 192 | 本项目在开发过程中参考和借鉴了以下优秀的开源项目: 193 | 194 | - [ComfyUI-Easy-Use](https://github.com/yolain/ComfyUI-Easy-Use/) - 提供了优秀的节点设计思路和实现参考 195 | - [execution-inversion-demo-comfyui](https://github.com/BadCafeCode/execution-inversion-demo-comfyui) - 提供了循环控制的核心实现思路 196 | - [cozy_ex_dynamic](https://github.com/cozy-comfyui/cozy_ex_dynamic) - 提供了动态输入节点的实现参考 197 | 198 | 特别感谢这些项目的作者们为ComfyUI社区做出的贡献! 199 | 200 | 201 | ## 关于作者 202 | 203 | 欢迎访问作者的B站主页,获取更多ComfyUI教程和更新: 204 | - B站:[CyberEve](https://space.bilibili.com/16993154) 205 | - 内容包括: 206 | - ComfyUI节点开发教程 207 | - 工作流使用教程 208 | - 最新功能更新介绍 209 | - AI绘画技巧分享 210 | 211 | 如果您觉得这个项目对您有帮助,欢迎关注作者B站账号获取更多资源! 212 | 213 | --- 214 | 215 | *Note: 本项目遵循开源协议,欢迎提出建议和改进意见。* -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .flow_control import CyberEve_Loop_CLASS_MAPPINGS, CyberEve_Loop_DISPLAY_NAME_MAPPINGS 2 | from .mask_split import Mask_CLASS_MAPPINGS, Mask_DISPLAY_NAME_MAPPINGS 3 | 4 | WEB_DIRECTORY = "./web" 5 | NODE_CLASS_MAPPINGS = {} 6 | NODE_CLASS_MAPPINGS.update(CyberEve_Loop_CLASS_MAPPINGS) 7 | NODE_CLASS_MAPPINGS.update(Mask_CLASS_MAPPINGS) 8 | 9 | NODE_DISPLAY_NAME_MAPPINGS = {} 10 | NODE_DISPLAY_NAME_MAPPINGS.update(CyberEve_Loop_DISPLAY_NAME_MAPPINGS) 11 | NODE_DISPLAY_NAME_MAPPINGS.update(Mask_DISPLAY_NAME_MAPPINGS) 12 | 13 | 14 | -------------------------------------------------------------------------------- /examples/Route_Selection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WainWong/ComfyUI-Loop-image/2e0153ba950c5b723062209d9aff8c0aba23a88e/examples/Route_Selection.png -------------------------------------------------------------------------------- /examples/batch_workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WainWong/ComfyUI-Loop-image/2e0153ba950c5b723062209d9aff8c0aba23a88e/examples/batch_workflow.png -------------------------------------------------------------------------------- /examples/single_workflow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WainWong/ComfyUI-Loop-image/2e0153ba950c5b723062209d9aff8c0aba23a88e/examples/single_workflow.png -------------------------------------------------------------------------------- /flow_control.py: -------------------------------------------------------------------------------- 1 | from comfy_execution.graph_utils import GraphBuilder, is_link 2 | from .tools import VariantSupport 3 | import torch.nn.functional as F 4 | import torch 5 | from nodes import NODE_CLASS_MAPPINGS as ALL_NODE_CLASS_MAPPINGS 6 | 7 | @VariantSupport() 8 | class BatchImageLoopOpen: 9 | def __init__(self): 10 | pass 11 | 12 | @classmethod 13 | def INPUT_TYPES(cls): 14 | inputs = { 15 | "required": { 16 | "segmented_images": ("IMAGE", {"forceInput": True}), 17 | "segmented_masks": ("MASK", {"forceInput": True}), 18 | }, 19 | "hidden": { 20 | "unique_id": "UNIQUE_ID", 21 | "iteration_count": ("INT", {"default": 0}), 22 | "previous_image": ("IMAGE",), # 新增:接收上一次循环的图片 23 | } 24 | } 25 | return inputs 26 | 27 | RETURN_TYPES = tuple(["FLOW_CONTROL", "IMAGE", "MASK", "INT", "INT"]) 28 | RETURN_NAMES = tuple(["FLOW_CONTROL", "current_image", "current_mask", "max_iterations", "iteration_count"]) 29 | FUNCTION = "while_loop_open" 30 | CATEGORY = "CyberEveLoop🐰" 31 | 32 | def standardize_input(self, images, masks): 33 | """ 34 | 标准化输入格式 35 | images: 确保是4D tensor [B,H,W,C] 36 | masks: 确保是3D tensor [B,H,W] 37 | 如果images是单张图片,会扩展到与masks相同的批次大小 38 | """ 39 | # 处理masks(先处理masks以获取批次大小) 40 | if isinstance(masks, list): 41 | masks = torch.cat(masks, dim=0) 42 | if len(masks.shape) == 2: # [H,W] -> [1,H,W] 43 | masks = masks.unsqueeze(0) 44 | assert len(masks.shape) == 3, f"Masks must be 3D [B,H,W], got shape {masks.shape}" 45 | 46 | # 处理images 47 | if isinstance(images, list): 48 | images = torch.cat(images, dim=0) 49 | if len(images.shape) == 3: # [H,W,C] -> [1,H,W,C] 50 | images = images.unsqueeze(0) 51 | assert len(images.shape) == 4, f"Images must be 4D [B,H,W,C], got shape {images.shape}" 52 | 53 | # 检查是否需要扩展images 54 | if images.shape[0] == 1 and masks.shape[0] > 1: 55 | print(f"Expanding single image to match mask batch size: {masks.shape[0]}") 56 | images = images.expand(masks.shape[0], -1, -1, -1) 57 | 58 | # 确保batch维度相同 59 | assert images.shape[0] == masks.shape[0], \ 60 | f"Batch size mismatch: images {images.shape[0]} vs masks {masks.shape[0]}" 61 | 62 | return images, masks 63 | 64 | 65 | def resize_to_match(self, image, target_shape): 66 | """调整图片尺寸以匹配目标shape""" 67 | if image.shape[1:3] != target_shape[1:3]: 68 | # 确保是4D tensor 69 | if len(image.shape) == 3: 70 | image = image.unsqueeze(0) 71 | 72 | # 转换为[B,C,H,W]用于插值 73 | image = image.permute(0, 3, 1, 2) 74 | 75 | # 执行resize 76 | image = F.interpolate( 77 | image, 78 | size=(target_shape[1], target_shape[2]), 79 | mode='bilinear', 80 | align_corners=False 81 | ) 82 | 83 | # 转换回[B,H,W,C] 84 | image = image.permute(0, 2, 3, 1) 85 | 86 | return image 87 | 88 | def while_loop_open(self, segmented_images, segmented_masks, unique_id=None, 89 | iteration_count=0, previous_image=None): 90 | print(f"while_loop_open Processing iteration {iteration_count}") 91 | 92 | # 标准化输入 93 | segmented_images, segmented_masks = self.standardize_input(segmented_images, segmented_masks) 94 | 95 | # 获取最大迭代次数 96 | max_iterations = segmented_images.shape[0] 97 | if max_iterations == 0: 98 | raise ValueError("No images provided in segmented_images") 99 | 100 | # 验证迭代计数 101 | if iteration_count >= max_iterations: 102 | raise ValueError(f"Iteration count {iteration_count} exceeds max iterations {max_iterations}") 103 | 104 | # 处理上一次循环传回的图片 105 | if previous_image is not None and iteration_count > 0: 106 | # 确保previous_image维度正确 107 | if len(previous_image.shape) == 3: 108 | previous_image = previous_image.unsqueeze(0) 109 | 110 | # 调整尺寸以匹配batch中的图片 111 | previous_image = self.resize_to_match(previous_image, segmented_images.shape) 112 | 113 | # 替换下一次要处理的图片 114 | next_idx = min(iteration_count, max_iterations - 1) 115 | segmented_images[next_idx:next_idx+1] = previous_image 116 | 117 | # 获取当前迭代的图片和蒙版 118 | current_image = segmented_images[iteration_count:iteration_count+1] 119 | current_mask = segmented_masks[iteration_count:iteration_count+1] 120 | 121 | return tuple(["stub", current_image, current_mask, max_iterations, iteration_count]) 122 | 123 | 124 | @VariantSupport() 125 | class BatchImageLoopClose: 126 | def __init__(self): 127 | pass 128 | 129 | @classmethod 130 | def INPUT_TYPES(cls): 131 | inputs = { 132 | "required": { 133 | "flow_control": ("FLOW_CONTROL", {"rawLink": True}), 134 | "current_image": ("IMAGE",), 135 | "current_mask": ("MASK",), 136 | "max_iterations": ("INT", {"forceInput": True}), 137 | }, 138 | "optional": { 139 | "pass_back": ("BOOLEAN", {"default": False}), # 新增:控制是否传回图片 140 | }, 141 | "hidden": { 142 | "dynprompt": "DYNPROMPT", 143 | "unique_id": "UNIQUE_ID", 144 | "result_images": ("IMAGE",), 145 | "result_masks": ("MASK",), 146 | "iteration_count": ("INT", {"default": 0}), 147 | } 148 | } 149 | return inputs 150 | 151 | RETURN_TYPES = tuple(["IMAGE", "MASK"]) 152 | RETURN_NAMES = tuple(["result_images", "result_masks"]) 153 | FUNCTION = "while_loop_close" 154 | CATEGORY = "CyberEveLoop🐰" 155 | 156 | def explore_dependencies(self, node_id, dynprompt, upstream, parent_ids): 157 | node_info = dynprompt.get_node(node_id) 158 | if "inputs" not in node_info: 159 | return 160 | 161 | for k, v in node_info["inputs"].items(): 162 | if is_link(v): 163 | parent_id = v[0] 164 | display_id = dynprompt.get_display_node_id(parent_id) 165 | display_node = dynprompt.get_node(display_id) 166 | class_type = display_node["class_type"] 167 | # 排除循环结束节点 168 | if class_type not in ['BatchImageLoopClose']: 169 | parent_ids.append(display_id) 170 | if parent_id not in upstream: 171 | upstream[parent_id] = [] 172 | self.explore_dependencies(parent_id, dynprompt, upstream, parent_ids) 173 | upstream[parent_id].append(node_id) 174 | 175 | def explore_output_nodes(self, dynprompt, upstream, output_nodes, parent_ids): 176 | """探索并添加输出节点的连接""" 177 | for parent_id in upstream: 178 | display_id = dynprompt.get_display_node_id(parent_id) 179 | for output_id in output_nodes: 180 | id = output_nodes[output_id][0] 181 | if id in parent_ids and display_id == id and output_id not in upstream[parent_id]: 182 | if '.' in parent_id: 183 | arr = parent_id.split('.') 184 | arr[len(arr)-1] = output_id 185 | upstream[parent_id].append('.'.join(arr)) 186 | else: 187 | upstream[parent_id].append(output_id) 188 | 189 | def collect_contained(self, node_id, upstream, contained): 190 | if node_id not in upstream: 191 | return 192 | for child_id in upstream[node_id]: 193 | if child_id not in contained: 194 | contained[child_id] = True 195 | self.collect_contained(child_id, upstream, contained) 196 | 197 | def standardize_input(self, image, mask): 198 | """ 199 | 标准化输入格式 200 | image: 确保是4D tensor [B,H,W,C] 201 | mask: 确保是3D tensor [B,H,W] 202 | """ 203 | # 处理image 204 | if len(image.shape) == 3: # [H,W,C] -> [1,H,W,C] 205 | image = image.unsqueeze(0) 206 | assert len(image.shape) == 4, f"Image must be 4D [B,H,W,C], got shape {image.shape}" 207 | 208 | # 处理mask 209 | if len(mask.shape) == 2: # [H,W] -> [1,H,W] 210 | mask = mask.unsqueeze(0) 211 | assert len(mask.shape) == 3, f"Mask must be 3D [B,H,W], got shape {mask.shape}" 212 | 213 | return image, mask 214 | 215 | def initialize_results(self, max_iterations, current_image, current_mask): 216 | """ 217 | 初始化结果张量,确保与MaskSplit输出格式一致 218 | """ 219 | # 确保维度正确 220 | assert len(current_image.shape) == 4, "Current image must be 4D [B,H,W,C]" 221 | assert len(current_mask.shape) == 3, "Current mask must be 3D [B,H,W]" 222 | 223 | # 创建结果张量,确保格式一致 224 | result_images = torch.zeros( 225 | (max_iterations, current_image.shape[1], current_image.shape[2], current_image.shape[3]), 226 | dtype=current_image.dtype, 227 | device=current_image.device 228 | ) # 明确指定 [B,H,W,C] 229 | 230 | result_masks = torch.zeros( 231 | (max_iterations, current_mask.shape[1], current_mask.shape[2]), 232 | dtype=current_mask.dtype, 233 | device=current_mask.device 234 | ) # 明确指定 [B,H,W] 235 | 236 | return result_images, result_masks 237 | 238 | def while_loop_close(self, flow_control, current_image, current_mask, max_iterations, 239 | pass_back=False, iteration_count=0, result_images=None, result_masks=None, 240 | dynprompt=None, unique_id=None,): 241 | print(f"Iteration {iteration_count} of {max_iterations}") 242 | 243 | # 标准化输入,确保格式一致 244 | current_image, current_mask = self.standardize_input(current_image, current_mask) 245 | 246 | # 验证迭代计数 247 | if iteration_count >= max_iterations: 248 | raise ValueError(f"Iteration count {iteration_count} exceeds max iterations {max_iterations}") 249 | 250 | # 结果初始化或验证 251 | if result_images is None or result_masks is None: 252 | result_images, result_masks = self.initialize_results(max_iterations, current_image, current_mask) 253 | else: 254 | # 验证现有结果的维度和格式 255 | assert result_images.shape[0] == max_iterations and len(result_images.shape) == 4, \ 256 | f"Result images must be 4D [B,H,W,C] with batch size {max_iterations}" 257 | assert result_masks.shape[0] == max_iterations and len(result_masks.shape) == 3, \ 258 | f"Result masks must be 3D [B,H,W] with batch size {max_iterations}" 259 | 260 | # 存储当前结果 261 | result_images[iteration_count:iteration_count+1] = current_image 262 | result_masks[iteration_count:iteration_count+1] = current_mask 263 | 264 | # 检查是否继续循环 265 | if iteration_count == max_iterations - 1: 266 | print(f"Loop finished with {iteration_count + 1} iterations") 267 | return (result_images, result_masks) 268 | 269 | # 准备下一次循环 270 | this_node = dynprompt.get_node(unique_id) 271 | upstream = {} 272 | parent_ids = [] 273 | self.explore_dependencies(unique_id, dynprompt, upstream, parent_ids) 274 | parent_ids = list(set(parent_ids)) # 去重 275 | 276 | # 获取并处理输出节点 277 | prompts = dynprompt.get_original_prompt() 278 | output_nodes = {} 279 | for id in prompts: 280 | node = prompts[id] 281 | if "inputs" not in node: 282 | continue 283 | class_type = node["class_type"] 284 | if class_type in ALL_NODE_CLASS_MAPPINGS: 285 | class_def = ALL_NODE_CLASS_MAPPINGS[class_type] 286 | if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True: 287 | for k, v in node['inputs'].items(): 288 | if is_link(v): 289 | output_nodes[id] = v 290 | 291 | # 创建新图 292 | graph = GraphBuilder() 293 | self.explore_output_nodes(dynprompt, upstream, output_nodes, parent_ids) 294 | 295 | contained = {} 296 | open_node = flow_control[0] 297 | self.collect_contained(open_node, upstream, contained) 298 | contained[unique_id] = True 299 | contained[open_node] = True 300 | 301 | # 创建节点 302 | for node_id in contained: 303 | original_node = dynprompt.get_node(node_id) 304 | node = graph.node(original_node["class_type"], 305 | "Recurse" if node_id == unique_id else node_id) 306 | node.set_override_display_id(node_id) 307 | 308 | # 设置连接 309 | for node_id in contained: 310 | original_node = dynprompt.get_node(node_id) 311 | node = graph.lookup_node("Recurse" if node_id == unique_id else node_id) 312 | for k, v in original_node["inputs"].items(): 313 | if is_link(v) and v[0] in contained: 314 | parent = graph.lookup_node(v[0]) 315 | node.set_input(k, parent.out(v[1])) 316 | else: 317 | node.set_input(k, v) 318 | 319 | # 设置节点参数 320 | my_clone = graph.lookup_node("Recurse") 321 | my_clone.set_input("iteration_count", iteration_count + 1) 322 | my_clone.set_input("result_images", result_images) 323 | my_clone.set_input("result_masks", result_masks) 324 | 325 | new_open = graph.lookup_node(open_node) 326 | new_open.set_input("iteration_count", iteration_count + 1) 327 | if pass_back: # 新增:根据pass_back决定是否传回图片 328 | new_open.set_input("previous_image", current_image) 329 | 330 | print(f"Continuing to iteration {iteration_count + 1}") 331 | 332 | return { 333 | "result": tuple([my_clone.out(0), my_clone.out(1)]), 334 | "expand": graph.finalize(), 335 | } 336 | 337 | 338 | @VariantSupport() 339 | class SingleImageLoopOpen: 340 | def __init__(self): 341 | pass 342 | 343 | @classmethod 344 | def INPUT_TYPES(cls): 345 | inputs = { 346 | "required": { 347 | "image": ("IMAGE",), 348 | "max_iterations": ("INT", {"default": 5, "min": 1, "max": 100}), 349 | }, 350 | "optional": { 351 | "mask": ("MASK",), 352 | }, 353 | "hidden": { 354 | "unique_id": "UNIQUE_ID", 355 | "iteration_count": ("INT", {"default": 0}), 356 | "previous_image": ("IMAGE",), 357 | "previous_mask": ("MASK",), 358 | } 359 | } 360 | return inputs 361 | 362 | RETURN_TYPES = tuple(["FLOW_CONTROL", "IMAGE", "MASK", "INT", "INT"]) 363 | RETURN_NAMES = tuple(["FLOW_CONTROL", "current_image", "current_mask", "max_iterations", "iteration_count"]) 364 | FUNCTION = "loop_open" 365 | CATEGORY = "CyberEveLoop🐰" 366 | 367 | def loop_open(self, image, max_iterations, mask=None, unique_id=None, 368 | iteration_count=0, previous_image=None, previous_mask=None): 369 | print(f"SingleImageLoopOpen Processing iteration {iteration_count}") 370 | 371 | # 确保维度正确 372 | if len(image.shape) == 3: 373 | image = image.unsqueeze(0) 374 | if mask is not None and len(mask.shape) == 2: 375 | mask = mask.unsqueeze(0) 376 | 377 | # 使用上一次循环的结果(如果有) 378 | current_image = previous_image if previous_image is not None and iteration_count > 0 else image 379 | current_mask = previous_mask if previous_mask is not None and iteration_count > 0 else mask 380 | 381 | return tuple(["stub", current_image, current_mask, max_iterations, iteration_count]) 382 | 383 | @VariantSupport() 384 | class SingleImageLoopClose: 385 | def __init__(self): 386 | pass 387 | 388 | @classmethod 389 | def INPUT_TYPES(cls): 390 | inputs = { 391 | "required": { 392 | "flow_control": ("FLOW_CONTROL", {"rawLink": True}), 393 | "current_image": ("IMAGE",), 394 | "max_iterations": ("INT", {"forceInput": True}), 395 | }, 396 | "optional": { 397 | "current_mask": ("MASK",), 398 | }, 399 | "hidden": { 400 | "dynprompt": "DYNPROMPT", 401 | "unique_id": "UNIQUE_ID", 402 | "iteration_count": ("INT", {"default": 0}), 403 | } 404 | } 405 | return inputs 406 | 407 | RETURN_TYPES = tuple(["IMAGE", "MASK"]) 408 | RETURN_NAMES = tuple(["final_image", "final_mask"]) 409 | FUNCTION = "loop_close" 410 | CATEGORY = "CyberEveLoop🐰" 411 | 412 | def explore_dependencies(self, node_id, dynprompt, upstream, parent_ids): 413 | node_info = dynprompt.get_node(node_id) 414 | if "inputs" not in node_info: 415 | return 416 | 417 | for k, v in node_info["inputs"].items(): 418 | if is_link(v): 419 | parent_id = v[0] 420 | display_id = dynprompt.get_display_node_id(parent_id) 421 | display_node = dynprompt.get_node(display_id) 422 | class_type = display_node["class_type"] 423 | if class_type not in ['SingleImageLoopClose']: 424 | parent_ids.append(display_id) 425 | if parent_id not in upstream: 426 | upstream[parent_id] = [] 427 | self.explore_dependencies(parent_id, dynprompt, upstream, parent_ids) 428 | upstream[parent_id].append(node_id) 429 | 430 | def explore_output_nodes(self, dynprompt, upstream, output_nodes, parent_ids): 431 | for parent_id in upstream: 432 | display_id = dynprompt.get_display_node_id(parent_id) 433 | for output_id in output_nodes: 434 | id = output_nodes[output_id][0] 435 | if id in parent_ids and display_id == id and output_id not in upstream[parent_id]: 436 | if '.' in parent_id: 437 | arr = parent_id.split('.') 438 | arr[len(arr)-1] = output_id 439 | upstream[parent_id].append('.'.join(arr)) 440 | else: 441 | upstream[parent_id].append(output_id) 442 | 443 | def collect_contained(self, node_id, upstream, contained): 444 | if node_id not in upstream: 445 | return 446 | for child_id in upstream[node_id]: 447 | if child_id not in contained: 448 | contained[child_id] = True 449 | self.collect_contained(child_id, upstream, contained) 450 | 451 | def loop_close(self, flow_control, current_image, max_iterations, current_mask=None, 452 | iteration_count=0, dynprompt=None, unique_id=None): 453 | print(f"Iteration {iteration_count} of {max_iterations}") 454 | 455 | # 维度处理 456 | if len(current_image.shape) == 3: 457 | current_image = current_image.unsqueeze(0) 458 | if current_mask is not None and len(current_mask.shape) == 2: 459 | current_mask = current_mask.unsqueeze(0) 460 | 461 | # 检查是否继续循环 462 | if iteration_count >= max_iterations - 1: 463 | print(f"Loop finished with {iteration_count + 1} iterations") 464 | return (current_image, current_mask if current_mask is not None else torch.zeros_like(current_image[:,:,:,0])) 465 | 466 | # 准备下一次循环 467 | this_node = dynprompt.get_node(unique_id) 468 | upstream = {} 469 | parent_ids = [] 470 | self.explore_dependencies(unique_id, dynprompt, upstream, parent_ids) 471 | parent_ids = list(set(parent_ids)) 472 | 473 | # 获取并处理输出节点 474 | prompts = dynprompt.get_original_prompt() 475 | output_nodes = {} 476 | for id in prompts: 477 | node = prompts[id] 478 | if "inputs" not in node: 479 | continue 480 | class_type = node["class_type"] 481 | if class_type in ALL_NODE_CLASS_MAPPINGS: 482 | class_def = ALL_NODE_CLASS_MAPPINGS[class_type] 483 | if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True: 484 | for k, v in node['inputs'].items(): 485 | if is_link(v): 486 | output_nodes[id] = v 487 | 488 | # 创建新图 489 | graph = GraphBuilder() 490 | self.explore_output_nodes(dynprompt, upstream, output_nodes, parent_ids) 491 | 492 | contained = {} 493 | open_node = flow_control[0] 494 | self.collect_contained(open_node, upstream, contained) 495 | contained[unique_id] = True 496 | contained[open_node] = True 497 | 498 | # 创建节点 499 | for node_id in contained: 500 | original_node = dynprompt.get_node(node_id) 501 | node = graph.node(original_node["class_type"], 502 | "Recurse" if node_id == unique_id else node_id) 503 | node.set_override_display_id(node_id) 504 | 505 | # 设置连接 506 | for node_id in contained: 507 | original_node = dynprompt.get_node(node_id) 508 | node = graph.lookup_node("Recurse" if node_id == unique_id else node_id) 509 | for k, v in original_node["inputs"].items(): 510 | if is_link(v) and v[0] in contained: 511 | parent = graph.lookup_node(v[0]) 512 | node.set_input(k, parent.out(v[1])) 513 | else: 514 | node.set_input(k, v) 515 | 516 | # 设置节点参数 517 | my_clone = graph.lookup_node("Recurse") 518 | my_clone.set_input("iteration_count", iteration_count + 1) 519 | 520 | new_open = graph.lookup_node(open_node) 521 | new_open.set_input("iteration_count", iteration_count + 1) 522 | new_open.set_input("previous_image", current_image) 523 | if current_mask is not None: 524 | new_open.set_input("previous_mask", current_mask) 525 | 526 | print(f"Continuing to iteration {iteration_count + 1}") 527 | 528 | return { 529 | "result": tuple([my_clone.out(0), my_clone.out(1)]), 530 | "expand": graph.finalize(), 531 | } 532 | 533 | 534 | 535 | @VariantSupport() 536 | class LoopIndexSwitch: 537 | def __init__(self): 538 | pass 539 | 540 | @classmethod 541 | def INPUT_TYPES(cls): 542 | """ 543 | 预定义100个隐藏的lazy输入 544 | """ 545 | optional_inputs = { 546 | "default_value": ("*", {"lazy": True}), # 默认值也设为lazy 547 | } 548 | # 添加100个隐藏的lazy输入 549 | hidden_inputs = {} 550 | for i in range(100): 551 | hidden_inputs[f"while_{i}"] = ("*", {"lazy": True}) 552 | 553 | return { 554 | "required": { 555 | "iteration_count": ("INT", {"forceInput": True}), # 当前迭代次数 556 | }, 557 | "optional": optional_inputs, 558 | "hidden": hidden_inputs, 559 | } 560 | 561 | RETURN_TYPES = ("*",) 562 | FUNCTION = "index_switch" 563 | CATEGORY = "CyberEveLoop🐰" 564 | 565 | def check_lazy_status(self, iteration_count, **kwargs): 566 | """ 567 | 检查当前迭代需要的输入和默认值 568 | """ 569 | needed = [] 570 | current_key = f"while_{iteration_count}" 571 | 572 | # 检查当前迭代的输入 573 | if current_key in kwargs : 574 | needed.append(current_key) 575 | else: 576 | needed.append("default_value") 577 | 578 | print(f"Index switch needed: {needed}") 579 | return needed 580 | 581 | 582 | 583 | def index_switch(self, iteration_count, **kwargs): 584 | """ 585 | 根据当前迭代次数选择对应的输入值 586 | """ 587 | current_key = f"while_{iteration_count}" 588 | 589 | if current_key in kwargs and kwargs[current_key] is not None: 590 | return (kwargs[current_key],) 591 | return (kwargs.get("default_value"),) 592 | 593 | 594 | CyberEve_Loop_CLASS_MAPPINGS = { 595 | "CyberEve_BatchImageLoopOpen": BatchImageLoopOpen, 596 | "CyberEve_BatchImageLoopClose": BatchImageLoopClose, 597 | "CyberEve_LoopIndexSwitch": LoopIndexSwitch, 598 | "CyberEve_SingleImageLoopOpen": SingleImageLoopOpen, 599 | "CyberEve_SingleImageLoopClose": SingleImageLoopClose, 600 | } 601 | 602 | CyberEve_Loop_DISPLAY_NAME_MAPPINGS = { 603 | "CyberEve_BatchImageLoopOpen": "Batch Image Loop Open🐰", 604 | "CyberEve_BatchImageLoopClose": "Batch Image Loop Close🐰", 605 | "CyberEve_LoopIndexSwitch": "Loop Index Switch🐰", 606 | "CyberEve_SingleImageLoopOpen": "Single Image Loop Open🐰", 607 | "CyberEve_SingleImageLoopClose": "Single Image Loop Close🐰", 608 | } -------------------------------------------------------------------------------- /mask_split.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | import cv2 4 | import numpy as np 5 | 6 | 7 | class MaskSplit: 8 | def __init__(self): 9 | pass 10 | 11 | @classmethod 12 | def INPUT_TYPES(cls): 13 | return { 14 | "required": { 15 | "image": ("IMAGE",), 16 | "mask": ("MASK",), 17 | 18 | }, 19 | } 20 | 21 | RETURN_TYPES = ("IMAGE","MASK") 22 | RETURN_NAMES = ("segmented_images","segmented_masks") 23 | FUNCTION = "segment_mask" 24 | 25 | CATEGORY = "CyberEveLoop🐰" 26 | 27 | def find_top_left_point(self, mask_np): 28 | """找到mask中最左上角的点""" 29 | # 找到所有非零点 30 | y_coords, x_coords = np.nonzero(mask_np) 31 | if len(x_coords) == 0: 32 | return float('inf'), float('inf') 33 | 34 | # 找到最小x值 35 | min_x = np.min(x_coords) 36 | # 在最小x值的点中找到最小y值 37 | min_y = np.min(y_coords[x_coords == min_x]) 38 | 39 | return min_x, min_y 40 | 41 | def segment_mask(self, mask, image): 42 | """使用OpenCV快速分割蒙版并处理图像""" 43 | # 保存原始设备信息 44 | device = mask.device if isinstance(mask, torch.Tensor) else torch.device('cpu') 45 | 46 | # 确保mask是正确的形状并转换为numpy数组 47 | if isinstance(mask, torch.Tensor): 48 | if len(mask.shape) == 2: 49 | mask = mask.unsqueeze(0) 50 | mask_np = (mask[0] * 255).cpu().numpy().astype(np.uint8) 51 | else: 52 | mask_np = (mask * 255).astype(np.uint8) 53 | 54 | # 使用OpenCV找到轮廓 55 | contours, hierarchy = cv2.findContours( 56 | mask_np, 57 | cv2.RETR_TREE, 58 | cv2.CHAIN_APPROX_SIMPLE 59 | ) 60 | 61 | mask_info = [] # 用于排序的信息列表 62 | 63 | if hierarchy is not None and len(contours) > 0: 64 | hierarchy = hierarchy[0] 65 | contour_masks = {} 66 | 67 | # 创建每个轮廓的mask 68 | for i, contour in enumerate(contours): 69 | mask = np.zeros_like(mask_np) 70 | cv2.drawContours(mask, [contour], -1, 255, -1) 71 | contour_masks[i] = mask 72 | 73 | # 处理每个轮廓 74 | processed_indices = set() 75 | 76 | for i, (contour, h) in enumerate(zip(contours, hierarchy)): 77 | if i in processed_indices: 78 | continue 79 | 80 | current_mask = contour_masks[i].copy() 81 | child_idx = h[2] 82 | 83 | if child_idx != -1: 84 | while child_idx != -1: 85 | current_mask = cv2.subtract(current_mask, contour_masks[child_idx]) 86 | processed_indices.add(child_idx) 87 | child_idx = hierarchy[child_idx][0] 88 | 89 | # 找到最左上角的点 90 | min_x, min_y = self.find_top_left_point(current_mask) 91 | 92 | # 转换为tensor 93 | mask_tensor = torch.from_numpy(current_mask).float() / 255.0 94 | mask_tensor = mask_tensor.unsqueeze(0) 95 | mask_tensor = mask_tensor.to(device) 96 | 97 | # 保存mask和排序信息 98 | mask_info.append((mask_tensor, min_x, min_y)) 99 | processed_indices.add(i) 100 | 101 | # 如果没有找到任何轮廓,使用原始mask 102 | if not mask_info: 103 | if isinstance(mask, torch.Tensor): 104 | mask_info.append((mask, 0, 0)) 105 | else: 106 | mask_tensor = torch.from_numpy(mask).float() 107 | if len(mask_tensor.shape) == 2: 108 | mask_tensor = mask_tensor.unsqueeze(0) 109 | mask_tensor = mask_tensor.to(device) 110 | mask_info.append((mask_tensor, 0, 0)) 111 | 112 | # 根据最左上角点排序 113 | mask_info.sort(key=lambda x: (x[1], x[2])) 114 | 115 | # 确保image是正确的形状 116 | if len(image.shape) == 3: 117 | image = image.unsqueeze(0) 118 | 119 | # 处理masks和images 120 | result_masks = None 121 | result_images = None 122 | 123 | for mask_tensor, _, _ in mask_info: 124 | # 处理masks 125 | if result_masks is None: 126 | result_masks = mask_tensor 127 | else: 128 | result_masks = torch.cat([result_masks, mask_tensor], dim=0) 129 | 130 | # 处理images 131 | if result_images is None: 132 | result_images = image.clone() 133 | else: 134 | result_images = torch.cat([result_images, image.clone()], dim=0) 135 | 136 | return (result_images, result_masks) 137 | 138 | 139 | 140 | class MaskMerge: 141 | def __init__(self): 142 | pass 143 | 144 | @classmethod 145 | def INPUT_TYPES(cls): 146 | return { 147 | "required": { 148 | "original_image": ("IMAGE",), 149 | }, 150 | "optional": { 151 | "processed_images": ("IMAGE", {"forceInput": True}), 152 | "masks": ("MASK", {"forceInput": True}), 153 | } 154 | } 155 | 156 | RETURN_TYPES = ("IMAGE",) 157 | RETURN_NAMES = ("merged_image",) 158 | FUNCTION = "merge_masked_images" 159 | CATEGORY = "CyberEveLoop🐰" 160 | 161 | def standardize_input(self, image, processed_images=None, masks=None): 162 | """ 163 | 标准化输入格式 164 | - image: [H,W,C] -> [1,H,W,C] 165 | - processed_images: [...] -> [B,H,W,C] 166 | - masks: [...] -> [B,H,W] 167 | """ 168 | # 处理原始图像 169 | if len(image.shape) == 3: 170 | image = image.unsqueeze(0) 171 | assert len(image.shape) == 4, f"Original image must be 4D [B,H,W,C], got shape {image.shape}" 172 | 173 | # 处理processed_images 174 | if processed_images is not None: 175 | if isinstance(processed_images, list): 176 | processed_images = torch.cat(processed_images, dim=0) 177 | if len(processed_images.shape) == 3: 178 | processed_images = processed_images.unsqueeze(0) 179 | assert len(processed_images.shape) == 4, \ 180 | f"Processed images must be 4D [B,H,W,C], got shape {processed_images.shape}" 181 | 182 | # 处理masks 183 | if masks is not None: 184 | if isinstance(masks, list): 185 | masks = torch.cat(masks, dim=0) 186 | if len(masks.shape) == 2: 187 | masks = masks.unsqueeze(0) 188 | assert len(masks.shape) == 3, f"Masks must be 3D [B,H,W], got shape {masks.shape}" 189 | 190 | return image, processed_images, masks 191 | 192 | def resize_tensor(self, x, size, mode='bilinear'): 193 | """调整tensor尺寸的辅助函数""" 194 | # 确保输入是4D tensor [B,C,H,W] 195 | orig_dim = x.dim() 196 | if orig_dim == 3: 197 | x = x.unsqueeze(0) 198 | 199 | # 如果是图像 [B,H,W,C],需要转换为 [B,C,H,W] 200 | if x.shape[-1] in [1, 3, 4]: 201 | x = x.permute(0, 3, 1, 2) 202 | 203 | # 执行调整 204 | x = F.interpolate(x, size=size, mode=mode, align_corners=False if mode in ['bilinear', 'bicubic'] else None) 205 | 206 | # 转换回原始格式 207 | if x.shape[1] in [1, 3, 4]: 208 | x = x.permute(0, 2, 3, 1) 209 | 210 | # 如果原始输入是3D,去掉batch维度 211 | if orig_dim == 3: 212 | x = x.squeeze(0) 213 | 214 | return x 215 | 216 | def merge_masked_images(self, original_image, processed_images=None, masks=None): 217 | """合并处理后的图像""" 218 | # 确保输入有效 219 | if processed_images is None or masks is None: 220 | return (original_image,) 221 | 222 | # 标准化输入 223 | original_image, processed_images, masks = self.standardize_input( 224 | original_image, processed_images, masks 225 | ) 226 | 227 | # 创建结果图像的副本 228 | result = original_image.clone() 229 | 230 | # 获取目标尺寸 231 | target_height = original_image.shape[1] 232 | target_width = original_image.shape[2] 233 | 234 | # 调整处理图像的尺寸(如果需要) 235 | if processed_images.shape[1:3] != (target_height, target_width): 236 | processed_images = self.resize_tensor( 237 | processed_images, 238 | (target_height, target_width), 239 | mode='bilinear' 240 | ) 241 | 242 | # 调整蒙版尺寸(如果需要) 243 | if masks.shape[1:3] != (target_height, target_width): 244 | masks = self.resize_tensor( 245 | masks, 246 | (target_height, target_width), 247 | mode='bilinear' 248 | ) 249 | 250 | # 扩展蒙版维度以匹配图像通道 251 | masks = masks.unsqueeze(-1).expand(-1, -1, -1, 3) 252 | 253 | # 批量处理所有图片 254 | for i in range(processed_images.shape[0]): 255 | current_image = processed_images[i:i+1] 256 | current_mask = masks[i:i+1] 257 | result = current_mask * current_image + (1 - current_mask) * result 258 | 259 | assert len(result.shape) == 4, "Output must be 4D [B,H,W,C]" 260 | return (result,) 261 | 262 | 263 | Mask_CLASS_MAPPINGS = { 264 | "CyberEve_MaskSegmentation": MaskSplit, 265 | "CyberEve_MaskMerge": MaskMerge, 266 | } 267 | 268 | Mask_DISPLAY_NAME_MAPPINGS = { 269 | "CyberEve_MaskSegmentation": "Mask Segmentation🐰", 270 | "CyberEve_MaskMerge": "Mask Merge🐰", 271 | } 272 | 273 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "loop-image" 3 | description = "ComfyUI Loop Image is a node package specifically designed for image loop processing. It provides two main processing modes: Batch Image Processing and Single Image Processing, along with supporting image segmentation and merging functions." 4 | version = "1.1.0" 5 | license = {file = "LICENSE"} 6 | dependencies = ["opencv-python", "numpy"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/WainWong/ComfyUI-Loop-image" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "cybereve-wain" 14 | DisplayName = "ComfyUI-Loop-image" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | numpy -------------------------------------------------------------------------------- /tools.py: -------------------------------------------------------------------------------- 1 | def MakeSmartType(t): 2 | if isinstance(t, str): 3 | return SmartType(t) 4 | return t 5 | 6 | class SmartType(str): 7 | def __ne__(self, other): 8 | if self == "*" or other == "*": 9 | return False 10 | selfset = set(self.split(',')) 11 | otherset = set(other.split(',')) 12 | return not selfset.issubset(otherset) 13 | 14 | def VariantSupport(): 15 | def decorator(cls): 16 | if hasattr(cls, "INPUT_TYPES"): 17 | old_input_types = getattr(cls, "INPUT_TYPES") 18 | def new_input_types(*args, **kwargs): 19 | types = old_input_types(*args, **kwargs) 20 | for category in ["required", "optional"]: 21 | if category not in types: 22 | continue 23 | for key, value in types[category].items(): 24 | if isinstance(value, tuple): 25 | types[category][key] = (MakeSmartType(value[0]),) + value[1:] 26 | return types 27 | setattr(cls, "INPUT_TYPES", new_input_types) 28 | if hasattr(cls, "RETURN_TYPES"): 29 | old_return_types = cls.RETURN_TYPES 30 | setattr(cls, "RETURN_TYPES", tuple(MakeSmartType(x) for x in old_return_types)) 31 | if hasattr(cls, "VALIDATE_INPUTS"): 32 | # Reflection is used to determine what the function signature is, so we can't just change the function signature 33 | raise NotImplementedError("VariantSupport does not support VALIDATE_INPUTS yet") 34 | else: 35 | def validate_inputs(input_types): 36 | inputs = cls.INPUT_TYPES() 37 | for key, value in input_types.items(): 38 | if isinstance(value, SmartType): 39 | continue 40 | if "required" in inputs and key in inputs["required"]: 41 | expected_type = inputs["required"][key][0] 42 | elif "optional" in inputs and key in inputs["optional"]: 43 | expected_type = inputs["optional"][key][0] 44 | else: 45 | expected_type = None 46 | if expected_type is not None and MakeSmartType(value) != expected_type: 47 | return f"Invalid type of {key}: {value} (expected {expected_type})" 48 | return True 49 | setattr(cls, "VALIDATE_INPUTS", validate_inputs) 50 | return cls 51 | return decorator 52 | 53 | -------------------------------------------------------------------------------- /web/node/dynamicnode.js: -------------------------------------------------------------------------------- 1 | import { app } from "../../../scripts/app.js" 2 | 3 | const _ID = "CyberEve_LoopIndexSwitch"; 4 | const _PREFIX = "while_"; 5 | const _TYPE = "*"; 6 | const MAX_INPUTS = 100; 7 | 8 | app.registerExtension({ 9 | name: 'CyberEveLoop.LoopIndexSwitch', 10 | async beforeRegisterNodeDef(nodeType, nodeData, app) { 11 | // 添加调试信息 12 | console.log("Registering extension for:", nodeData.name); 13 | console.log("Looking for:", _ID); 14 | if (nodeData.name !== _ID) { 15 | return; 16 | } 17 | 18 | // 添加右键菜单选项 19 | const onGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; 20 | nodeType.prototype.getExtraMenuOptions = function(_, options) { 21 | if (onGetExtraMenuOptions) { 22 | onGetExtraMenuOptions.apply(this, arguments); 23 | } 24 | 25 | // 添加输入槽 26 | options.push({ 27 | content: "Add Loop Input", 28 | callback: () => { 29 | // 弹出对话框让用户输入循环次数 30 | const number = prompt("Enter loop iteration number (0-99):", "0"); 31 | if (number === null || isNaN(number)) { 32 | return; 33 | } 34 | 35 | const num = parseInt(number); 36 | if (num < 0 || num >= MAX_INPUTS) { 37 | alert(`Please enter a number between 0 and ${MAX_INPUTS-1}`); 38 | return; 39 | } 40 | 41 | const slotName = `${_PREFIX}${num}`; 42 | 43 | // 检查是否已存在该输入槽 44 | if (this.inputs.find(input => input.name === slotName)) { 45 | alert(`Input for iteration ${num} already exists!`); 46 | return; 47 | } 48 | 49 | // 添加新的输入槽 50 | this.addInput(slotName, _TYPE); 51 | this.graph.setDirtyCanvas(true); 52 | } 53 | }); 54 | 55 | // 删除输入槽子菜单 56 | const valueInputs = this.inputs.filter(input => 57 | input.name.startsWith(_PREFIX) 58 | ); 59 | 60 | if (valueInputs.length > 0) { 61 | const removeOptions = valueInputs.map(input => ({ 62 | content: `Remove iteration ${input.name.substring(_PREFIX.length)}`, 63 | callback: () => { 64 | const index = this.inputs.findIndex(i => i.name === input.name); 65 | if (index !== -1) { 66 | this.removeInput(index); 67 | this.graph.setDirtyCanvas(true); 68 | } 69 | } 70 | })); 71 | 72 | options.push({ 73 | content: "Remove Loop Input", 74 | submenu: { 75 | options: removeOptions 76 | } 77 | }); 78 | } 79 | }; 80 | 81 | // 序列化节点时保存输入槽信息 82 | nodeType.prototype.serialize = function() { 83 | const data = LGraphNode.prototype.serialize.apply(this); 84 | data.inputSlots = this.inputs.filter(input => 85 | input.name.startsWith(_PREFIX) 86 | ).map(input => ({ 87 | name: input.name, 88 | type: input.type 89 | })); 90 | return data; 91 | }; 92 | 93 | // 反序列化时恢复输入槽 94 | nodeType.prototype.configure = function(data) { 95 | LGraphNode.prototype.configure.apply(this, arguments); 96 | if (data.inputSlots) { 97 | // 移除所有循环相关的输入 98 | this.inputs = this.inputs.filter(input => 99 | !input.name.startsWith(_PREFIX) 100 | ); 101 | // 恢复保存的输入槽 102 | data.inputSlots.forEach(slot => { 103 | this.addInput(slot.name, slot.type); 104 | }); 105 | } 106 | }; 107 | } 108 | }); 109 | --------------------------------------------------------------------------------