├── .gitattributes
├── .github
├── FUNDING.yml
└── workflows
│ └── publish.yml
├── .gitignore
├── LICENSE
├── README.md
├── __init__.py
├── blendif.py
├── blendmodes.py
├── blur.py
├── colors.py
├── component-modes.md
├── contrast-modes.md
├── contrast.py
├── darken-modes.md
├── hsv.py
├── inversion-modes.md
├── lighten-modes.md
├── normal-modes.md
├── pyproject.toml
├── requirements.txt
├── resize.py
├── selectivecolor.py
└── specialty-mode.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
12 | polar: # Replace with a single Polar username
13 | buy_me_a_coffee: chrisfreilich
14 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
15 |
--------------------------------------------------------------------------------
/.github/workflows/publish.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 == 'chrisfreilich' }}
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 | ## Add your own personal access token to your Github Repository secrets and reference it here.
25 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .venv
2 | archive
--------------------------------------------------------------------------------
/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 | # Virtuoso Nodes for ComfyUI
2 |
3 | This set of nodes is designed to give some Photoshop-like functionality within ComfyUI. The nodes available are:
4 |
5 | - [**Blend Modes**](https://github.com/chrisfreilich/virtuoso-nodes#blend-modes): Applies an image to another image using a blend mode operation. Every conceivable blend mode is available.
6 | - [**Blend If**](https://github.com/chrisfreilich/virtuoso-nodes#blend-if-node): Composites one image on top of another with transparency based on several parameters.
7 | - [**Adjustment Nodes**](https://github.com/chrisfreilich/virtuoso-nodes#adjustment-nodes)
8 | - **Selective Color**: Adjust the color of a specific color or brightness range in an image, as with Photoshop's Selective Color adjustment layer.
9 | - **Color Balance**: Make detailed color balance adjustments to shadows, midtones, and highlights of an image.
10 | - **Color Balance Advanced**: Color balance of a targeted brightness range.
11 | - **Levels**: Adjust the brightness levels of an image or single color channels. Works the same as Photoshop's Levels adjustment layer.
12 | - **Black and White**: Transform a color image into Black and White while controlling brightness levels based on hue. Works the same as Photoshop's Black and White adjustment layer.
13 | - **Hue/Saturation**: Simplified version of the Advanced Hue/Saturation Node. Allows you to choose colors by name, and choose from preset range sizes and feather values.
14 | - **Hue/Saturation Advanced**: Control Hue, Saturation, and Lightness of an image based on the selection of a range of hues. Works the same as Photoshop's Hue/Saturation adjustment layer.
15 | - [**Blur Nodes**](https://github.com/chrisfreilich/virtuoso-nodes#blur-nodes)
16 | - **Motion Blur / Motion Blur with Depth Map**
17 | - **Lens Blur / Lens Blur with Depth Map**
18 | - **Gaussian Blur / Gaussian Blur with Depth Map**
19 | - [**Solid Color Nodes**](https://github.com/chrisfreilich/virtuoso-nodes#solid-color-nodes)
20 | - **Solid Color**: Create a solid color image by choosing from a list of 16 basic colors.
21 | - **Solid Color RGB**: Create a solid color image by entering Red, Green, and Blue values, or entering an RGB hex value.
22 | - **Solid Color HSV**: Create a solid color image by entering Hue, Saturation, and Value.
23 | - [**Channel Nodes**](https://github.com/chrisfreilich/virtuoso-nodes#channel-nodes)
24 | - **SplitRGB**: This node takes an image and splits it into its red, green, and blue components. These then can be used in creative ways with blend modes as well.
25 | - **MergeRGB**: This node takes three images, and merges the specified channels into one image. It is the complementary node to the SplitRGB node, to be used to recombine channels that you have split, though you can feel free to merge any images you wish for trippy effects.
26 |
27 |
28 | [**Installation Instructions**](https://github.com/chrisfreilich/virtuoso-nodes#installation)
29 |
30 |
31 | ## Blend Modes
32 |
33 | 
34 |
35 | This node gives access to thirty different blend modes, and includes a scaling option for the top layer and the ability to use external masks.
36 |
37 | ### Node controls:
38 |
39 | - **backdrop**: This is the background image. The output image will have the same dimensions as this image.
40 | - **source**: This is the top image. If it is not the same size as the backdrop image, it will be resized to cover the backdrop.
41 | - **mask**: Can be used to retain the alpha channel from the source image, or you can use an external mask to control the blended area.
42 | - **opacity**: The opacity of the source image. The backdrop image is always 100% opacity.
43 | - **source_adjust**: The method by which the source image will be resized if necessary.
44 | - *Stretch* will change each dimension independently just as much as needed to match that dimension, potentially changing the aspect ratio of the source image and causing distortion.
45 | - *Crop* will maintain the aspect ratio of the source image, and resize it until it just covers the backdrop image, then crop what doesn't fit.
46 | - **blend_mode**: normal is the default blend mode.
47 |
48 | ### Examples
49 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
50 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
51 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
52 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
53 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
54 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)
55 |
56 | [Learn about the math behind blend modes](https://learning.hccs.edu/faculty/bradly.brown/arts2348/handouts/blending-modes)
57 | [A practical discussion of the blend modes](https://www.youtube.com/watch?v=i1D9ijh3_-I)
58 |
59 |
60 | ## Blend If Node
61 |
62 | 
63 |
64 | This node gives you the functionality that is available with Photoshop's Blend If feature:
65 |
66 | 
67 |
68 | This feature composites the top_layer image over the bottom_layer image based on various possible calculations. ComfyUI's interface options being limited, the inputs have all been converted to fields instead of nice sliders.
69 |
70 | ### Node input controls:
71 |
72 | - **top_layer**: This is the top image. If it is not the same size as the bottom_layer image, it will be resized to cover the bottom layer. This is equivalent to 'current layer' in Photoshop.
73 | - **bottom_layer**: This is the background image. The output image will have the same dimensions as this image. This is equivalent to 'underlying layer' in Photoshop.
74 | - **mask**: This is an optional mask for the top layer, which will add to the transparency of the top layer in addition to the transparency created by the Blend If process. Any alpha channels in the top_layer and bottom_layer images are ignored.
75 | - **blend_if_layer**: Choose the layer that will be analyzed to determine the opacity of the top layer. This is equivalent to Photoshop's 'current layer' and 'underlying layer' sliders. This node only calculates one or the other.
76 | - **blend_if_channel**: Which color channel (or gray) will be used to analyze the selected layer. This is equivalent to the "Blend If:" dropdown in photoshop.
77 | - **start_rise, end_rise, start_fall, end_fall**: These four inputs define which brightness values for the selected channel on the selected layer are opaque. They are equivalent to the triangles below the 'current layer' and 'underlying layer' sliders, which each split into two to add softness to the selection. In this node, any brightness values lower than start_rise or greater than end_fall will be completely transparent, and brightness values between end_rise and start_fall will be completely opaque. Brightness values between start_rise and end_rise and between start_fall and end_fall will be partially transparent to feather the edges of the selection.
78 | - **opacity**: Values less than 1 will reduce the opacity of the top_layer image in addition to any transparency calculated by the Blend If process. This is the equivalent to the opacity setting for the entire layer in Photoshop.
79 | - **match_size**: Method to use to resize the top_layer image if it is not the same size as the bottom_layer image.
80 | - **invert_mask**: 'yes' will invert the incoming mask before applying it to the top_layer image. Set to 'yes' by default, as it seems to be the more common situation.
81 |
82 | ### Node Outputs
83 | - **IMAGE**: The final image with top_layer composited on top of bottom_layer.
84 | - **MASK**: This is the mask generated by the Blend If process. It can be useful to ensure you are getting the result you want, or to do further processing on the same pixels.
85 |
86 |
87 |
88 | ## Adjustment Nodes
89 |
90 | These nodes replicate Photoshop adjustment layers.
91 |
92 | ### Selective Color Node
93 |
94 | 
95 |
96 | This feature allows you to adjust the color balance of a specified range of colors or brightness in an image. This node can be chained to affect different color ranges.
97 |
98 | ### Node input controls:
99 |
100 | - **image**: This is image to be adjusted.
101 | - **color_range**: This selects which range of colors or gray values will be affected.
102 | - **cyan, magenta, yellow, black**: These inputs control how much of each secondary color or black is added or removed from the color range selected.
103 | - **method**: 'absolute' will directly apply the change, whereas 'relative' will apply the change as a percentage of the current value, resulting in a subtler effect.
104 |
105 | [Good reference on selective color](https://fstoppers.com/photoshop/selective-color-possibly-best-tool-photographers-7954)
106 |
107 |
108 |
109 |
110 | ### Color Balance Node
111 |
112 | 
113 |
114 | This feature allows you to finely adjust the color balance of the shadows, midtones, and highlights of an image. It reproduces the Photoshop functionality of the Color Balance layer.
115 |
116 | ### Node input controls:
117 |
118 | - **image**: This is image to be adjusted.
119 | - **lows, mids, highs**: Each of these prefixes indicates the brightness range on which the correction will have the greatest effect.
120 | - **cyan_red, magenta_green, yellow_blue**: These suffixes indicate the color axis the adjustment will work on. -1 will be the most cyan/magenta/yellow possible, and 1 will be the most red/green/blue possible.
121 | - **preserve luminosity**: This will maintain the brightness of the image while adjusting the relative color values. This will help prevent clipping of brightness values, while making the overall effect more subtle.
122 |
123 |
124 | ### Color Balance Advanced Node
125 |
126 | 
127 |
128 | This node allows you to target a specific brightness as the center of an adjustment range, and gives full range of adjustment. Unlike the standard Color Balance Node, it is easy to create distorted corrections with this node if you are not careful.
129 |
130 | ### Node input controls:
131 |
132 | - **image**: This is image to be adjusted.
133 | - **brightness_target**: What brightness level the correction should be centered on. 0 is black and 1 is white. This brightness level will receive the strongest correction, tapering off for brighter and darker pixels.
134 | - **cyan_red, magenta_green, yellow_blue**: These suffixes indicate the color axis the adjustment will work on. -1 will be the most cyan/magenta/yellow possible, and 1 will be the most red/green/blue possible. Unlike the standard Color Balance Mode, these adjustments are unrestricted, so less is more!
135 | - **preserve luminosity**: This will maintain the brightness of the image while adjusting the relative color values. This will help prevent clipping of brightness values, while making the overall effect more subtle.
136 |
137 |
138 | ### Levels
139 |
140 | 
141 |
142 | This node works just like Photoshop's Levels, without the fancy controls. Move around your black and white points and your gamma, across all channels, or select just one color channel.
143 |
144 | ### Node controls:
145 |
146 | - **image**: The image to set the levels for.
147 | - **channel**: Choose 'RGB' to work on the whole image, or a color to set levels only on that color channel.
148 | - **input_black_point**: Choose what brightness level becomes black. 0 is black, 1 is white.
149 | - **input_gamma**: Adjust the gamma.
150 | - **input_white_point**: Choose what brightness level becomes white. 0 is black, 1 is white.
151 | - **output_black_point**: After input calculations are complete, what brightness will black pixels be output at.
152 | - **output_white_point**: After input calculations are complete, what brightness will white pixels be output at.
153 |
154 |
155 |
156 | ### Black and White
157 |
158 | 
159 |
160 | This node works just like Photoshop's Black and White adjustment layer. Add or remove brightness based on each of the color ranges in the image.
161 |
162 | ### Node controls:
163 |
164 | - **image**: The image to set the levels for.
165 | - **red, green, blue, cyan, magenta, yellow**: Reduce these values to make the given color range darker, increase the values to make the given color range brighter.
166 |
167 |
168 |
169 |
170 | ### Hue / Saturation
171 |
172 | 
173 |
174 | This node works like a simplified version of Photoshop's Hue/Saturation adjustment layer. Select a color range to work on, then change the hue, saturation, and lightness of that range. Note that Stable Diffusion images seem to have pretty brutal color compression, so this node is best for subtle effects... otherwise things get pretty weird.
175 |
176 | ### Node input controls:
177 |
178 | - **image**: The image to set the levels for.
179 | - **hue**: Choose the main color to affect.
180 | - **hue_width**: How far away from the main color do you want to full affect?
181 | - **feather**: How much softening do you want from fully selected colors to unselected colors?
182 | - **hue_offset**: This value changes each pixel's hue value by rotating it this number of degrees around the color wheel. Each color on the hue list is 60 degrees apart.
183 | - **sat_offset**: This value increases or decreases color saturation.
184 | - **lightness_offset**: This value affects how much white or black is added to the image.
185 |
186 | ### Node Outputs
187 | - **IMAGE**: The final image
188 | - **MASK**: This is the mask generated by the hue selection process. It can be useful to ensure you are getting the result you want, or to do further processing on the same pixels.
189 |
190 |
191 |
192 |
193 | ### Hue / Saturation Advanced
194 |
195 | 
196 |
197 | This node works like Photoshop's Hue/Saturation adjustment layer. Select a color range to work on, then change the hue, saturation, and lightness of that range. Note that Stable Diffusion images seem to have pretty brutal color compression, so this node is best for subtle effects... otherwise things get pretty weird.
198 |
199 | To use this node well, you need to be aware of where the colors are placed on the color wheel. The measurements are in degrees:
200 |
201 | - **Red**: 0 degrees (and 360 degrees)
202 | - **Yellow**: 60 degrees
203 | - **Green**: 120 degrees
204 | - **Cyan**: 180 degrees
205 | - **Blue**: 240 degrees
206 | - **Magenta**: 300 degrees
207 |
208 | ### Node input controls:
209 |
210 | - **image**: The image to set the levels for.
211 | - **hue_low**: What hue (in degrees) will start the range of fully selected hues?
212 | - **hue_low_feather**: How many hue degrees will the low end of the selected hue range take to feather from fully selected to unselected?
213 | - **hue_high**: What hue (in degrees) will end the range of fully selected hues? Note that because the hue wheel is a circle, the hue_high value can be lower than the hue_low value.
214 | - **hue_high_feather**: How many hue degrees will the high end of the selected hue range take to feather from fully selected to unselected?
215 | - **hue_offset**: This value changes each pixel's hue value by rotating it this number of degrees around the color wheel.
216 | - **sat_offset**: This value increases or decreases color saturation.
217 | - **lightness_offset**: This value affects how much white or black is added to the image.
218 |
219 | ### Node Outputs
220 | - **IMAGE**: The final image
221 | - **MASK**: This is the mask generated by the hue selection process. It can be useful to ensure you are getting the result you want, or to do further processing on the same pixels.
222 |
223 |
224 |
225 | ## Blur Nodes
226 |
227 | Nodes to blur the image in various ways.
228 |
229 | ### Motion Blur / Motion Blur with Depth Map
230 |
231 | 
232 |
233 | These two nodes apply motion blur to the image. The Motion Blur with Depth Map takes a depth map image which is used to apply the blur selectively. The darker areas in the depth map will be blurred less, and the lighter areas will be blurred more.
234 |
235 | ### Node input controls:
236 |
237 | - **size**: The strength of the blur (Motion Blur node only)
238 | - **angle**: Angle of motion for the blur
239 | - **num_layers**: How many levels of depth are calculated for the blur. More layers creates a smoother blur, but can add a lot of time. (Motion Blur with Depth Map node only)
240 | - **min_blur**: The blur percentage of the darkest area of the depth map. (Motion Blur with Depth Map node only)
241 | - **max_blur**: The blur percentage of the lightest area of the depth map. (Motion Blur with Depth Map node only)
242 |
243 |
244 |
245 | ### Lens Blur / Lens Blur with Depth Map
246 |
247 | 
248 |
249 | These two nodes apply lens blur to the image. The Lens Blur with Depth Map takes a depth map image which is used to apply the blur selectively. The darker areas in the depth map will be blurred less, and the lighter areas will be blurred more.
250 |
251 | ### Node input controls:
252 |
253 | - **radius**: The strength of the blur (Lens Blur node only)
254 | - **components**: The number of lens components in the virtual lens
255 | - **exposure_gamma**: Effects the quality of the blurred areas
256 | - **num_layers**: How many levels of depth are calculated for the blur. More layers creates a smoother blur, but can add a lot of time. (Lens Blur with Depth Map node only)
257 | - **min_blur**: The blur percentage of the darkest area of the depth map. (Lens Blur with Depth Map node only)
258 | - **max_blur**: The blur percentage of the lightest area of the depth map. (Lens Blur with Depth Map node only)
259 |
260 |
261 |
262 | ### Gaussian Blur / Gaussian Blur with Depth Map
263 |
264 | 
265 |
266 | These two nodes apply lens blur to the image. The Lens Blur with Depth Map takes a depth map image which is used to apply the blur selectively. The darker areas in the depth map will be blurred less, and the lighter areas will be blurred more.
267 |
268 | ### Node input controls:
269 |
270 | - **amount**: The strength of the blur (Gaussian Blur node only)
271 | - **sigma**: The strength of the blur (Gaussian Blur with Depth Map node only)
272 | - **num_layers**: How many levels of depth are calculated for the blur. More layers creates a smoother blur, but can add a lot of time. (Gaussian Blur with Depth Map node only)
273 | - **min_blur**: The blur percentage of the darkest area of the depth map. (Gaussian Blur with Depth Map node only)
274 | - **max_blur**: The blur percentage of the lightest area of the depth map. (Gaussian Blur with Depth Map node only)
275 |
276 |
277 |
278 |
279 | ## Solid Color Nodes
280 |
281 | Creates an image of one color.
282 |
283 | ### Solid Color
284 |
285 | 
286 |
287 | This node is a simple way to create a solid color image by choosing a color from a list.
288 |
289 | ### Node input controls:
290 |
291 | - **color**: The color to make the new solid color image.
292 | - **height**: Pixel height of new solid color image.
293 | - **width**: Pixel width of new solid color image.
294 |
295 |
296 |
297 |
298 | ### Solid Color RGB
299 |
300 | 
301 |
302 | This node creatse a solid color image by setting the Red, Green, and Blue values, or one hexidecimal value.
303 |
304 | ### Node input controls:
305 |
306 | - **red, green, blue**: The amount of each primary color to include in the color image. Values are 0-255, with 0 meaning none of the primary color and 255 being 100% of that color.
307 | - **height**: Pixel height of new solid color image.
308 | - **width**: Pixel width of new solid color image.
309 | - **hex**: A hexidecimal code containing an RGB value. If this value is provided and is valid, it will be used instead of the above red, green, and blue values.
310 |
311 |
312 |
313 |
314 | ### Solid Color HSV
315 |
316 | 
317 |
318 | This node creatse a solid color image by setting the hue, saturation, and value of the color. To use this node well, you need to be aware of where the colors are placed on the color wheel. The measurements are in degrees:
319 |
320 | - **Red**: 0 degrees (and 360 degrees)
321 | - **Yellow**: 60 degrees
322 | - **Green**: 120 degrees
323 | - **Cyan**: 180 degrees
324 | - **Blue**: 240 degrees
325 | - **Magenta**: 300 degrees
326 |
327 | Note that any color with the value set to 0 will be black, but not every color with the value set to 100 will be white. If you want white, use value = 100 and saturation = 0.
328 |
329 | ### Node input controls:
330 |
331 | - **hue**: The degree value of the hue you want.
332 | - **saturation**: The percent of color saturation you want for the color.
333 | - **value**: The brightness of the color, in percentage from 0-100.
334 | - **height**: Pixel height of new solid color image.
335 | - **width**: Pixel width of new solid color image.
336 |
337 |
338 |
339 | ## Channel Nodes
340 |
341 | Nodes that work on the color channels of the image.
342 |
343 | ### Split RGB and Merge RGB
344 |
345 | 
346 |
347 | These nodes split apart images into their component color channels and merge them back together. You can do fun things with the layers once they're separate, and then combine them back together when you're done. If you want even more control when merging them back together, you can use the Linear Dodge (Add) blend mode instead (twice), which will accomplish the same thing while giving you the ability to play around with the opacities of each layer.
348 |
349 | ### Node controls:
350 |
351 | - **image**: The image to split on the Split RGB node, and the merged image on the Merge RGB node
352 | - **red, green, blue**: The separate images holding the red, green, and blue channels of the image. Note that there is nothing stopping you from using any images you want here on the Merge RGB node-- the node will only take the indicated color channel from each image.
353 |
354 |
355 |
356 |
357 | # Installation:
358 |
359 | 1. Git clone this repo into a folder in ComfyUI\custom_nodes.
360 | 2. pip install -r requirements.txt.
361 | 3. [Install FFmpeg](https://ffmpeg.org/download.html), which is required for the Selective Color Node.
362 |
363 | **Please let me know if you have any thoughts or suggestions!**
364 |
365 |
366 |
367 |
368 |
369 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 | from .blendmodes import BlendModes
2 | from .selectivecolor import SelectiveColor
3 | from .contrast import Levels
4 | from .blendif import BlendIf
5 | from .colors import SplitRGB, MergeRGB
6 | from .colors import ColorBalance, ColorBalanceAdvanced
7 | from .colors import BlackAndWhite
8 | from .colors import HueSatAdvanced, HueSat
9 | from .colors import SolidColorRGB, SolidColorHSV, SolidColor
10 | from .blur import MotionBlur, LensBlur, GaussianBlur, MotionBlurDepth, LensBlurDepth, GaussianBlurDepth
11 |
12 | NODE_CLASS_MAPPINGS = {
13 | "BlackAndWhite": BlackAndWhite,
14 | "BlendIf": BlendIf,
15 | "BlendModes": BlendModes,
16 | "ColorBalance": ColorBalance,
17 | "ColorBalanceAdvanced": ColorBalanceAdvanced,
18 | "HueSat": HueSat,
19 | "HueSatAdvanced": HueSatAdvanced,
20 | "Levels": Levels,
21 | "LensBlur": LensBlur,
22 | "MotionBlur": MotionBlur,
23 | "GaussianBlur": GaussianBlur,
24 | "LensBlurDepth": LensBlurDepth,
25 | "MotionBlurDepth": MotionBlurDepth,
26 | "GaussianBlurDepth": GaussianBlurDepth,
27 | "MergeRGB": MergeRGB,
28 | "SplitRGB": SplitRGB,
29 | "SelectiveColor": SelectiveColor,
30 | "SolidColor": SolidColor,
31 | "SolidColorRGB": SolidColorRGB,
32 | "SolidColorHSV": SolidColorHSV
33 | }
34 |
35 | NODE_DISPLAY_NAME_MAPPINGS = {
36 | "BlackAndWhite": "Black and White",
37 | "BlendIf": "Blend If",
38 | "BlendModes": "Blend Modes",
39 | "ColorBalance": "Color Balance",
40 | "ColorBalanceAdvanced": "Color Balance Advanced",
41 | "HueSat": "Hue/Saturation",
42 | "HueSatAdvanced": "Hue/Saturation Advanced",
43 | "Levels": "Levels",
44 | "LensBlur": "Lens Blur",
45 | "MotionBlur":"Motion Blur",
46 | "GaussianBlur": "Gaussian Blur",
47 | "LensBlurDepth": "Lens Blur with Depth Map",
48 | "MotionBlurDepth":"Motion Blur with Depth Map",
49 | "GaussianBlurDepth": "Gaussian Blur with Depth Map",
50 | "MergeRGB": "Merge RGB",
51 | "SplitRGB": "Split RGB",
52 | "SelectiveColor": "Selective Color",
53 | "SolidColor": "Solid Color",
54 | "SolidColorRGB": "Solid Color RGB",
55 | "SolidColorHSV": "Solid Color HSV"
56 | }
57 |
58 | __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
--------------------------------------------------------------------------------
/blendif.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Blend If
4 | @nickname: Virtuoso Pack - Blend If
5 | @description: This extension provides a "Blend If (BlendIf)" node.
6 | """
7 | import torch
8 | from .resize import match_sizes
9 |
10 | class BlendIf:
11 |
12 | def __init__(self):
13 | pass
14 |
15 | @classmethod
16 | def INPUT_TYPES(s):
17 |
18 | return {
19 | "required": {
20 | "top_layer": ("IMAGE",),
21 | "bottom_layer": ("IMAGE",),
22 | "blend_if_layer": (["top", "bottom"],),
23 | "blend_if_channel": (["gray", "red", "green", "blue"],),
24 | "start_rise": ("FLOAT", {
25 | "default": 0.0,
26 | "min": 0.0,
27 | "max": 1.0,
28 | "step": 0.01,
29 | "round": 0.001,
30 | "display": "number"}),
31 | "end_rise": ("FLOAT", {
32 | "default": 0.0,
33 | "min": 0.0,
34 | "max": 1.0,
35 | "step": 0.01,
36 | "round": 0.001,
37 | "display": "number"}),
38 | "start_fall": ("FLOAT", {
39 | "default": 1.0,
40 | "min": 0.0,
41 | "max": 1.0,
42 | "step": 0.01,
43 | "round": 0.001,
44 | "display": "number"}),
45 | "end_fall": ("FLOAT", {
46 | "default": 1.0,
47 | "min": 0.0,
48 | "max": 1.0,
49 | "step": 0.01,
50 | "round": 0.001,
51 | "display": "number"}),
52 | "opacity": ("FLOAT", {
53 | "default": 1.0,
54 | "min": 0.0,
55 | "max": 1.0,
56 | "step": 0.01,
57 | "round": 0.001,
58 | "display": "number"}),
59 | "match_size": (["crop", "stretch"],),
60 | "invert_mask": (["yes", "no"],),
61 | },
62 | "optional": {
63 | "mask": ("MASK",),
64 | }
65 | }
66 |
67 | RETURN_TYPES = ("IMAGE","MASK")
68 | FUNCTION = "do_blendif"
69 | CATEGORY = "Virtuoso"
70 |
71 | def do_blendif(self, top_layer, bottom_layer, blend_if_layer, blend_if_channel, start_rise, end_rise, start_fall, end_fall, opacity, match_size, invert_mask, mask=None):
72 |
73 | t = top_layer.clone()
74 | b = bottom_layer.clone()
75 |
76 | # Ensure the parameters are in order
77 | parameters = [end_fall, start_fall, end_rise, start_rise]
78 | for i in range(len(parameters) - 1):
79 | for j in range(i + 1, len(parameters)):
80 | if parameters[i] < parameters[j]:
81 | parameters[i] = parameters[j]
82 | end_fall_adjusted, start_fall_adjusted, end_rise_adjusted, start_rise_adjusted = parameters
83 |
84 | # Remove alpha channel if it exists (we use mask parameter if passed in)
85 | if t.shape[-1] == 4:
86 | t = t[..., :3]
87 | if b.shape[-1] == 4:
88 | b = b[..., :3]
89 |
90 | t, m = match_sizes(match_size, top_layer, bottom_layer, mask)
91 |
92 | # Invert the mask if required
93 | if invert_mask == 'yes' and m is not None:
94 | m = 1 - m
95 |
96 | # Calculate the base opacity
97 | if blend_if_channel == 'gray':
98 | if blend_if_layer == 'bottom':
99 | luminosity = 0.2126 * b[..., 0] + 0.7152 * b[..., 1] + 0.0722 * b[..., 2]
100 | else: # blend_if_layer == 'top'
101 | luminosity = 0.2126 * t[..., 0] + 0.7152 * t[..., 1] + 0.0722 * t[..., 2]
102 | base_opacity = calculate_opacity(luminosity, start_rise_adjusted, end_rise_adjusted, start_fall_adjusted, end_fall_adjusted)
103 | else:
104 | channel_index = {'red': 0, 'green': 1, 'blue': 2}[blend_if_channel]
105 | if blend_if_layer == 'bottom':
106 | base_opacity = calculate_opacity(b[..., channel_index], start_rise_adjusted, end_rise_adjusted, start_fall_adjusted, end_fall_adjusted)
107 | else: # blend_if_layer == 'top'
108 | base_opacity = calculate_opacity(t[..., channel_index], start_rise_adjusted, end_rise_adjusted, start_fall_adjusted, end_fall_adjusted)
109 |
110 | # Apply the mask and the opacity parameter
111 | if m is not None:
112 | final_opacity = base_opacity * m * opacity
113 | else:
114 | final_opacity = base_opacity * opacity
115 |
116 | # Composite the top_layer onto the bottom_layer
117 | new_image = final_opacity[..., None] * t + (1.0 - final_opacity[..., None]) * b
118 |
119 | return (new_image, base_opacity)
120 |
121 |
122 | def calculate_opacity(t, start_rise, end_rise, start_fall, end_fall):
123 | # Values to the left of start_rise and to the right of end_fall return 0
124 | opacity = torch.zeros_like(t)
125 | # Apply cubic-bezier curve between start_rise and end_rise
126 | rise_mask = (t > start_rise) & (t < end_rise)
127 | t_normalized = (t[rise_mask] - start_rise) / (end_rise - start_rise)
128 | opacity[rise_mask] = 3 * t_normalized**2 - 2 * t_normalized**3
129 | # Values between end_rise and start_fall return 1
130 | opacity[(t >= end_rise) & (t <= start_fall)] = 1.0
131 | # Apply cubic-bezier curve between start_fall and end_fall
132 | fall_mask = (t > start_fall) & (t < end_fall)
133 | t_normalized = (t[fall_mask] - start_fall) / (end_fall - start_fall)
134 | opacity[fall_mask] = 1 - (3 * t_normalized**2 - 2 * t_normalized**3)
135 | return opacity
--------------------------------------------------------------------------------
/blendmodes.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Blend Modes
4 | @nickname: Virtuoso Pack - Blend Nodes
5 | @description: This extension provides a blend modes node with 30 blend modes.
6 | """
7 | import numpy as np
8 | import torch
9 | import torch.nn.functional as F
10 | from blend_modes import grain_extract, grain_merge
11 | from .resize import match_sizes
12 | from .hsv import rgb_to_hsv, hsv_to_rgb
13 |
14 | modes_8bit = ["grain extract", "grain merge"]
15 |
16 | class BlendModes:
17 |
18 | def __init__(self):
19 | pass
20 |
21 | @classmethod
22 | def INPUT_TYPES(s):
23 |
24 | return {
25 | "required": {
26 | "backdrop": ("IMAGE",),
27 | "source": ("IMAGE",),
28 | "blend_mode": (["normal", "dissolve", "darken", "multiply", "color burn", "linear burn", "darker color",
29 | "lighten", "screen", "color dodge", "linear dodge (add)", "lighter color",
30 | "overlay", "soft light", "hard light", "vivid light", "linear light", "pin light", "hard mix",
31 | "difference", "exclusion", "subtract", "divide",
32 | "hue", "saturation", "color", "luminosity",
33 | "grain extract", "grain merge"],),
34 | "opacity": ("FLOAT", {
35 | "default": 1.0,
36 | "min": 0.0,
37 | "max": 1.0,
38 | "step": 0.01,
39 | "round": 0.001,
40 | "display": "number"}),
41 | "source_adjust": (["crop", "stretch"],),
42 | "invert_mask": (["yes", "no"],),
43 | },
44 | "optional": {
45 | "mask": ("MASK",),
46 | }
47 | }
48 |
49 | RETURN_TYPES = ("IMAGE",)
50 | FUNCTION = "do_blend"
51 | CATEGORY = "Virtuoso"
52 |
53 | def do_blend(self, backdrop, source, blend_mode, opacity, source_adjust, invert_mask, mask=None ):
54 |
55 | backdrop_prepped = handle_alpha(backdrop, False)
56 | source_prepped = handle_alpha(source, invert_mask, mask)
57 | source_prepped, _ = match_sizes(source_adjust, source_prepped, backdrop_prepped)
58 | if blend_mode in modes_8bit:
59 | source_prepped = source_prepped.squeeze(0)
60 | backdrop_prepped = backdrop_prepped.squeeze(0)
61 | source_prepped = source_prepped * 255
62 | backdrop_prepped = backdrop_prepped * 255
63 | final_tensor = torch.from_numpy(modes[blend_mode](backdrop_prepped.numpy(), source_prepped.numpy(), opacity)).unsqueeze(0)
64 | else:
65 | final_tensor = modes[blend_mode](backdrop_prepped, source_prepped, opacity)
66 |
67 | return (final_tensor,)
68 |
69 | def handle_alpha(img, invert_mask="true", mask=None):
70 |
71 | alpha_img = img.clone()
72 |
73 | if mask is None:
74 | if alpha_img.shape[3] == 4: # If img already has an alpha channel, use it
75 | alpha_channel = alpha_img[:, :, 3:4]
76 | else:
77 | alpha_channel = torch.full((1, alpha_img.shape[1], alpha_img.shape[2], 1), fill_value=1, dtype=img.dtype, device=img.device)
78 | else:
79 | alpha_channel = mask.clone()
80 | if invert_mask == "yes":
81 | alpha_channel = 1 - alpha_channel
82 | _, h, w, _ = alpha_img.shape
83 | alpha_channel = F.interpolate(alpha_channel[None, ...], size=(h, w), mode='bilinear', align_corners=False)[0]
84 |
85 | if len(alpha_channel.shape) < len(alpha_img.shape):
86 | alpha_channel = alpha_channel.unsqueeze(-1)
87 |
88 | if alpha_img.shape[3] == 4: # If img already has an alpha channel, replace it
89 | alpha_img[:, :, 3:4] = alpha_channel
90 | else:
91 | batch_size = alpha_img.shape[0]
92 | alpha_channel_repeated = alpha_channel.repeat(batch_size, 1, 1, 1)
93 | alpha_img = torch.cat((alpha_img, alpha_channel_repeated), dim=3)
94 |
95 | return alpha_img
96 |
97 | def dissolve(backdrop, source, opacity):
98 |
99 | transparency = opacity * source[..., 3]
100 | random_matrix = torch.rand_like(transparency)
101 | mask = random_matrix < transparency
102 |
103 | # Use the mask to select pixels from the source or backdrop
104 | blend = torch.where(mask[..., None], source[..., :3], backdrop[..., :3])
105 |
106 | # Apply the alpha channel of the source image to the blended image
107 | new_rgb = (1 - source[..., 3, None]) * backdrop[..., :3] + source[..., 3, None] * blend
108 |
109 | # Ensure the RGB values are within the valid range
110 | new_rgb = torch.clamp(new_rgb, 0, 1)
111 |
112 | # Calculate the new alpha value by taking the maximum of the backdrop and source alpha channels
113 | new_alpha = torch.max(backdrop[..., 3], source[..., 3])
114 |
115 | # Create a new RGBA image with the calculated RGB and alpha values
116 | result = torch.cat((new_rgb, new_alpha[..., None]), dim=-1)
117 |
118 | return result
119 |
120 | def hsv(backdrop, source, opacity, channel):
121 |
122 | source_alpha = source[:, :, :, 3:4]
123 |
124 | # Convert RGB to HSV
125 | backdrop_hsv = rgb_to_hsv(backdrop)
126 | source_hsv = rgb_to_hsv(source)
127 |
128 | new_hsv = backdrop_hsv.clone()
129 | if channel == "saturation":
130 | new_hsv[:, :, :, 1:2] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, :, 1:2] + opacity * source_alpha * source_hsv[:, :, :, 1:2]
131 | elif channel == "luminance":
132 | new_hsv[:, :, :, 2:3] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, :, 2:3] + opacity * source_alpha * source_hsv[:, :, :, 2:3]
133 | elif channel == "hue":
134 | new_hue = source_hsv[:, :, :, 0:1]
135 | mask = (source_hsv[:, :, :, 1:2] == 0) # if sat == 0, sat = 0 in new image
136 | new_saturation = torch.where(mask, source_hsv[:, :, :, 1:2], backdrop_hsv[:, :, :, 1:2])
137 | new_hsv[:, :, :, 0:1] = new_hue
138 | new_hsv[:, :, :, 1:2] = new_saturation
139 | elif channel == "color":
140 | new_hsv[:, :, :, :2] = (1 - opacity * source_alpha) * backdrop_hsv[:, :, :, :2] + opacity * source_alpha * source_hsv[:, :, :, :2]
141 |
142 | new_rgb = hsv_to_rgb(new_hsv)
143 | new_rgb = (1 - source_alpha * opacity) * backdrop + source_alpha * opacity * new_rgb
144 | new_rgb = torch.clamp(new_rgb, 0, 1)
145 | rgb_channels = new_rgb[:, :, :, :3]
146 | backdrop_alpha = backdrop[:, :, :, 3:4]
147 | new_img = torch.cat((rgb_channels, backdrop_alpha), dim=-1)
148 | return new_img
149 |
150 | def saturation(backdrop, source, opacity):
151 | return hsv(backdrop, source, opacity, "saturation")
152 |
153 | def luminance(backdrop, source, opacity):
154 | return hsv(backdrop, source, opacity, "luminance")
155 |
156 | def hue(backdrop, source, opacity):
157 | return hsv(backdrop, source, opacity, "hue")
158 |
159 | def color(backdrop, source, opacity):
160 | return hsv(backdrop, source, opacity, "color")
161 |
162 | def darker_lighter_color(backdrop, source, opacity, type):
163 |
164 | # Convert RGB to HSV
165 | backdrop_hsv = rgb_to_hsv(backdrop)
166 | source_hsv = rgb_to_hsv(source)
167 |
168 | # Create a mask where the value (brightness) of the source image is less than the value of the backdrop image
169 | if type == "dark":
170 | mask = source_hsv[:, :, :, 2] < backdrop_hsv[:, :, :, 2]
171 | else:
172 | mask = source_hsv[:, :, :, 2] > backdrop_hsv[:, :, :, 2]
173 |
174 | # Use the mask to select pixels from the source or backdrop
175 | blend = torch.where(mask.unsqueeze(-1), source, backdrop)
176 |
177 | source_alpha = source[:, :, :, 3:4]
178 | new_rgb = (1 - source_alpha * opacity) * backdrop + source_alpha * opacity * blend
179 | rgb_channels = new_rgb[:, :, :, :3]
180 | backdrop_alpha = backdrop[:, :, :, 3:4]
181 | new_img = torch.cat((rgb_channels, backdrop_alpha), dim=-1)
182 | return new_img
183 |
184 | def darker_color(backdrop, source, opacity):
185 | return darker_lighter_color(backdrop, source, opacity, "dark")
186 |
187 | def lighter_color(backdrop, source, opacity):
188 | return darker_lighter_color(backdrop, source, opacity, "light")
189 |
190 | def simple_mode(backdrop, source, opacity, mode):
191 |
192 | if mode == "linear_burn":
193 | blend = backdrop + source - 1
194 | elif mode == "darken_only":
195 | rgb_min = torch.min(backdrop[..., :3], source[..., :3])
196 | alpha = backdrop[..., 3:]
197 | blend = torch.cat([rgb_min, alpha], dim=-1)
198 | elif mode == "lighten_only":
199 | rgb_min = torch.max(backdrop[..., :3], source[..., :3])
200 | alpha = backdrop[..., 3:]
201 | blend = torch.cat([rgb_min, alpha], dim=-1)
202 | elif mode == "difference":
203 | blend = abs(backdrop - source)
204 | elif mode == "normal":
205 | blend = source
206 | elif mode == "addition":
207 | blend = source + backdrop
208 | elif mode == "multiply":
209 | blend = source * backdrop
210 | elif mode == "divide":
211 | blend = backdrop / source
212 | elif mode == "screen":
213 | blend = 1 - (1-source)*(1-backdrop)
214 | elif mode == "linear_light":
215 | blend = backdrop + (2 * source) - 1
216 | elif mode == "color_dodge":
217 | blend = backdrop / (1 - source)
218 | elif mode == "color_burn":
219 | blend = 1 - ((1 - backdrop) / source)
220 | elif mode == "exclusion":
221 | blend = backdrop + source - (2 * backdrop * source)
222 | elif mode == "subtract":
223 | blend = backdrop - source
224 | elif mode == "soft_light":
225 | blend = torch.where(source <= 0.5, 2 * backdrop * source + backdrop * backdrop * (1 - 2 * source), 2 * backdrop * (1 - source) + torch.sqrt(backdrop) * ((2 * source) - 1))
226 | elif mode == "overlay":
227 | blend = torch.where(backdrop <= 0.5, 2 * backdrop * source, 1 - 2 * (1 - backdrop) * (1 - source))
228 | elif mode == "hard_light":
229 | blend = torch.where(source <= 0.5, 2 * source * backdrop, 1 - 2 * (1 - backdrop) * (1 - source))
230 | elif mode == "vivid_light":
231 | blend = torch.where(source <= 0.5, backdrop / (1 - 2 * source), 1 - (1 -backdrop) / (2 * source - 0.5) )
232 | elif mode == "pin_light":
233 | blend = torch.where(source <= 0.5, torch.minimum(backdrop, 2 * source), torch.maximum(backdrop, 2 * (source - 0.5)))
234 | elif mode == "hard_mix":
235 | blend = simple_mode(backdrop, source, opacity, "linear_light")
236 | rgb_channels = torch.round(blend[:, :, :, :3])
237 | alpha_channel = blend[:, :, :, 3:4]
238 | blend = torch.cat((rgb_channels, alpha_channel), dim=-1)
239 |
240 | blend = torch.clamp(blend, 0, 1)
241 |
242 | source_alpha = source[:, :, :, 3:4]
243 | new_rgb = (1 - source_alpha * opacity) * backdrop + source_alpha * opacity * blend
244 | rgb_channels = new_rgb[:, :, :, :3]
245 | backdrop_alpha = backdrop[:, :, :, 3:4]
246 | new_img = torch.cat((rgb_channels, backdrop_alpha), dim=-1)
247 | return new_img
248 |
249 | def normal(backdrop, source, opacity):
250 | return simple_mode(backdrop, source, opacity, "normal")
251 | def difference(backdrop, source, opacity):
252 | return simple_mode(backdrop, source, opacity, "difference")
253 | def multiply(backdrop, source, opacity):
254 | return simple_mode(backdrop, source, opacity, "multiply")
255 | def divide(backdrop, source, opacity):
256 | return simple_mode(backdrop, source, opacity, "divide")
257 | def addition(backdrop, source, opacity):
258 | return simple_mode(backdrop, source, opacity, "addition")
259 | def linear_light(backdrop, source, opacity):
260 | return simple_mode(backdrop, source, opacity, "linear_light")
261 | def vivid_light(backdrop, source, opacity):
262 | return simple_mode(backdrop, source, opacity, "vivid_light")
263 | def pin_light(backdrop, source, opacity):
264 | return simple_mode(backdrop, source, opacity, "pin_light")
265 | def hard_mix(backdrop, source, opacity):
266 | return simple_mode(backdrop, source, opacity, "hard_mix")
267 | def linear_burn(backdrop, source, opacity):
268 | return simple_mode(backdrop, source, opacity, "linear_burn")
269 | def color_dodge(backdrop, source, opacity):
270 | return simple_mode(backdrop, source, opacity, "color_dodge")
271 | def color_burn(backdrop, source, opacity):
272 | return simple_mode(backdrop, source, opacity, "color_burn")
273 | def exclusion(backdrop, source, opacity):
274 | return simple_mode(backdrop, source, opacity, "exclusion")
275 | def subtract(backdrop, source, opacity):
276 | return simple_mode(backdrop, source, opacity, "subtract")
277 | def screen(backdrop, source, opacity):
278 | return simple_mode(backdrop, source, opacity, "screen")
279 | def soft_light(backdrop, source, opacity):
280 | return simple_mode(backdrop, source, opacity, "soft_light")
281 | def hard_light(backdrop, source, opacity):
282 | return simple_mode(backdrop, source, opacity, "hard_light")
283 | def overlay(backdrop, source, opacity):
284 | return simple_mode(backdrop, source, opacity, "overlay")
285 | def darken_only(backdrop, source, opacity):
286 | return simple_mode(backdrop, source, opacity, "darken_only")
287 | def lighten_only(backdrop, source, opacity):
288 | return simple_mode(backdrop, source, opacity, "lighten_only")
289 |
290 | modes = {
291 | "difference": difference,
292 | "exclusion": exclusion,
293 | "dissolve": dissolve,
294 | "normal": normal,
295 | "screen": screen,
296 | "soft light": soft_light,
297 | "lighten": lighten_only,
298 | "lighter color": lighter_color,
299 | "dodge": color_dodge,
300 | "color dodge": color_dodge,
301 | "linear burn": linear_burn,
302 | "linear dodge (add)": addition,
303 | "linear light": linear_light,
304 | "vivid light": vivid_light,
305 | "pin light": pin_light,
306 | "hard mix": hard_mix,
307 | "darken": darken_only,
308 | "darker color": darker_color,
309 | "multiply": multiply,
310 | "color burn": color_burn,
311 | "hard light": hard_light,
312 | "subtract": subtract,
313 | "grain extract": grain_extract,
314 | "grain merge": grain_merge,
315 | "divide": divide,
316 | "overlay": overlay,
317 | "hue": hue,
318 | "saturation": saturation,
319 | "color": color,
320 | "luminosity": luminance
321 | }
--------------------------------------------------------------------------------
/blur.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Blur
4 | @nickname: Virtuoso Pack - Blur
5 | @description: This extension provides blur nodes.
6 | """
7 | import torch
8 | import cv2
9 | import numpy as np
10 | from blurgenerator import motion_blur, motion_blur_with_depth_map, \
11 | lens_blur, lens_blur_with_depth_map, \
12 | gaussian_blur, gaussian_blur_with_depth_map
13 |
14 | class MotionBlur:
15 |
16 | def __init__(self):
17 | pass
18 |
19 | @classmethod
20 | def INPUT_TYPES(s):
21 |
22 | return {
23 | "required": {
24 | "image": ("IMAGE",),
25 | "size": ("INT", {
26 | "default": 100.0,
27 | "min": 0.0,
28 | "max": 4096.0,
29 | "step": 0.1,
30 | "round": 0.01,
31 | "display": "number"}),
32 | "angle": ("INT", {
33 | "default": 0.0,
34 | "min": 0.0,
35 | "max": 360.0,
36 | "step": 0.1,
37 | "round": 0.01,
38 | "display": "number"})
39 | }
40 | }
41 |
42 | RETURN_TYPES = ("IMAGE",)
43 | FUNCTION = "do_blur"
44 | CATEGORY = "Virtuoso/Blur"
45 |
46 | def do_blur(self, image, size, angle):
47 | return blur(image, "motion", size=size, angle=angle)
48 |
49 | class LensBlur:
50 |
51 | def __init__(self):
52 | pass
53 |
54 | @classmethod
55 | def INPUT_TYPES(s):
56 |
57 | return {
58 | "required": {
59 | "image": ("IMAGE",),
60 | "radius": ("INT", {
61 | "default": 5,
62 | "min": 1,
63 | "max": 4096,
64 | "step": 1,
65 | "round": 1,
66 | "display": "number"}),
67 | "components": ("INT", {
68 | "default": 4,
69 | "min": 1,
70 | "max": 6,
71 | "step": 1,
72 | "round": 1,
73 | "display": "number"}),
74 | "exposure_gamma": ("FLOAT", {
75 | "default": 2,
76 | "min": -100,
77 | "max": 100,
78 | "step": 0.01,
79 | "round": 0.01,
80 | "display": "number"})
81 | }
82 | }
83 |
84 | RETURN_TYPES = ("IMAGE",)
85 | FUNCTION = "do_blur"
86 | CATEGORY = "Virtuoso/Blur"
87 |
88 | def do_blur(self, image, radius, components, exposure_gamma):
89 | return blur(image, "lens", radius=radius, components=components, exposure_gamma=exposure_gamma)
90 |
91 | class GaussianBlur:
92 |
93 | def __init__(self):
94 | pass
95 |
96 | @classmethod
97 | def INPUT_TYPES(s):
98 |
99 | return {
100 | "required": {
101 | "image": ("IMAGE",),
102 | "amount": ("INT", {
103 | "default": 100,
104 | "min": 1,
105 | "max": 100,
106 | "step": 1,
107 | "round": 1,
108 | "display": "number"})
109 | }
110 | }
111 |
112 | RETURN_TYPES = ("IMAGE",)
113 | FUNCTION = "do_blur"
114 | CATEGORY = "Virtuoso/Blur"
115 |
116 | def do_blur(self, image, amount):
117 | return blur(image, "gaussian", amount=amount)
118 |
119 | class MotionBlurDepth:
120 |
121 | def __init__(self):
122 | pass
123 |
124 | @classmethod
125 | def INPUT_TYPES(s):
126 |
127 | return {
128 | "required": {
129 | "image": ("IMAGE",),
130 | "depth_map": ("IMAGE",),
131 | "angle": ("INT", {
132 | "default": 0.0,
133 | "min": 0.0,
134 | "max": 360.0,
135 | "step": 0.1,
136 | "round": 0.01,
137 | "display": "number"}),
138 | "num_layers": ("INT", {
139 | "default": 10,
140 | "min": 1,
141 | "max": 100,
142 | "step": 1,
143 | "round": 1,
144 | "display": "number"}),
145 | "min_blur": ("INT", {
146 | "default": 1,
147 | "min": 1,
148 | "max": 100,
149 | "step": 1,
150 | "round": 1,
151 | "display": "number"}),
152 | "max_blur": ("INT", {
153 | "default": 100,
154 | "min": 1,
155 | "max": 100,
156 | "step": 1,
157 | "round": 1,
158 | "display": "number"})
159 | }
160 | }
161 |
162 | RETURN_TYPES = ("IMAGE",)
163 | FUNCTION = "do_blur"
164 | CATEGORY = "Virtuoso/Blur"
165 |
166 | def do_blur(self, image, depth_map, angle, num_layers, min_blur, max_blur):
167 | return blur(image, "motion_depth", depth_map=depth_map, angle=angle, num_layers=num_layers, min_blur=min_blur, max_blur=max_blur)
168 |
169 | class LensBlurDepth:
170 |
171 | def __init__(self):
172 | pass
173 |
174 | @classmethod
175 | def INPUT_TYPES(s):
176 |
177 | return {
178 | "required": {
179 | "image": ("IMAGE",),
180 | "depth_map": ("IMAGE",),
181 | "components": ("INT", {
182 | "default": 4,
183 | "min": 1,
184 | "max": 6,
185 | "step": 1,
186 | "round": 1,
187 | "display": "number"}),
188 | "exposure_gamma": ("FLOAT", {
189 | "default": 2,
190 | "min": -100,
191 | "max": 100,
192 | "step": 0.01,
193 | "round": 0.01,
194 | "display": "number"}),
195 | "num_layers": ("INT", {
196 | "default": 10,
197 | "min": 1,
198 | "max": 100,
199 | "step": 1,
200 | "round": 1,
201 | "display": "number"}),
202 | "min_blur": ("INT", {
203 | "default": 1,
204 | "min": 1,
205 | "max": 100,
206 | "step": 1,
207 | "round": 1,
208 | "display": "number"}),
209 | "max_blur": ("INT", {
210 | "default": 100,
211 | "min": 1,
212 | "max": 100,
213 | "step": 1,
214 | "round": 1,
215 | "display": "number"})
216 | }
217 | }
218 |
219 | RETURN_TYPES = ("IMAGE",)
220 | FUNCTION = "do_blur"
221 | CATEGORY = "Virtuoso/Blur"
222 |
223 | def do_blur(self, image, depth_map, components, exposure_gamma, num_layers, min_blur, max_blur):
224 | return blur(image, "lens_depth", depth_map=depth_map, components=components, exposure_gamma=exposure_gamma, num_layers=num_layers, min_blur=min_blur, max_blur=max_blur)
225 |
226 | class GaussianBlurDepth:
227 |
228 | def __init__(self):
229 | pass
230 |
231 | @classmethod
232 | def INPUT_TYPES(s):
233 |
234 | return {
235 | "required": {
236 | "image": ("IMAGE",),
237 | "depth_map": ("IMAGE",),
238 | "sigma": ("INT", {
239 | "default": 5,
240 | "min": 1,
241 | "max": 100,
242 | "step": 1,
243 | "round": 1,
244 | "display": "number"}),
245 | "num_layers": ("INT", {
246 | "default": 10,
247 | "min": 1,
248 | "max": 100,
249 | "step": 1,
250 | "round": 1,
251 | "display": "number"}),
252 | "min_blur": ("INT", {
253 | "default": 1,
254 | "min": 1,
255 | "max": 100,
256 | "step": 1,
257 | "round": 1,
258 | "display": "number"}),
259 | "max_blur": ("INT", {
260 | "default": 100,
261 | "min": 1,
262 | "max": 100,
263 | "step": 1,
264 | "round": 1,
265 | "display": "number"})
266 | }
267 | }
268 |
269 | RETURN_TYPES = ("IMAGE",)
270 | FUNCTION = "do_blur"
271 | CATEGORY = "Virtuoso/Blur"
272 |
273 | def do_blur(self, image, depth_map, sigma, num_layers, min_blur, max_blur):
274 | return blur(image, "gaussian_depth", depth_map=depth_map, sigma=sigma, num_layers=num_layers, min_blur=min_blur, max_blur=max_blur)
275 |
276 |
277 | def blur(image, type, depth_map=None, **kwargs):
278 |
279 | if type in ["lens_depth", "gaussian_depth", "motion_depth"]:
280 | if depth_map.shape[3] == 4:
281 | depth_map = depth_map[:, :, :, :3] # Remove alpha channel if it exists
282 |
283 | # If batch size of depth_map does not match with image, use the first depth_map for all images
284 | if depth_map.shape[0] != image.shape[0]:
285 | depth_map = depth_map[0].unsqueeze(0).repeat(image.shape[0], 1, 1, 1)
286 |
287 | if image.shape[3] == 4:
288 | original_alpha = image[:, :, :, 3]
289 | image = image[:, :, :, :3]
290 | else:
291 | original_alpha = None
292 |
293 | blurred_images = []
294 | for i, img in enumerate(image):
295 | img_cv2 = img.cpu().numpy()
296 | img_cv2 = (img_cv2 * 255).astype(np.uint8)
297 | img_cv2 = cv2.cvtColor(img_cv2, cv2.COLOR_RGB2BGR)
298 |
299 | if type == "gaussian":
300 | blurred_img_cv2 = gaussian_blur(img_cv2, kwargs["amount"])
301 | elif type == "lens":
302 | blurred_img_cv2 = lens_blur(img_cv2, kwargs["radius"], kwargs["components"], kwargs["exposure_gamma"])
303 | elif type == "motion":
304 | blurred_img_cv2 = motion_blur(img_cv2, kwargs["size"], kwargs["angle"])
305 | else: #depth map blur
306 | depth_map_img = depth_map[i].cpu().numpy()
307 | depth_map_img = (depth_map_img * 255).astype(np.uint8)
308 | if type == "motion_depth":
309 | blurred_img_cv2 = motion_blur_with_depth_map(img_cv2, depth_map=depth_map_img, angle=kwargs["angle"], num_layers=kwargs["num_layers"], min_blur=kwargs["min_blur"], max_blur=kwargs["max_blur"])
310 | elif type == "lens_depth":
311 | blurred_img_cv2 = lens_blur_with_depth_map(img_cv2, depth_map=depth_map_img, components=kwargs["components"], exposure_gamma=kwargs["exposure_gamma"], num_layers=kwargs["num_layers"], min_blur=kwargs["min_blur"], max_blur=kwargs["max_blur"])
312 | elif type == "gaussian_depth":
313 | blurred_img_cv2 = gaussian_blur_with_depth_map(img_cv2, depth_map=depth_map_img, sigma=kwargs["sigma"], num_layers=kwargs["num_layers"], min_blur=kwargs["min_blur"], max_blur=kwargs["max_blur"])
314 | blurred_img = cv2.cvtColor(blurred_img_cv2, cv2.COLOR_BGR2RGB)
315 | blurred_img = torch.from_numpy(blurred_img.astype(np.float32) / 255.0).to(image.device)
316 | blurred_images.append(blurred_img)
317 |
318 | final_tensor = torch.stack(blurred_images)
319 |
320 | if original_alpha is not None:
321 | final_tensor = torch.cat((final_tensor, original_alpha.unsqueeze(3)), dim=3)
322 |
323 | return (final_tensor, )
--------------------------------------------------------------------------------
/colors.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Color Nodes
4 | @nickname: Virtuoso Pack - Color Nodes
5 | @description: This extension provides a solid color node, Color Balance Node, Color Balance Advanced Node,
6 | SplitRGB and MergeRGB nodes, Hue/Saturation, Hue/Saturation Advanced,
7 | SolidColorRGB, SolidColorHSV, and Black and White nodes.
8 | """
9 | import torch
10 | from scipy.interpolate import CubicSpline
11 | import colorsys
12 | from .hsv import rgb_to_hsv, hsv_to_rgb
13 |
14 | class SolidColorRGB():
15 | NAME = "Solid Color RGB"
16 | CATEGORY = "Virtuoso/Solid Color"
17 | RETURN_TYPES = ("IMAGE",)
18 | RETURN_NAMES = ('solid color image',)
19 | FUNCTION = "get_solid_color"
20 |
21 | @classmethod
22 | def INPUT_TYPES(s) -> dict:
23 | return {
24 | "required": {
25 | "red": ("FLOAT", {
26 | "default": 0,
27 | "min": 0,
28 | "max": 255.0,
29 | "step": 1,
30 | "round": 0.1,
31 | "display": "number"}),
32 | "green": ("FLOAT", {
33 | "default": 0,
34 | "min": 0,
35 | "max": 255.0,
36 | "step": 1,
37 | "round": 0.1,
38 | "display": "number"}),
39 | "blue": ("FLOAT", {
40 | "default": 0,
41 | "min": 0,
42 | "max": 255.0,
43 | "step": 1,
44 | "round": 0.1,
45 | "display": "number"}),
46 | "height": ("INT", {
47 | "default": 1024,
48 | "min": 1,
49 | "max": 4096,
50 | "step": 1,
51 | "round": 1,
52 | "display": "number"}),
53 | "width": ("INT", {
54 | "default": 1024,
55 | "min": 1,
56 | "max": 4096,
57 | "step": 1,
58 | "round": 1,
59 | "display": "number"}),
60 | },
61 | "optional":{
62 | "hex": ("STRING", {
63 | "default": ""
64 | }),
65 | }
66 | }
67 |
68 | def get_solid_color(self, red, green, blue, height, width, hex=""):
69 |
70 | validated_hex = validate_hex_code(hex)
71 |
72 | if validated_hex == "":
73 | return (create_solid_rgb(red, green, blue, height, width), )
74 | else:
75 | return (create_solid_hex(validated_hex, height, width), )
76 |
77 | class SolidColorHSV():
78 | NAME = "Solid Color HSV"
79 | CATEGORY = "Virtuoso/Solid Color"
80 | RETURN_TYPES = ("IMAGE",)
81 | RETURN_NAMES = ('solid color image',)
82 | FUNCTION = "get_solid_color"
83 |
84 | @classmethod
85 | def INPUT_TYPES(s) -> dict:
86 | return {
87 | "required": {
88 | "hue": ("FLOAT", {
89 | "default": 0,
90 | "min": 0,
91 | "max": 360.0,
92 | "step": 1,
93 | "round": 0.1,
94 | "display": "number"}),
95 | "saturation": ("FLOAT", {
96 | "default": 50,
97 | "min": 0,
98 | "max": 100.0,
99 | "step": 1,
100 | "round": 0.1,
101 | "display": "number"}),
102 | "value": ("FLOAT", {
103 | "default": 100,
104 | "min": 0,
105 | "max": 100.0,
106 | "step": 1,
107 | "round": 0.1,
108 | "display": "number"}),
109 | "height": ("INT", {
110 | "default": 1024,
111 | "min": 1,
112 | "max": 4096,
113 | "step": 1,
114 | "round": 1,
115 | "display": "number"}),
116 | "width": ("INT", {
117 | "default": 1024,
118 | "min": 1,
119 | "max": 4096,
120 | "step": 1,
121 | "round": 1,
122 | "display": "number"}),
123 | }
124 | }
125 |
126 | def get_solid_color(self, hue, saturation, value, height, width):
127 | return (create_solid_hsv(hue, saturation, value, height, width), )
128 |
129 | class SolidColor():
130 | NAME = "Solid Color"
131 | CATEGORY = "Virtuoso/Solid Color"
132 | RETURN_TYPES = ("IMAGE",)
133 | RETURN_NAMES = ('solid color image',)
134 | FUNCTION = "get_solid_color"
135 |
136 | @classmethod
137 | def INPUT_TYPES(s) -> dict:
138 | return {
139 | "required": {
140 | "color": (["black", "silver", "gray", "white","maroon","red",
141 | "purple", "fuchsia", "green", "lime", "olive",
142 | "yellow", "navy", "blue", "teal", "aqua"],),
143 | "height": ("INT", {
144 | "default": 1024,
145 | "min": 1,
146 | "max": 4096,
147 | "step": 1,
148 | "round": 1,
149 | "display": "number"}),
150 | "width": ("INT", {
151 | "default": 1024,
152 | "min": 1,
153 | "max": 4096,
154 | "step": 1,
155 | "round": 1,
156 | "display": "number"}),
157 | }
158 | }
159 |
160 | def get_solid_color(self, color, height, width):
161 |
162 | colors = {"black": "#000000",
163 | "silver": "#c0c0c0",
164 | "gray": "#808080",
165 | "white": "#ffffff",
166 | "maroon": "#800000",
167 | "red": "#ff0000",
168 | "purple": "#800080",
169 | "fuchsia": "#ff00ff",
170 | "green": "#008000",
171 | "lime": "#00ff00",
172 | "olive": "#808000",
173 | "yellow": "#ffff00",
174 | "navy": "#000080",
175 | "blue": "#0000ff",
176 | "teal": "#008080",
177 | "aqua": "#00ffff",
178 | }
179 |
180 | return (create_solid_hex(colors[color], height, width), )
181 |
182 | class SplitRGB():
183 |
184 | def __init__(self):
185 | pass
186 |
187 | @classmethod
188 | def INPUT_TYPES(s):
189 |
190 | return {
191 | "required": {
192 | "image": ("IMAGE",),
193 | },
194 | }
195 |
196 | RETURN_TYPES = ("IMAGE","IMAGE","IMAGE")
197 | RETURN_NAMES = ('red', 'green', 'blue',)
198 | FUNCTION = "do_split"
199 | CATEGORY = "Virtuoso/Channels"
200 |
201 | def do_split(self, image):
202 | # Create tensors for red, green, and blue channels
203 | red = torch.zeros_like(image)
204 | green = torch.zeros_like(image)
205 | blue = torch.zeros_like(image)
206 |
207 | # Assign the corresponding color channels from the input image to all images in the batch
208 | red[:, :, :, 0] = image[:, :, :, 0]
209 | green[:, :, :, 1] = image[:, :, :, 1]
210 | blue[:, :, :, 2] = image[:, :, :, 2]
211 |
212 | return (red, green, blue)
213 |
214 |
215 | class MergeRGB():
216 |
217 | def __init__(self):
218 | pass
219 |
220 | @classmethod
221 | def INPUT_TYPES(s):
222 |
223 | return {
224 | "required": {
225 | "red": ("IMAGE",),
226 | "green": ("IMAGE",),
227 | "blue": ("IMAGE",)
228 | },
229 | }
230 |
231 | RETURN_TYPES = ("IMAGE",)
232 | FUNCTION = "do_merge"
233 | CATEGORY = "Virtuoso/Channels"
234 |
235 | def do_merge(self, red, green, blue):
236 |
237 | # Create a tensor for the new image
238 | img = torch.zeros_like(red)
239 |
240 | # Assign the corresponding color channels from the input images
241 | img[0, :, :, 0] = red[0, :, :, 0]
242 | img[0, :, :, 1] = green[0, :, :, 1]
243 | img[0, :, :, 2] = blue[0, :, :, 2]
244 |
245 | return (img,)
246 |
247 |
248 | class ColorBalance():
249 | NAME = "Color Balance"
250 | CATEGORY = "Virtuoso/Adjustment"
251 | RETURN_TYPES = ("IMAGE",)
252 | FUNCTION = "do_color_balance"
253 |
254 | @classmethod
255 | def INPUT_TYPES(s) -> dict:
256 | return {
257 | "required": {
258 | "image": ("IMAGE",),
259 | "lows_cyan_red": ("FLOAT", {
260 | "default": 0,
261 | "min": -1.0,
262 | "max": 1.0,
263 | "step": 0.01,
264 | "round": 0.001,
265 | "display": "number"}),
266 | "lows_magenta_green": ("FLOAT", {
267 | "default": 0,
268 | "min": -1.0,
269 | "max": 1.0,
270 | "step": 0.01,
271 | "round": 0.001,
272 | "display": "number"}),
273 | "lows_yellow_blue": ("FLOAT", {
274 | "default": 0,
275 | "min": -1.0,
276 | "max": 1.0,
277 | "step": 0.01,
278 | "round": 0.001,
279 | "display": "number"}),
280 | "mids_cyan_red": ("FLOAT", {
281 | "default": 0,
282 | "min": -1.0,
283 | "max": 1.0,
284 | "step": 0.01,
285 | "round": 0.001,
286 | "display": "number"}),
287 | "mids_magenta_green": ("FLOAT", {
288 | "default": 0,
289 | "min": -1.0,
290 | "max": 1.0,
291 | "step": 0.01,
292 | "round": 0.001,
293 | "display": "number"}),
294 | "mids_yellow_blue": ("FLOAT", {
295 | "default": 0,
296 | "min": -1.0,
297 | "max": 1.0,
298 | "step": 0.01,
299 | "round": 0.001,
300 | "display": "number"}),
301 | "highs_cyan_red": ("FLOAT", {
302 | "default": 0,
303 | "min": -1.0,
304 | "max": 1.0,
305 | "step": 0.01,
306 | "round": 0.001,
307 | "display": "number"}),
308 | "highs_magenta_green": ("FLOAT", {
309 | "default": 0,
310 | "min": -1.0,
311 | "max": 1.0,
312 | "step": 0.01,
313 | "round": 0.001,
314 | "display": "number"}),
315 | "highs_yellow_blue": ("FLOAT", {
316 | "default": 0,
317 | "min": -1.0,
318 | "max": 1.0,
319 | "step": 0.01,
320 | "round": 0.001,
321 | "display": "number"}),
322 | "preserve_luminosity": ("BOOLEAN", {"default": True})
323 | }
324 | }
325 |
326 | def do_color_balance(self, image, lows_cyan_red, lows_magenta_green, lows_yellow_blue,
327 | mids_cyan_red, mids_magenta_green, mids_yellow_blue,
328 | highs_cyan_red, highs_magenta_green, highs_yellow_blue, preserve_luminosity):
329 | return (color_balance(image,
330 | [lows_cyan_red, lows_magenta_green, lows_yellow_blue],
331 | [mids_cyan_red, mids_magenta_green, mids_yellow_blue],
332 | [highs_cyan_red, highs_magenta_green, highs_yellow_blue], preserve_luminosity=preserve_luminosity), )
333 |
334 | class ColorBalanceAdvanced():
335 | NAME = "Color Balance Advanced"
336 | CATEGORY = "Virtuoso/Adjustment"
337 | RETURN_TYPES = ("IMAGE",)
338 | FUNCTION = "do_color_balance"
339 |
340 | @classmethod
341 | def INPUT_TYPES(s) -> dict:
342 | return {
343 | "required": {
344 | "image": ("IMAGE",),
345 | "brightness_target": ("FLOAT", {
346 | "default": 0.5,
347 | "min": 0.001,
348 | "max": 0.999,
349 | "step": 0.001,
350 | "round": 0.001,
351 | "display": "number"}),
352 | "cyan_red": ("FLOAT", {
353 | "default": 0,
354 | "min": -1.0,
355 | "max": 1.0,
356 | "step": 0.01,
357 | "round": 0.001,
358 | "display": "number"}),
359 | "magenta_green": ("FLOAT", {
360 | "default": 0,
361 | "min": -1.0,
362 | "max": 1.0,
363 | "step": 0.01,
364 | "round": 0.001,
365 | "display": "number"}),
366 | "yellow_blue": ("FLOAT", {
367 | "default": 0,
368 | "min": -1.0,
369 | "max": 1.0,
370 | "step": 0.01,
371 | "round": 0.001,
372 | "display": "number"}),
373 | "preserve_luminosity": ("BOOLEAN", {"default": True})
374 | }
375 | }
376 |
377 | def do_color_balance(self, image, brightness_target, cyan_red, magenta_green, yellow_blue, preserve_luminosity):
378 | return (color_balance(image,
379 | [0, 0, 0],
380 | [cyan_red, magenta_green,yellow_blue],
381 | [0, 0, 0], 0.15, brightness_target, midtone_max=1, preserve_luminosity=preserve_luminosity), )
382 |
383 |
384 | def color_balance(img, shadows, midtones, highlights, shadow_center=0.15, midtone_center=0.5, highlight_center=0.8, shadow_max=0.1, midtone_max=0.3, highlight_max=0.2, preserve_luminosity=False):
385 | # Create a copy of the img tensor
386 | img_copy = img.clone()
387 |
388 | # Calculate the original luminance if preserve_luminosity is True
389 | if preserve_luminosity:
390 | original_luminance = 0.2126 * img_copy[..., 0] + 0.7152 * img_copy[..., 1] + 0.0722 * img_copy[..., 2]
391 |
392 | # Define the adjustment curves
393 | def adjust(x, center, value, max_adjustment):
394 | # Scale the adjustment value
395 | value = value * max_adjustment
396 |
397 | # Define control points
398 | points = torch.tensor([[0, 0], [center, center + value], [1, 1]])
399 |
400 | # Create cubic spline
401 | cs = CubicSpline(points[:, 0], points[:, 1])
402 |
403 | # Apply the cubic spline to the color channel
404 | return torch.clamp(torch.from_numpy(cs(x)), 0, 1)
405 |
406 | # Apply the adjustments to each color channel
407 | # shadows, midtones, highlights are lists of length 3 (for R, G, B channels) with values between -1 and 1
408 | for i, (s, m, h) in enumerate(zip(shadows, midtones, highlights)):
409 | img_copy[..., i] = adjust(img_copy[..., i], shadow_center, s, shadow_max)
410 | img_copy[..., i] = adjust(img_copy[..., i], midtone_center, m, midtone_max)
411 | img_copy[..., i] = adjust(img_copy[..., i], highlight_center, h, highlight_max)
412 |
413 | # If preserve_luminosity is True, adjust the RGB values to match the original luminance
414 | if preserve_luminosity:
415 | current_luminance = 0.2126 * img_copy[..., 0] + 0.7152 * img_copy[..., 1] + 0.0722 * img_copy[..., 2]
416 | img_copy *= (original_luminance / current_luminance).unsqueeze(-1)
417 |
418 | return img_copy
419 |
420 | class BlackAndWhite():
421 | NAME = "Black and White"
422 | CATEGORY = "Virtuoso/Adjustment"
423 | RETURN_TYPES = ("IMAGE",)
424 | FUNCTION = "do_black_and_white"
425 |
426 | @classmethod
427 | def INPUT_TYPES(s) -> dict:
428 | return {
429 | "required": {
430 | "image": ("IMAGE",),
431 | "red": ("FLOAT", {
432 | "default": 0,
433 | "min": -1.0,
434 | "max": 1.0,
435 | "step": 0.01,
436 | "round": 0.001,
437 | "display": "number"}),
438 | "green": ("FLOAT", {
439 | "default": 0,
440 | "min": -1.0,
441 | "max": 1.0,
442 | "step": 0.01,
443 | "round": 0.001,
444 | "display": "number"}),
445 | "blue": ("FLOAT", {
446 | "default": 0,
447 | "min": -1.0,
448 | "max": 1.0,
449 | "step": 0.01,
450 | "round": 0.001,
451 | "display": "number"}),
452 | "cyan": ("FLOAT", {
453 | "default": 0,
454 | "min": -1.0,
455 | "max": 1.0,
456 | "step": 0.01,
457 | "round": 0.001,
458 | "display": "number"}),
459 | "magenta": ("FLOAT", {
460 | "default": 0,
461 | "min": -1.0,
462 | "max": 1.0,
463 | "step": 0.01,
464 | "round": 0.001,
465 | "display": "number"}),
466 | "yellow": ("FLOAT", {
467 | "default": 0,
468 | "min": -1.0,
469 | "max": 1.0,
470 | "step": 0.01,
471 | "round": 0.001,
472 | "display": "number"}),
473 | }
474 | }
475 |
476 | def do_black_and_white(self, image, red, green, blue, cyan, magenta, yellow):
477 | """
478 | Convert a color image to black and white with adjustable color weights.
479 |
480 | Parameters:
481 | img (torch.Tensor): Input image tensor with shape [batch size, height, width, number of channels]
482 | red (float): Weight for red, range -1.0 to 1.0
483 | green (float): Weight for green, range -1.0 to 1.0
484 | blue (float): Weight for blue, range -1.0 to 1.0
485 | cyan (float): Weight for cyan, range -1.0 to 1.0
486 | magenta (float): Weight for magenta, range -1.0 to 1.0
487 | yellow (float): Weight for yellow, range -1.0 to 1.0
488 |
489 | Returns:
490 | torch.Tensor: Black and white image tensor with values in range 0-1
491 | """
492 | # Calculate minimum color value across all color channels for each pixel
493 | min_c, _ = image.min(dim=-1)
494 |
495 | # Calculate differences between color channels and minimum color value
496 | diff = image - min_c.unsqueeze(-1)
497 |
498 | # Create masks for red, green, and blue pixels
499 | red_mask = (diff[:, :, :, 0] == 0)
500 | green_mask = torch.logical_and((diff[:, :, :, 1] == 0), ~red_mask)
501 | blue_mask = ~torch.logical_or(red_mask, green_mask)
502 |
503 | # Calculate c, m, and yel values
504 | c, _ = diff[:, :, :, 1:].min(dim=-1)
505 | m, _ = diff[:, :, :, [0, 2]].min(dim=-1)
506 | yel, _ = diff[:, :, :, :2].min(dim=-1)
507 |
508 | # Calculate luminance using vectorized operations
509 | luminance = min_c + red_mask * (c * cyan + (diff[:, :, :, 1] - c) * green + (diff[:, :, :, 2] - c) * blue)
510 | luminance += green_mask * (m * magenta + (diff[:, :, :, 0] - m) * red + (diff[:, :, :, 2] - m) * blue)
511 | luminance += blue_mask * (yel * yellow + (diff[:, :, :, 0] - yel) * red + (diff[:, :, :, 1] - yel) * green)
512 |
513 | # Clip luminance values to be between 0 and 1
514 | luminance = luminance.clamp(0, 1)
515 |
516 | # Add an extra dimension for color channels
517 | luminance = luminance.unsqueeze(-1)
518 |
519 | # Convert grayscale to RGB by duplicating the grayscale channel
520 | rgb_image = luminance.expand(-1, -1, -1, 3)
521 |
522 | # If the original image had an alpha channel, append it back
523 | if image.shape[-1] == 4:
524 | alpha_channel = image[:, :, :, 3:]
525 | rgb_image = torch.cat((rgb_image, alpha_channel), dim=-1)
526 |
527 | return (rgb_image,)
528 |
529 |
530 | class HueSatAdvanced():
531 | NAME = "Hue/Saturation Advanced"
532 | CATEGORY = "Virtuoso/Adjustment"
533 | RETURN_TYPES = ("IMAGE", "MASK")
534 | FUNCTION = "do_hue_sat"
535 |
536 | @classmethod
537 | def INPUT_TYPES(s) -> dict:
538 | return {
539 | "required": {
540 | "image": ("IMAGE",),
541 | "hue_low": ("FLOAT", {
542 | "default": 0,
543 | "min": 0,
544 | "max": 360.0,
545 | "step": 1,
546 | "round": 0.1,
547 | "display": "number"}),
548 | "hue_low_feather": ("FLOAT", {
549 | "default": 0,
550 | "min": 0,
551 | "max": 180,
552 | "step": 1,
553 | "round": 0.1,
554 | "display": "number"}),
555 | "hue_high": ("FLOAT", {
556 | "default": 360,
557 | "min": 0,
558 | "max": 360.0,
559 | "step": 1,
560 | "round": 0.1,
561 | "display": "number"}),
562 | "hue_high_feather": ("FLOAT", {
563 | "default": 0,
564 | "min": 0,
565 | "max": 180,
566 | "step": 1,
567 | "round": 0.1,
568 | "display": "number"}),
569 | "hue_offset": ("FLOAT", {
570 | "default": 0,
571 | "min": -180.0,
572 | "max": 180.0,
573 | "step": 0.1,
574 | "round": 0.01,
575 | "display": "number"}),
576 | "sat_offset": ("FLOAT", {
577 | "default": 0,
578 | "min": -100,
579 | "max": 100,
580 | "step": 0.1,
581 | "round": 0.01,
582 | "display": "number"}),
583 | "lightness_offset": ("FLOAT", {
584 | "default": 0,
585 | "min": -100.0,
586 | "max": 100.0,
587 | "step": 0.1,
588 | "round": 0.01,
589 | "display": "number"}),
590 | }
591 | }
592 |
593 | def do_hue_sat(self, image, hue_low, hue_low_feather, hue_high, hue_high_feather, hue_offset, sat_offset, lightness_offset):
594 |
595 | # Convert image to HSV and build mask
596 | image_hsv = rgb_to_hsv(image)
597 | mask = create_mask(image_hsv[..., 0], image_hsv[..., 1], hue_low, hue_high, hue_low_feather, hue_high_feather)
598 | # Adjust hue
599 | image_hsv[..., 0] = adjust_hue(image_hsv[..., 0], hue_offset)
600 |
601 | # Adjust saturation
602 | image_hsv[..., 1] = adjust_saturation(image_hsv[..., 1], sat_offset)
603 |
604 | # Adjust lightness
605 | image_hsv = adjust_lightness(image_hsv, lightness_offset)
606 |
607 | # Convert back to RGB
608 | adjusted_image_rgb = hsv_to_rgb(image_hsv[..., :3])
609 |
610 | # Blend the original and adjusted images based on the mask
611 | blended_rgb = (adjusted_image_rgb * mask.unsqueeze(-1)) + (image[..., :3] * (1 - mask.unsqueeze(-1)))
612 |
613 | # Include the alpha channel if present
614 | if image.shape[-1] == 4:
615 | blended_rgba = torch.cat((blended_rgb, image[..., 3:4]), dim=-1)
616 | else:
617 | blended_rgba = blended_rgb
618 |
619 | return (blended_rgba, mask)
620 |
621 |
622 | class HueSat():
623 | NAME = "Hue/Saturation"
624 | CATEGORY = "Virtuoso/Adjustment"
625 | RETURN_TYPES = ("IMAGE", "MASK")
626 | FUNCTION = "do_hue_sat"
627 |
628 | @classmethod
629 | def INPUT_TYPES(s) -> dict:
630 | return {
631 | "required": {
632 | "image": ("IMAGE",),
633 | "hue": (["red", "yellow", "green", "cyan", "blue", "magenta"],),
634 | "hue_width": (["normal","narrow", "wide"],),
635 | "feather": (["normal", "none", "wide"],),
636 | "hue_offset": ("FLOAT", {
637 | "default": 0,
638 | "min": -180.0,
639 | "max": 180.0,
640 | "step": 0.1,
641 | "round": 0.01,
642 | "display": "number"}),
643 | "sat_offset": ("FLOAT", {
644 | "default": 0,
645 | "min": -100,
646 | "max": 100,
647 | "step": 0.1,
648 | "round": 0.01,
649 | "display": "number"}),
650 | "lightness_offset": ("FLOAT", {
651 | "default": 0,
652 | "min": -100.0,
653 | "max": 100.0,
654 | "step": 0.1,
655 | "round": 0.01,
656 | "display": "number"}),
657 | }
658 | }
659 |
660 | def do_hue_sat(self, image, hue, hue_width, feather, hue_offset, sat_offset, lightness_offset):
661 |
662 | # Convert image to HSV
663 | image_hsv = rgb_to_hsv(image)
664 |
665 | # Calculate ranges from parameters
666 | hues = {"red": 0, "yellow": 60, "green": 120, "cyan": 180, "blue": 240, "magenta": 300}
667 | widths = {"narrow": 15, "normal": 30, "wide": 60}
668 | feathers = {"none": 0, "normal": 25, "wide": 50}
669 | base_hue = hues[hue]
670 | hue_low = base_hue - (widths[hue_width]/2)
671 | if hue_low < 0:
672 | hue_low = 360 + hue_low
673 | hue_high = base_hue + (widths[hue_width]/2)
674 |
675 | mask = create_mask(image_hsv[..., 0], image_hsv[..., 1], hue_low, hue_high, feathers[feather]/2, feathers[feather]/2)
676 |
677 | # Adjust hue
678 | image_hsv[..., 0] = adjust_hue(image_hsv[..., 0], hue_offset)
679 |
680 | # Adjust saturation
681 | image_hsv[..., 1] = adjust_saturation(image_hsv[..., 1], sat_offset)
682 |
683 | # Adjust lightness
684 | image_hsv = adjust_lightness(image_hsv, lightness_offset)
685 |
686 | # Convert back to RGB
687 | adjusted_image_rgb = hsv_to_rgb(image_hsv[..., :3])
688 |
689 | # Blend the original and adjusted images based on the mask
690 | blended_rgb = (adjusted_image_rgb * mask.unsqueeze(-1)) + (image[..., :3] * (1 - mask.unsqueeze(-1)))
691 |
692 | # Include the alpha channel if present
693 | if image.shape[-1] == 4:
694 | blended_rgba = torch.cat((blended_rgb, image[..., 3:4]), dim=-1)
695 | else:
696 | blended_rgba = blended_rgb
697 |
698 | return (blended_rgba, mask)
699 |
700 | ## Support functions
701 | def create_solid_rgb(r, g, b, h, w):
702 | return torch.zeros(1, h, w, 3) + torch.tensor([r/255.0, g/255.0, b/255.0])
703 |
704 | def create_solid_hsv(h, s, v, h_img, w_img):
705 | r, g, b = colorsys.hsv_to_rgb(h/360.0, s/100.0, v/100.0)
706 | return torch.zeros(1, h_img, w_img, 3) + torch.tensor([r, g, b])
707 |
708 | def create_solid_hex(hex, h, w):
709 | if hex[0] == '#':
710 | hex = hex[1:]
711 | r, g, b = tuple(int(hex[i:i+2], 16)/255.0 for i in (0, 2, 4))
712 | return torch.zeros(1, h, w, 3) + torch.tensor([r, g, b])
713 |
714 | def validate_hex_code(hex_code):
715 | hex_code = hex_code.lstrip('#')
716 |
717 | if len(hex_code) == 3 and all(c in '0123456789ABCDEFabcdef' for c in hex_code):
718 | return ''.join([c*2 for c in hex_code]).upper()
719 | elif len(hex_code) == 6 and all(c in '0123456789ABCDEFabcdef' for c in hex_code):
720 | return hex_code.upper()
721 | else:
722 | return ""
723 |
724 | def create_mask(hue, saturation, hue_low, hue_high, hue_low_feather, hue_high_feather):
725 | # Normalize the values to the range [0, 1]
726 | hue_low_norm = hue_low / 360.0
727 | hue_high_norm = hue_high / 360.0
728 | hue_low_feather_norm = hue_low_feather / 360.0
729 | hue_high_feather_norm = hue_high_feather / 360.0
730 |
731 | # Calculate the mask
732 | mask_low = linearstep(hue_low_norm - hue_low_feather_norm, hue_low_norm, hue, increasing=True)
733 | mask_high = linearstep(hue_high_norm, hue_high_norm + hue_high_feather_norm, hue, increasing=False)
734 |
735 | if hue_low_norm < hue_high_norm:
736 | mask_middle = torch.where((hue >= hue_low_norm) & (hue <= hue_high_norm), torch.tensor(1.0), torch.tensor(0.0))
737 | else:
738 | mask_middle = torch.where((hue <= hue_low_norm) & (hue >= hue_high_norm), torch.tensor(0.0), torch.tensor(1.0))
739 |
740 | # Calculate the final mask by taking the maximum value among the three masks
741 | mask = torch.max(torch.max(mask_low, mask_middle), mask_high)
742 |
743 | # Only select pixels with a saturation greater than 0
744 | mask = torch.where(saturation > 0, mask, torch.tensor(0.0))
745 |
746 | return mask
747 |
748 | def linearstep(low_edge, high_edge, x, increasing=True):
749 | # Handle the case where the gradient overflows past 0
750 | if low_edge < 0:
751 | # Define gradient function for low gradient
752 | overflow_mask_low = torch.where((x >= 0) & (x <= high_edge), (x - low_edge) / (high_edge - low_edge), torch.tensor(0.0))
753 | overflow_mask_high = torch.where((x >= (1 + low_edge)) & (x <= 1), (x - 1 - low_edge) / (high_edge - low_edge), torch.tensor(0.0))
754 | mask = torch.max(overflow_mask_low, overflow_mask_high)
755 | elif high_edge > 1:
756 | overflow_mask_high = torch.where((x >= low_edge) & (x <= 1), 1 - ((x - low_edge) / (high_edge - low_edge)), torch.tensor(0.0))
757 | overflow_mask_low = torch.where((x >= 0) & (x <= (high_edge - 1)), 1 - ((x + 1 - low_edge) / (high_edge - low_edge)), torch.tensor(0.0))
758 | mask = torch.max(overflow_mask_low, overflow_mask_high)
759 | else:
760 | # Create a mask where values within the range are set to abs( (hue value - low_edge)/(high_edge - low_edge))
761 | gradient = torch.abs((x - low_edge) / (high_edge - low_edge))
762 | if not increasing:
763 | gradient = 1 - gradient
764 | # Return the mask where values within the range are set to the gradient, and 0 otherwise
765 | mask = torch.where((x >= low_edge) & (x <= high_edge), gradient, torch.tensor(0.0))
766 |
767 | return mask
768 |
769 | def adjust_saturation(saturation, sat_offset):
770 | # Calculate the change in saturation
771 | if sat_offset < 0:
772 | delta_saturation = (sat_offset / 100.0) * saturation
773 | else:
774 | delta_saturation = (sat_offset / 100.0) * (1 - saturation)
775 | # Apply the change to the saturation channel
776 | new_saturation = torch.clamp(saturation + delta_saturation, 0, 1)
777 | return new_saturation
778 |
779 | def adjust_hue(hue, hue_offset):
780 | # Normalize hue_offset to the range [0, 1]
781 | hue_offset_normalized = hue_offset / 360.0
782 | # Apply the normalized hue_offset and ensure the result is within [0, 1]
783 | new_hue = (hue + hue_offset_normalized) % 1.0
784 | return new_hue
785 |
786 | def adjust_lightness(image, lightness_offset):
787 |
788 | image_hsv = image.clone()
789 |
790 | # Map lightness_offset to [-1, 1]
791 | offset = lightness_offset / 100.0
792 |
793 | # If lightness_offset < 0, interpolate between the image and a black image
794 | if lightness_offset < 0:
795 | image_hsv[..., 2] = image_hsv[..., 2] * (1 + offset)
796 | # If lightness_offset > 0, interpolate between the image and a white image
797 | elif lightness_offset > 0:
798 | image_hsv[..., 2] = image_hsv[..., 2] * (1 - offset) + offset
799 | # Also reduce the saturation as the lightness increases
800 | image_hsv[..., 1] = image_hsv[..., 1] * ((1 - offset) ** 0.45)
801 |
802 | return image_hsv
--------------------------------------------------------------------------------
/component-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | [Inversion](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/inversion-modes.md)
7 | Component
8 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
9 |
10 | # Component Modes
11 |
12 | ### Hue Mode
13 | 
14 |
15 | ### Saturation Mode
16 | 
17 |
18 | ### Color Mode
19 | 
20 |
21 | ### Luminosity Mode
22 | 
23 |
--------------------------------------------------------------------------------
/contrast-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
5 | Contrast
6 | [Inversion](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/inversion-modes.md)
7 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
8 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
9 |
10 | # Contrast Modes
11 |
12 | ### Overlay Mode
13 | 
14 |
15 | ### Soft Light Mode
16 | 
17 |
18 | ### Hard Light Mode
19 | 
20 |
21 | ### Vivid Light Mode
22 | 
23 |
24 | ### Linear Light Mode
25 | 
26 |
27 | ### Pin Light Mode
28 | 
29 |
30 | ### Hard Mix Mode
31 | 
32 |
--------------------------------------------------------------------------------
/contrast.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Contrast
4 | @nickname: Virtuoso Pack - Contrast
5 | @description: This extension provides a "Levels" node.
6 | """
7 | import torch
8 |
9 | class Levels:
10 |
11 | def __init__(self):
12 | pass
13 |
14 | @classmethod
15 | def INPUT_TYPES(s):
16 |
17 | return {
18 | "required": {
19 | "image": ("IMAGE",),
20 | "channel": (["RGB", "red", "green", "blue"],),
21 | "input_black_point": ("FLOAT", {
22 | "default": 0.0,
23 | "min": 0.00,
24 | "max": 0.98,
25 | "step": 0.01,
26 | "round": 0.001,
27 | "display": "number"}),
28 | "input_gamma": ("FLOAT", {
29 | "default": 1.0,
30 | "min": 0.01,
31 | "max": 9.99,
32 | "step": 0.01,
33 | "round": 0.001,
34 | "display": "number"}),
35 | "input_white_point": ("FLOAT", {
36 | "default": 1.0,
37 | "min": 0.0,
38 | "max": 1.0,
39 | "step": 0.01,
40 | "round": 0.001,
41 | "display": "number"}),
42 | "output_black_point": ("FLOAT", {
43 | "default": 0.0,
44 | "min": 0.0,
45 | "max": 1.0,
46 | "step": 0.01,
47 | "round": 0.001,
48 | "display": "number"}),
49 | "output_white_point": ("FLOAT", {
50 | "default": 1.0,
51 | "min": 0.0,
52 | "max": 1.0,
53 | "step": 0.01,
54 | "round": 0.001,
55 | "display": "number"}),
56 | }
57 | }
58 |
59 | RETURN_TYPES = ("IMAGE",)
60 | FUNCTION = "do_levels"
61 | CATEGORY = "Virtuoso/Adjustment"
62 |
63 | def do_levels(self, image, channel, input_black_point, input_gamma, input_white_point, output_black_point, output_white_point):
64 | """
65 | Applies levels adjustment to an input image tensor.
66 |
67 | Args:
68 | image (torch.Tensor): Input image tensor with shape [batch size, height, width, num color channels].
69 | channel (str): The color channel to adjust ('RGB', 'red', 'green', 'blue').
70 | input_black_point (float): Black point value (lower bound of input range).
71 | input_white_point (float): White point value (upper bound of input range).
72 | input_gamma (float): Gamma value (controls contrast).
73 | output_black_point (float): New black point value (lower bound of output range).
74 | output_white_point (float): New white point value (upper bound of output range).
75 |
76 | Returns:
77 | Tuple[torch.Tensor]: Output tensor with the adjusted pixel values in a tuple.
78 | """
79 | # Determine if there is an alpha channel
80 | has_alpha = image.shape[-1] in [2, 4]
81 | alpha_channel = image[..., -1:] if has_alpha else None
82 |
83 | # Extract the color channels (excluding alpha if present)
84 | color_channels = image[..., :-1] if has_alpha else image
85 |
86 | # Initialize a tensor to hold the adjusted color channels
87 | adjusted_color = torch.zeros_like(color_channels)
88 |
89 | # Apply the levels adjustment curve to the specified channel(s)
90 | for i, color in enumerate(['red', 'green', 'blue']):
91 | if channel == 'RGB' or channel == color:
92 | adjusted_channel = ((color_channels[..., i] - input_black_point) / (input_white_point - input_black_point)) ** input_gamma
93 | adjusted_channel = torch.clamp(adjusted_channel, 0.0, 1.0)
94 | adjusted_channel = output_black_point + (adjusted_channel * (output_white_point - output_black_point))
95 | adjusted_color[..., i] = adjusted_channel
96 | else:
97 | adjusted_color[..., i] = color_channels[..., i]
98 |
99 | # If there is an alpha channel, combine the adjusted color channels with the original alpha channel
100 | if has_alpha:
101 | adjusted_image = torch.cat([adjusted_color, alpha_channel], dim=-1)
102 | else:
103 | adjusted_image = adjusted_color
104 |
105 | # Return the adjusted image in a tuple
106 | return (adjusted_image,)
--------------------------------------------------------------------------------
/darken-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | Darken
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
7 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
8 |
9 | # Darken Modes
10 |
11 | ### Darken Mode
12 | 
13 |
14 | ### Multiply Mode
15 | 
16 |
17 | ### Color Burn Mode
18 | 
19 |
20 | ### Linear Burn Mode
21 | 
22 |
23 | ### Darker Color Mode
24 | 
25 |
--------------------------------------------------------------------------------
/hsv.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | def rgb_to_hsv(rgb):
4 | # Separate the RGB channels
5 | r, g, b = rgb[:, :, :, 0:1], rgb[:, :, :, 1:2], rgb[:, :, :, 2:3]
6 |
7 | # Compute the HSV channels
8 | max_val, _ = torch.max(rgb[:, :, :, :3], dim=-1, keepdim=True)
9 | min_val, _ = torch.min(rgb[:, :, :, :3], dim=-1, keepdim=True)
10 | diff = max_val - min_val
11 |
12 | v = max_val
13 |
14 | s = diff / v
15 | s = torch.where(torch.isnan(s), torch.zeros_like(s), s)
16 |
17 | h = torch.zeros_like(r)
18 | h = torch.where((max_val == r) & (g >= b), ((g - b) / diff) / 6, h)
19 | h = torch.where((max_val == r) & (g < b), ((g - b) / diff) / 6 + 1, h)
20 | h = torch.where(max_val == g, ((b - r) / diff) / 6 + 1 / 3, h)
21 | h = torch.where(max_val == b, ((r - g) / diff) / 6 + 2 / 3, h)
22 | h = torch.where(max_val == min_val, torch.zeros_like(h), h)
23 |
24 | # If the input has an alpha channel, append it to the output
25 | if rgb.shape[-1] == 4:
26 | hsv = torch.cat((h, s, v, rgb[:, :, :, 3:4]), dim=-1)
27 | else:
28 | hsv = torch.cat((h, s, v), dim=-1)
29 |
30 | return hsv
31 |
32 | def hsv_to_rgb(hsv):
33 | # Separate the HSV channels
34 | h, s, v = hsv[:, :, :, 0:1], hsv[:, :, :, 1:2], hsv[:, :, :, 2:3]
35 |
36 | # Compute the RGB channels
37 | i = (h * 6).floor()
38 | f = h * 6 - i
39 | p = v * (1 - s)
40 | q = v * (1 - f * s)
41 | t = v * (1 - (1 - f) * s)
42 |
43 | i = i % 6
44 |
45 | r = torch.where(i == 0, v, torch.where(i == 1, q, torch.where(i == 2, p, torch.where(i == 3, p, torch.where(i == 4, t, v)))))
46 | g = torch.where(i == 0, t, torch.where(i == 1, v, torch.where(i == 2, v, torch.where(i == 3, q, torch.where(i == 4, p, p)))))
47 | b = torch.where(i == 0, p, torch.where(i == 1, p, torch.where(i == 2, t, torch.where(i == 3, v, torch.where(i == 4, v, q)))))
48 |
49 | # If the input has an alpha channel, append it to the output
50 | if hsv.shape[-1] == 4:
51 | rgb = torch.cat((r, g, b, hsv[:, :, :, 3:4]), dim=-1)
52 | else:
53 | rgb = torch.cat((r, g, b), dim=-1)
54 |
55 | return rgb
56 |
57 |
--------------------------------------------------------------------------------
/inversion-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | Inversion
7 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
8 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
9 |
10 | # Inversion Modes
11 |
12 | ### Difference Mode
13 | 
14 |
15 | ### Exclusion Mode
16 | 
17 |
18 | ### Subtract Mode
19 | 
20 |
21 | ### Divide Mode
22 | 
23 |
--------------------------------------------------------------------------------
/lighten-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | Lighten
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | [Inversion](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/inversion-modes.md)
7 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
8 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
9 |
10 | # Lighten Modes
11 |
12 | ### Lighten Mode
13 | 
14 |
15 | ### Screen Mode
16 | 
17 |
18 | ### Dodge Mode
19 | 
20 |
21 | ### Color Dodge Mode
22 | 
23 |
24 | ### Linear Dodge (Add) Mode
25 | 
26 |
27 | ### Lighter Color Mode
28 | 
29 |
--------------------------------------------------------------------------------
/normal-modes.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | Normal
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-modes.md)
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | [Inversion](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/inversion-modes.md)
7 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
8 | [Specialty](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/specialty-mode.md)**
9 |
10 | # Normal Modes
11 |
12 | ### Normal Mode
13 | 
14 |
15 | ### Dissolve Mode
16 | 
17 |
18 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "virtuoso-nodes"
3 | description = "Photoshop type functions and adjustment layers: 30 blend modes, Selective Color, Blend If, Color Balance, Solid Color Images, Black and White, Hue/Saturation, Levels, and RGB Splitting and Merging."
4 | version = "1.0.0"
5 | license = "LICENSE"
6 | dependencies = ["numpy", "blend_modes", "Pillow", "torch", "scipy", "cv2", "blurgenerator"]
7 |
8 | [project.urls]
9 | Repository = "https://github.com/chrisfreilich/virtuoso-nodes"
10 | # Used by Comfy Registry https://comfyregistry.org
11 |
12 | [tool.comfy]
13 | PublisherId = "cfreilich"
14 | DisplayName = "virtuoso-nodes"
15 | Icon = ""
16 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | blend_modes
3 | Pillow
4 | torch
5 | scipy
6 | opencv-python
7 | blurgenerator
8 |
--------------------------------------------------------------------------------
/resize.py:
--------------------------------------------------------------------------------
1 | import torch.nn.functional as F
2 |
3 | def match_sizes(match_size, top, bottom, m=None):
4 | top_layer = top.clone()
5 | bottom_layer = bottom.clone()
6 | mask = None
7 |
8 | # Resize top_layer and mask to match bottom_layer
9 | if match_size == 'stretch':
10 | top_layer = F.interpolate(top_layer.permute(0, 3, 1, 2), size=(bottom_layer.shape[1], bottom_layer.shape[2]), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
11 |
12 | if m is not None:
13 | # Resize mask to match bottom_layer size
14 | mask = F.interpolate(m.unsqueeze(1), size=(bottom_layer.shape[1], bottom_layer.shape[2]), mode='nearest').squeeze(1).clone()
15 | else:
16 | # Calculate the scale factors for both dimensions separately
17 | scale_factor_h = bottom_layer.shape[1] / top_layer.shape[1]
18 | scale_factor_w = bottom_layer.shape[2] / top_layer.shape[2]
19 |
20 | # Use the correct scale factor to resize the top_layer
21 | scale_factor = max(scale_factor_w, scale_factor_h) # must grow/shrink while covering both dimensions of bottom_layer
22 |
23 | new_h = round(top_layer.shape[1] * scale_factor)
24 | new_w = round(top_layer.shape[2] * scale_factor)
25 |
26 | # Resize top_layer while keeping aspect ratio constant
27 | top_layer = F.interpolate(top_layer.permute(0, 3, 1, 2), size=(new_h, new_w), mode='bilinear', align_corners=False).permute(0, 2, 3, 1)
28 |
29 | # Crop top_layer to match bottom_layer size
30 | top_layer = top_layer[:, :bottom_layer.shape[1], :bottom_layer.shape[2], :]
31 |
32 | if m is not None:
33 | # Calculate the scale factors for both dimensions separately for mask
34 | scale_factor_mask_h = bottom_layer.shape[1] / m.shape[1]
35 | scale_factor_mask_w = bottom_layer.shape[2] / m.shape[2]
36 |
37 | # Use the correct scale factor to resize the mask
38 | scale_factor_mask = max(scale_factor_mask_w, scale_factor_mask_h) # must grow to cover both dimensions
39 |
40 | new_h_mask = round(m.shape[1] * scale_factor_mask)
41 | new_w_mask = round(m.shape[2] * scale_factor_mask)
42 |
43 | # Resize and crop mask in the same way
44 | mask = F.interpolate(m.unsqueeze(1), size=(new_h_mask, new_w_mask), mode='nearest').squeeze(1).clone()
45 | mask = mask[:, :bottom_layer.shape[1], :bottom_layer.shape[2]]
46 |
47 | return top_layer, mask
--------------------------------------------------------------------------------
/selectivecolor.py:
--------------------------------------------------------------------------------
1 | """
2 | @author: Chris Freilich
3 | @title: Virtuoso Pack - Selective Color
4 | @nickname: Virtuoso Pack - Selective Color
5 | @description: This extension provides a selective color node.
6 | """
7 | import torch
8 | import torchvision.transforms as transforms
9 | import subprocess
10 | import imageio
11 | import tempfile
12 |
13 | class SelectiveColor:
14 |
15 | def __init__(self):
16 | pass
17 |
18 | @classmethod
19 | def INPUT_TYPES(s):
20 |
21 | return {
22 | "required": {
23 | "image": ("IMAGE",),
24 | "color_range": (["reds", "yellows","greens", "cyans","blues", "magentas","whites", "neutrals", "blacks"],),
25 | "cyan": ("FLOAT", {
26 | "default": 0.0,
27 | "min": -1.0,
28 | "max": 1.0,
29 | "step": 0.01,
30 | "round": 0.01,
31 | "display": "number"}),
32 | "magenta": ("FLOAT", {
33 | "default": 0.0,
34 | "min": -1.0,
35 | "max": 1.0,
36 | "step": 0.01,
37 | "round": 0.01,
38 | "display": "number"}),
39 | "yellow": ("FLOAT", {
40 | "default": 0.0,
41 | "min": -1.0,
42 | "max": 1.0,
43 | "step": 0.01,
44 | "round": 0.01,
45 | "display": "number"}),
46 | "black": ("FLOAT", {
47 | "default": 0.0,
48 | "min": -1.0,
49 | "max": 1.0,
50 | "step": 0.01,
51 | "round": 0.01,
52 | "display": "number"}),
53 | "method": (["absolute", "relative"],),
54 | }
55 | }
56 |
57 | RETURN_TYPES = ("IMAGE",)
58 | FUNCTION = "do_selectivecolor"
59 | CATEGORY = "Virtuoso/Adjustment"
60 |
61 | def do_selectivecolor(self, image, color_range, cyan, magenta, yellow, black, method):
62 |
63 | output_tensors = []
64 |
65 | # Create a temporary directory using the tempfile module
66 | with tempfile.TemporaryDirectory() as tmpdirname:
67 |
68 | # Iterate over each image in the batch
69 | for i in range(image.shape[0]):
70 |
71 | batch_image = image[i]
72 |
73 | # Permute the dimensions to be in the format expected by ToPILImage (C x H x W)
74 | batch_image = batch_image.permute(2, 0, 1)
75 |
76 | # Convert the PyTorch tensor to a PIL image
77 | img_pil = transforms.ToPILImage()(batch_image)
78 | img_pil.save(f"{tmpdirname}/temp{i}.png")
79 |
80 | # Construct the ffmpeg command
81 | command = ["ffmpeg", "-i", f"{tmpdirname}/temp{i}.png", "-vf"]
82 | command.append(f"selectivecolor={method}:{color_range}={cyan} {magenta} {yellow} {black}")
83 | command.extend(["-update", "1", f"{tmpdirname}/output{i}.png"])
84 |
85 | # Run the ffmpeg command
86 | subprocess.run(command)
87 |
88 | # Load the output image as a PyTorch tensor
89 | img_array = imageio.imread(f"{tmpdirname}/output{i}.png")
90 | img_tensor = transforms.ToTensor()(img_array)
91 |
92 | # Permute the dimensions back to the original format (H x W x C)
93 | img_tensor = img_tensor.permute(1, 2, 0)
94 |
95 | # Add the output tensor to the list
96 | output_tensors.append(img_tensor)
97 |
98 | # Stack the output tensors along a new dimension to form a batch
99 | output_batch = torch.stack(output_tensors)
100 |
101 | # Return the output batch
102 | return (output_batch,)
103 |
104 |
105 |
--------------------------------------------------------------------------------
/specialty-mode.md:
--------------------------------------------------------------------------------
1 | **[README](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/README.md)
2 | [Normal](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/normal-modes.md)
3 | [Darken](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/darken-modes.md)
4 | [Lighten](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/lighten-mode.md)
5 | [Contrast](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/contrast-modes.md)
6 | [Inversion](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/inversion-modes.md)
7 | [Component](https://github.com/chrisfreilich/virtuoso-nodes/blob/main/component-modes.md)
8 | Specialty**
9 |
10 | # Specialty Modes
11 |
12 | ### Grain Merge Mode
13 | 
14 |
15 | ### Grain Extract Mode
16 | 
17 |
--------------------------------------------------------------------------------