File size: 82,592 Bytes
c2ded79 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 |
# By WASasquatch (Discord: WAS#0263)
#
# Copyright 2023 Jordan Thompson (WASasquatch)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to
# deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import torch, os, sys, subprocess, random, math, hashlib, json, time
import torch.nn as nn
import torchvision.transforms as transforms
import numpy as np
from PIL import Image, ImageFilter, ImageEnhance, ImageOps, ImageDraw, ImageChops
from PIL.PngImagePlugin import PngInfo
from urllib.request import urlopen
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
sys.path.append('../ComfyUI')
import comfy.samplers
import comfy.sd
import comfy.utils
import comfy_extras.clip_vision
import model_management
import importlib
import nodes
# GLOBALS
MIDAS_INSTALLED = False
#! FUNCTIONS
# Freeze PIP modules
def packages():
import sys, subprocess
return [r.decode().split('==')[0] for r in subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']).split()]
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# Convert PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
# PIL Hex
def pil2hex(image):
return hashlib.sha256(np.array(tensor2pil(image)).astype(np.uint16).tobytes()).hexdigest().hex();
# Median Filter
def medianFilter(img, diameter, sigmaColor, sigmaSpace):
import cv2 as cv
diameter = int(diameter); sigmaColor = int(sigmaColor); sigmaSpace = int(sigmaSpace)
img = img.convert('RGB')
img = cv.cvtColor(np.array(img), cv.COLOR_RGB2BGR)
img = cv.bilateralFilter(img, diameter, sigmaColor, sigmaSpace)
img = cv.cvtColor(np.array(img), cv.COLOR_BGR2RGB)
return Image.fromarray(img).convert('RGB')
# INSTALLATION CLEANUP
# Delete legacy nodes
legacy_was_nodes = ['fDOF_WAS.py','Image_Blank_WAS.py','Image_Blend_WAS.py','Image_Canny_Filter_WAS.py', 'Canny_Filter_WAS.py','Image_Combine_WAS.py','Image_Edge_Detection_WAS.py', 'Image_Film_Grain_WAS.py', 'Image_Filters_WAS.py', 'Image_Flip_WAS.py','Image_Nova_Filter_WAS.py','Image_Rotate_WAS.py','Image_Style_Filter_WAS.py','Latent_Noise_Injection_WAS.py','Latent_Upscale_WAS.py','MiDaS_Depth_Approx_WAS.py','NSP_CLIPTextEncoder.py','Samplers_WAS.py']
legacy_was_nodes_found = []
f_disp = False
for f in legacy_was_nodes:
node_path_dir = os.getcwd()+'/ComfyUI/custom_nodes/'
file = f'{node_path_dir}{f}'
if os.path.exists(file):
import zipfile
if not f_disp:
print('\033[34mWAS Node Suite:\033[0m Found legacy nodes. Archiving legacy nodes...')
f_disp = True
legacy_was_nodes_found.append(file)
if legacy_was_nodes_found:
from os.path import basename
archive = zipfile.ZipFile(f'{node_path_dir}WAS_Legacy_Nodes_Backup_{round(time.time())}.zip', "w")
for f in legacy_was_nodes_found:
archive.write(f, basename(f))
try:
os.remove(f)
except OSError:
pass
archive.close()
if f_disp:
print('\033[34mWAS Node Suite:\033[0m Legacy cleanup complete.')
#! IMAGE FILTER NODES
# IMAGE FILTER ADJUSTMENTS
class WAS_Image_Filters:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"brightness": ("FLOAT", {"default": 0.0, "min": -1.0, "max": 1.0, "step": 0.01}),
"contrast": ("FLOAT", {"default": 1.0, "min": -1.0, "max": 2.0, "step": 0.01}),
"saturation": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01}),
"sharpness": ("FLOAT", {"default": 1.0, "min": -5.0, "max": 5.0, "step": 0.01}),
"blur": ("INT", {"default": 0, "min": 0, "max": 16, "step": 1}),
"gaussian_blur": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1024.0, "step": 0.1}),
"edge_enhance": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_filters"
CATEGORY = "WAS Suite/Image"
def image_filters(self, image, brightness, contrast, saturation, sharpness, blur, gaussian_blur, edge_enhance):
pil_image = None
# Apply NP Adjustments
if brightness > 0.0 or brightness < 0.0:
# Apply brightness
image = np.clip(image + brightness, 0.0, 1.0)
if contrast > 1.0 or contrast < 1.0:
# Apply contrast
image = np.clip(image * contrast, 0.0, 1.0)
# Apply PIL Adjustments
if saturation > 1.0 or saturation < 1.0:
#PIL Image
pil_image = tensor2pil(image)
# Apply saturation
pil_image = ImageEnhance.Color(pil_image).enhance(saturation)
if sharpness > 1.0 or sharpness < 1.0:
# Assign or create PIL Image
pil_image = pil_image if pil_image else tensor2pil(image)
# Apply sharpness
pil_image = ImageEnhance.Sharpness(pil_image).enhance(sharpness)
if blur > 0:
# Assign or create PIL Image
pil_image = pil_image if pil_image else tensor2pil(image)
# Apply blur
for _ in range(blur):
pil_image = pil_image.filter(ImageFilter.BLUR)
if gaussian_blur > 0.0:
# Assign or create PIL Image
pil_image = pil_image if pil_image else tensor2pil(image)
# Apply Gaussian blur
pil_image = pil_image.filter(ImageFilter.GaussianBlur(radius = gaussian_blur))
if edge_enhance > 0.0:
# Assign or create PIL Image
pil_image = pil_image if pil_image else tensor2pil(image)
# Edge Enhancement
edge_enhanced_img = pil_image.filter(ImageFilter.EDGE_ENHANCE_MORE)
# Blend Mask
blend_mask = Image.new(mode = "L", size = pil_image.size, color = (round(edge_enhance * 255)))
# Composite Original and Enhanced Version
pil_image = Image.composite(edge_enhanced_img, pil_image, blend_mask)
# Clean-up
del blend_mask, edge_enhanced_img
# Output image
out_image = ( pil2tensor(pil_image) if pil_image else image )
return ( out_image, )
# IMAGE STYLE FILTER
class WAS_Image_Style_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"style": ([
"1977",
"aden",
"brannan",
"brooklyn",
"clarendon",
"earlybird",
"gingham",
"hudson",
"inkwell",
"kelvin",
"lark",
"lofi",
"maven",
"mayfair",
"moon",
"nashville",
"perpetua",
"reyes",
"rise",
"slumber",
"stinson",
"toaster",
"valencia",
"walden",
"willow",
"xpro2"
],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_style_filter"
CATEGORY = "WAS Suite/Image"
def image_style_filter(self, image, style):
# Install Pilgram
if 'pilgram' not in packages():
print("\033[34mWAS NS:\033[0m Installing Pilgram...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'pilgram'])
# Import Pilgram module
import pilgram
# Convert image to PIL
image = tensor2pil(image)
# Apply blending
match style:
case "1977":
out_image = pilgram._1977(image)
case "aden":
out_image = pilgram.aden(image)
case "brannan":
out_image = pilgram.brannan(image)
case "brooklyn":
out_image = pilgram.brooklyn(image)
case "clarendon":
out_image = pilgram.clarendon(image)
case "earlybird":
out_image = pilgram.earlybird(image)
case "gingham":
out_image = pilgram.gingham(image)
case "hudson":
out_image = pilgram.hudson(image)
case "inkwell":
out_image = pilgram.inkwell(image)
case "kelvin":
out_image = pilgram.kelvin(image)
case "lark":
out_image = pilgram.lark(image)
case "lofi":
out_image = pilgram.lofi(image)
case "maven":
out_image = pilgram.maven(image)
case "mayfair":
out_image = pilgram.mayfair(image)
case "moon":
out_image = pilgram.moon(image)
case "nashville":
out_image = pilgram.nashville(image)
case "perpetua":
out_image = pilgram.perpetua(image)
case "reyes":
out_image = pilgram.reyes(image)
case "rise":
out_image = pilgram.rise(image)
case "slumber":
out_image = pilgram.slumber(image)
case "stinson":
out_image = pilgram.stinson(image)
case "toaster":
out_image = pilgram.toaster(image)
case "valencia":
out_image = pilgram.valencia(image)
case "walden":
out_image = pilgram.walden(image)
case "willow":
out_image = pilgram.willow(image)
case "xpro2":
out_image = pilgram.xpro2(image)
case _:
out_image = image
out_image = out_image.convert("RGB")
return ( torch.from_numpy(np.array(out_image).astype(np.float32) / 255.0).unsqueeze(0), )
# COMBINE NODE
class WAS_Image_Blending_Mode:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_a": ("IMAGE",),
"image_b": ("IMAGE",),
"mode": ([
"add",
"color",
"color_burn",
"color_dodge",
"darken",
"difference",
"exclusion",
"hard_light",
"hue",
"lighten",
"multiply",
"overlay",
"screen",
"soft_light"
],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_blending_mode"
CATEGORY = "WAS Suite/Image"
def image_blending_mode(self, image_a, image_b, mode):
# Install Pilgram
if 'pilgram' not in packages():
print("\033[34mWAS NS:\033[0m Installing Pilgram...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'pilgram'])
# Import Pilgram module
import pilgram
# Convert images to PIL
img_a = tensor2pil(image_a)
img_b = tensor2pil(image_b)
# Apply blending
match mode:
case "color":
out_image = pilgram.css.blending.color(img_a, img_b)
case "color_burn":
out_image = pilgram.css.blending.color_burn(img_a, img_b)
case "color_dodge":
out_image = pilgram.css.blending.color_dodge(img_a, img_b)
case "darken":
out_image = pilgram.css.blending.darken(img_a, img_b)
case "difference":
out_image = pilgram.css.blending.difference(img_a, img_b)
case "exclusion":
out_image = pilgram.css.blending.exclusion(img_a, img_b)
case "hard_light":
out_image = pilgram.css.blending.hard_light(img_a, img_b)
case "hue":
out_image = pilgram.css.blending.hue(img_a, img_b)
case "lighten":
out_image = pilgram.css.blending.lighten(img_a, img_b)
case "multiply":
out_image = pilgram.css.blending.multiply(img_a, img_b)
case "add":
out_image = pilgram.css.blending.normal(img_a, img_b)
case "overlay":
out_image = pilgram.css.blending.overlay(img_a, img_b)
case "screen":
out_image = pilgram.css.blending.screen(img_a, img_b)
case "soft_light":
out_image = pilgram.css.blending.soft_light(img_a, img_b)
case _:
out_image = img_a
out_image = out_image.convert("RGB")
return ( pil2tensor(out_image), )
# IMAGE BLEND NODE
class WAS_Image_Blend:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_a": ("IMAGE",),
"image_b": ("IMAGE",),
"blend_percentage": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_blend"
CATEGORY = "WAS Suite/Image"
def image_blend(self, image_a, image_b, blend_percentage):
# Convert images to PIL
img_a = tensor2pil(image_a)
img_b = tensor2pil(image_b)
# Blend image
blend_mask = Image.new(mode = "L", size = img_a.size, color = (round(blend_percentage * 255)))
blend_mask = ImageOps.invert(blend_mask)
img_result = Image.composite(img_a, img_b, blend_mask)
del img_a, img_b, blend_mask
return ( pil2tensor(img_result), )
# IMAGE THRESHOLD NODE
class WAS_Image_Threshold:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"threshold": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_threshold"
CATEGORY = "WAS Suite/Image"
def image_threshold(self, image, threshold=0.5):
return ( pil2tensor(self.apply_threshold(tensor2pil(image), threshold)), )
# IMAGE CHROMATIC ABERRATION NODE
class WAS_Image_Chromatic_Aberration:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"red_offset": ("INT", {"default": 2, "min": -255, "max": 255, "step": 1}),
"green_offset": ("INT", {"default": -1, "min": -255, "max": 255, "step": 1}),
"blue_offset": ("INT", {"default": 1, "min": -255, "max": 255, "step": 1}),
"intensity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_chromatic_aberration"
CATEGORY = "WAS Suite/Image"
def image_chromatic_aberration(self, image, red_offset=4, green_offset=2, blue_offset=0, intensity=1):
return ( pil2tensor(self.apply_chromatic_aberration(tensor2pil(image), red_offset, green_offset, blue_offset, intensity)), )
def apply_chromatic_aberration(self, img, r_offset, g_offset, b_offset, intensity):
# split the channels of the image
r, g, b = img.split()
# apply the offset to each channel
r_offset_img = ImageChops.offset(r, r_offset, 0)
g_offset_img = ImageChops.offset(g, 0, g_offset)
b_offset_img = ImageChops.offset(b, 0, b_offset)
# blend the original image with the offset channels
blended_r = ImageChops.blend(r, r_offset_img, intensity)
blended_g = ImageChops.blend(g, g_offset_img, intensity)
blended_b = ImageChops.blend(b, b_offset_img, intensity)
# merge the channels back into an RGB image
result = Image.merge("RGB", (blended_r, blended_g, blended_b))
return result
# IMAGE BLOOM FILTER
class WAS_Image_Bloom_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"radius": ("FLOAT", {"default": 10, "min": 0.0, "max": 1024, "step": 0.1}),
"intensity": ("FLOAT", {"default": 1, "min": 0.0, "max": 1.0, "step": 0.1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_bloom"
CATEGORY = "WAS Suite/Image"
def image_bloom(self, image, radius=0.5, intensity=1.0):
return ( pil2tensor(self.apply_bloom_filter(tensor2pil(image), radius, intensity)), )
def apply_bloom_filter(self, input_image, radius, bloom_factor):
# Apply a blur filter to the input image
blurred_image = input_image.filter(ImageFilter.GaussianBlur(radius=radius))
# Subtract the blurred image from the input image to create a high-pass filter
high_pass_filter = ImageChops.subtract(input_image, blurred_image)
# Create a blurred version of the bloom filter
bloom_filter = high_pass_filter.filter(ImageFilter.GaussianBlur(radius=radius*2))
# Adjust brightness and levels of bloom filter
bloom_filter = ImageEnhance.Brightness(bloom_filter).enhance(2.0)
# Multiply the bloom image with the bloom factor
bloom_filter = ImageChops.multiply(bloom_filter, Image.new('RGB', input_image.size, (int(255 * bloom_factor), int(255 * bloom_factor), int(255 * bloom_factor))))
# Multiply the bloom filter with the original image using the bloom factor
blended_image = ImageChops.screen(input_image, bloom_filter)
return blended_image
# IMAGE REMOVE COLOR
class WAS_Image_Remove_Color:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"target_red": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"target_green": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"target_blue": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"replace_red": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"replace_green": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"replace_blue": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"clip_threshold": ("INT", {"default": 10, "min": 0, "max": 255, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_remove_color"
CATEGORY = "WAS Suite/Image"
def image_remove_color(self, image, clip_threshold=10, target_red=255, target_green=255, target_blue=255, replace_red=255, replace_green=255, replace_blue=255):
return ( pil2tensor(self.apply_remove_color(tensor2pil(image), clip_threshold, (target_red, target_green, target_blue), (replace_red, replace_green, replace_blue))), )
def apply_remove_color(self, image, threshold=10, color=(255, 255, 255), rep_color=(0, 0, 0)):
# Create a color image with the same size as the input image
color_image = Image.new('RGB', image.size, color)
# Calculate the difference between the input image and the color image
diff_image = ImageChops.difference(image, color_image)
# Convert the difference image to grayscale
gray_image = diff_image.convert('L')
# Apply a threshold to the grayscale difference image
mask_image = gray_image.point(lambda x: 255 if x > threshold else 0)
# Invert the mask image
mask_image = ImageOps.invert(mask_image)
# Apply the mask to the original image
result_image = Image.composite(Image.new('RGB', image.size, rep_color), image, mask_image)
return result_image
# IMAGE BLEND MASK NODE
class WAS_Image_Blend_Mask:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_a": ("IMAGE",),
"image_b": ("IMAGE",),
"mask": ("IMAGE",),
"blend_percentage": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_blend_mask"
CATEGORY = "WAS Suite/Image"
def image_blend_mask(self, image_a, image_b, mask, blend_percentage):
# Convert images to PIL
img_a = tensor2pil(image_a)
img_b = tensor2pil(image_b)
mask = ImageOps.invert(tensor2pil(mask).convert('L'))
# Mask image
masked_img = Image.composite(img_a, img_b, mask.resize(img_a.size))
# Blend image
blend_mask = Image.new(mode = "L", size = img_a.size, color = (round(blend_percentage * 255)))
blend_mask = ImageOps.invert(blend_mask)
img_result = Image.composite(img_a, masked_img, blend_mask)
del img_a, img_b, blend_mask, mask
return ( pil2tensor(img_result), )
# IMAGE BLANK NOE
class WAS_Image_Blank:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 1}),
"height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 1}),
"red": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"green": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
"blue": ("INT", {"default": 255, "min": 0, "max": 255, "step": 1}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "blank_image"
CATEGORY = "WAS Suite/Image"
def blank_image(self, width, height, red, green, blue):
# Ensure multiples
width = ( width // 8 ) * 8
height = ( height // 8 ) * 8
# Blend image
blank = Image.new(mode = "RGB", size = (width, height), color = (red, green, blue))
return ( pil2tensor(blank), )
# IMAGE HIGH PASS
class WAS_Image_High_Pass_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"radius": ("INT", {"default": 10, "min": 1, "max": 500, "step": 1}),
"strength": ("FLOAT", {"default": 1.5, "min": 0.0, "max": 255.0, "step": 0.1})
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "high_pass"
CATEGORY = "WAS Suite/Image"
def high_pass(self, image, radius=10, strength=1.5):
hpf = tensor2pil(image).convert('L')
return ( pil2tensor(self.apply_hpf(hpf.convert('RGB'), radius, strength)), )
def apply_hpf(self, img, radius=10, strength=1.5):
# pil to numpy
img_arr = np.array(img).astype('float')
# Apply a Gaussian blur with the given radius
blurred_arr = np.array(img.filter(ImageFilter.GaussianBlur(radius=radius))).astype('float')
# Apply the High Pass Filter
hpf_arr = img_arr - blurred_arr
hpf_arr = np.clip(hpf_arr * strength, 0, 255).astype('uint8')
# Convert the numpy array back to a PIL image and return it
return Image.fromarray(hpf_arr, mode='RGB')
# IMAGE LEVELS NODE
class WAS_Image_Levels:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"black_level": ("FLOAT", {"default": 0.0, "min": 0.0, "max":255.0, "step": 0.1}),
"mid_level": ("FLOAT", {"default": 127.5, "min": 0.0, "max": 255.0, "step": 0.1}),
"white_level": ("FLOAT", {"default": 255, "min": 0.0, "max": 255.0, "step": 0.1}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "apply_image_levels"
CATEGORY = "WAS Suite/Image"
def apply_image_levels(self, image, black_level, mid_level, white_level):
# Convert image to PIL
image = tensor2pil(image)
#apply image levels
#image = self.adjust_levels(image, black_level, mid_level, white_level)
levels = self.AdjustLevels(black_level, mid_level, white_level)
image = levels.adjust(image)
# Return adjust image tensor
return ( pil2tensor(image), )
def adjust_levels(self, image, black=0.0, mid=1.0, white=255):
"""
Adjust the black, mid, and white levels of an RGB image.
"""
# Create a new empty image with the same size and mode as the original image
result = Image.new(image.mode, image.size)
# Check that the mid value is within the valid range
if mid < 0 or mid > 1:
raise ValueError("mid value must be between 0 and 1")
# Create a lookup table to map the pixel values to new values
lut = []
for i in range(256):
if i < black:
lut.append(0)
elif i > white:
lut.append(255)
else:
lut.append(int(((i - black) / (white - black)) ** mid * 255.0))
# Split the image into its red, green, and blue channels
r, g, b = image.split()
# Apply the lookup table to each channel
r = r.point(lut)
g = g.point(lut)
b = b.point(lut)
# Merge the channels back into an RGB image
result = Image.merge("RGB", (r, g, b))
return result
class AdjustLevels:
def __init__(self, min_level, mid_level, max_level):
self.min_level = min_level
self.mid_level = mid_level
self.max_level = max_level
def adjust(self, im):
# load the image
# convert the image to a numpy array
im_arr = np.array(im)
# apply the min level adjustment
im_arr[im_arr < self.min_level] = self.min_level
# apply the mid level adjustment
im_arr = (im_arr - self.min_level) * (255 / (self.max_level - self.min_level))
im_arr[im_arr < 0] = 0
im_arr[im_arr > 255] = 255
im_arr = im_arr.astype(np.uint8)
# apply the max level adjustment
im = Image.fromarray(im_arr)
im = ImageOps.autocontrast(im, cutoff=self.max_level)
return im
# FILM GRAIN NODE
class WAS_Film_Grain:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"density": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 1.0, "step": 0.01}),
"intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 1.0, "step": 0.01}),
"highlights": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 255.0, "step": 0.01}),
"supersample_factor": ("INT", {"default": 4, "min": 1, "max": 8, "step": 1})
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "film_grain"
CATEGORY = "WAS Suite/Image"
def film_grain(self, image, density, intensity, highlights, supersample_factor):
return ( pil2tensor(self.apply_film_grain(tensor2pil(image), density, intensity, highlights, supersample_factor)), )
def apply_film_grain(self, img, density=0.1, intensity=1.0, highlights=1.0, supersample_factor = 4):
"""
Apply grayscale noise with specified density, intensity, and highlights to a PIL image.
"""
# Convert the image to grayscale
img_gray = img.convert('L')
# Super Resolution noise image
original_size = img.size
img_gray = img_gray.resize(((img.size[0] * supersample_factor), (img.size[1] * supersample_factor)), Image.Resampling(2))
# Calculate the number of noise pixels to add
num_pixels = int(density * img_gray.size[0] * img_gray.size[1])
# Create a list of noise pixel positions
noise_pixels = []
for i in range(num_pixels):
x = random.randint(0, img_gray.size[0]-1)
y = random.randint(0, img_gray.size[1]-1)
noise_pixels.append((x, y))
# Apply the noise to the grayscale image
for x, y in noise_pixels:
value = random.randint(0, 255)
img_gray.putpixel((x, y), value)
# Convert the grayscale image back to RGB
img_noise = img_gray.convert('RGB')
# Blur noise image
img_noise = img_noise.filter(ImageFilter.GaussianBlur(radius = 0.125))
# Downsize noise image
img_noise = img_noise.resize(original_size, Image.Resampling(1))
# Sharpen super resolution result
img_noise = img_noise.filter(ImageFilter.EDGE_ENHANCE_MORE)
# Blend the noisy color image with the original color image
img_final = Image.blend(img, img_noise, intensity)
# Adjust the highlights
enhancer = ImageEnhance.Brightness(img_final)
img_highlights = enhancer.enhance(highlights)
# Return the final image
return img_highlights
# IMAGE FLIP NODE
class WAS_Image_Flip:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"mode": (["horizontal", "vertical",],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_flip"
CATEGORY = "WAS Suite/Image"
def image_flip(self, image, mode):
# PIL Image
image = tensor2pil(image)
# Rotate Image
if mode == 'horizontal':
image = image.transpose(0)
if mode == 'vertical':
image = image.transpose(1)
return ( pil2tensor(image), )
class WAS_Image_Rotate:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"mode": (["transpose", "internal",],),
"rotation": ("INT", {"default": 0, "min": 0, "max": 360, "step": 90}),
"sampler": (["nearest", "bilinear", "bicubic"],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_rotate"
CATEGORY = "WAS Suite/Image"
def image_rotate(self, image, mode, rotation, sampler):
# PIL Image
image = tensor2pil(image)
# Check rotation
if rotation > 360:
rotation = int(360)
if (rotation % 90 != 0):
rotation = int((rotation//90)*90);
# Set Sampler
match sampler:
case 'nearest':
sampler = PIL.Image.NEAREST
case 'bicubic':
sampler = PIL.Image.BICUBIC
case 'bilinear':
sampler = PIL.Image.BILINEAR
# Rotate Image
if mode == 'internal':
image = image.rotate(rotation, sampler)
else:
rot = int(rotation / 90)
for _ in range(rot):
image = image.transpose(2)
return ( torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0), )
# IMAGE NOVA SINE FILTER
class WAS_Image_Nova_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"amplitude": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.001}),
"frequency": ("FLOAT", {"default": 3.14, "min": 0.0, "max": 100.0, "step": 0.001}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "nova_sine"
CATEGORY = "WAS Suite/Image"
def nova_sine(self, image, amplitude, frequency):
# Convert image to numpy
img = tensor2pil(image)
# Convert the image to a numpy array
img_array = np.array(img)
# Define a sine wave function
def sine(x, freq, amp):
return amp * np.sin(2 * np.pi * freq * x)
# Calculate the sampling frequency of the image
resolution = img.info.get('dpi') # PPI
physical_size = img.size # pixels
if resolution is not None:
# Convert PPI to pixels per millimeter (PPM)
ppm = 25.4 / resolution
physical_size = tuple(int(pix * ppm) for pix in physical_size)
# Set the maximum frequency for the sine wave
max_freq = img.width / 2
# Ensure frequency isn't outside visual representable range
if frequency > max_freq:
frequency = max_freq
# Apply levels to the image using the sine function
for i in range(img_array.shape[0]):
for j in range(img_array.shape[1]):
for k in range(img_array.shape[2]):
img_array[i,j,k] = int(sine(img_array[i,j,k]/255, frequency, amplitude) * 255)
return ( torch.from_numpy(img_array.astype(np.float32) / 255.0).unsqueeze(0), )
# IMAGE CANNY FILTER
class WAS_Canny_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"enable_threshold": (['false', 'true'],),
"threshold_low": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"threshold_high": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "canny_filter"
CATEGORY = "WAS Suite/Image"
def canny_filter(self, image, threshold_low, threshold_high, enable_threshold):
self.install_opencv()
if enable_threshold == 'false':
threshold_low = None
threshold_high = None
image_canny = Image.fromarray(self.Canny_detector(255. * image.cpu().numpy().squeeze(), threshold_low, threshold_high)).convert('RGB')
return ( pil2tensor(image_canny), )
# Defining the Canny Detector function
# From: https://www.geeksforgeeks.org/implement-canny-edge-detector-in-python-using-opencv/
# here weak_th and strong_th are thresholds for
# double thresholding step
def Canny_detector(self, img, weak_th = None, strong_th = None):
import cv2
# conversion of image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Noise reduction step
img = cv2.GaussianBlur(img, (5, 5), 1.4)
# Calculating the gradients
gx = cv2.Sobel(np.float32(img), cv2.CV_64F, 1, 0, 3)
gy = cv2.Sobel(np.float32(img), cv2.CV_64F, 0, 1, 3)
# Conversion of Cartesian coordinates to polar
mag, ang = cv2.cartToPolar(gx, gy, angleInDegrees = True)
# setting the minimum and maximum thresholds
# for double thresholding
mag_max = np.max(mag)
if not weak_th:weak_th = mag_max * 0.1
if not strong_th:strong_th = mag_max * 0.5
# getting the dimensions of the input image
height, width = img.shape
# Looping through every pixel of the grayscale
# image
for i_x in range(width):
for i_y in range(height):
grad_ang = ang[i_y, i_x]
grad_ang = abs(grad_ang-180) if abs(grad_ang)>180 else abs(grad_ang)
# selecting the neighbours of the target pixel
# according to the gradient direction
# In the x axis direction
if grad_ang<= 22.5:
neighb_1_x, neighb_1_y = i_x-1, i_y
neighb_2_x, neighb_2_y = i_x + 1, i_y
# top right (diagonal-1) direction
elif grad_ang>22.5 and grad_ang<=(22.5 + 45):
neighb_1_x, neighb_1_y = i_x-1, i_y-1
neighb_2_x, neighb_2_y = i_x + 1, i_y + 1
# In y-axis direction
elif grad_ang>(22.5 + 45) and grad_ang<=(22.5 + 90):
neighb_1_x, neighb_1_y = i_x, i_y-1
neighb_2_x, neighb_2_y = i_x, i_y + 1
# top left (diagonal-2) direction
elif grad_ang>(22.5 + 90) and grad_ang<=(22.5 + 135):
neighb_1_x, neighb_1_y = i_x-1, i_y + 1
neighb_2_x, neighb_2_y = i_x + 1, i_y-1
# Now it restarts the cycle
elif grad_ang>(22.5 + 135) and grad_ang<=(22.5 + 180):
neighb_1_x, neighb_1_y = i_x-1, i_y
neighb_2_x, neighb_2_y = i_x + 1, i_y
# Non-maximum suppression step
if width>neighb_1_x>= 0 and height>neighb_1_y>= 0:
if mag[i_y, i_x]<mag[neighb_1_y, neighb_1_x]:
mag[i_y, i_x]= 0
continue
if width>neighb_2_x>= 0 and height>neighb_2_y>= 0:
if mag[i_y, i_x]<mag[neighb_2_y, neighb_2_x]:
mag[i_y, i_x]= 0
weak_ids = np.zeros_like(img)
strong_ids = np.zeros_like(img)
ids = np.zeros_like(img)
# double thresholding step
for i_x in range(width):
for i_y in range(height):
grad_mag = mag[i_y, i_x]
if grad_mag<weak_th:
mag[i_y, i_x]= 0
elif strong_th>grad_mag>= weak_th:
ids[i_y, i_x]= 1
else:
ids[i_y, i_x]= 2
# finally returning the magnitude of
# gradients of edges
return mag
def install_opencv(self):
if 'opencv-python' not in packages():
print("\033[34mWAS NS:\033[0m Installing CV2...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
# IMAGE EDGE DETECTION
class WAS_Image_Edge:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"mode": (["normal", "laplacian"],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "image_edges"
CATEGORY = "WAS Suite/Image"
def image_edges(self, image, mode):
# Convert image to PIL
image = tensor2pil(image)
# Detect edges
match mode:
case "normal":
image = image.filter(ImageFilter.FIND_EDGES)
case "laplacian":
image = image.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 8,
-1, -1, -1, -1), 1, 0))
case _:
image = image
return ( torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0), )
# IMAGE FDOF NODE
class WAS_Image_fDOF:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"depth": ("IMAGE",),
"mode": (["mock","gaussian","box"],),
"radius": ("INT", {"default": 8, "min": 1, "max": 128, "step": 1}),
"samples": ("INT", {"default": 1, "min": 1, "max": 3, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "fdof_composite"
CATEGORY = "WAS Suite/Image"
def fdof_composite(self, image, depth, radius, samples, mode):
if 'opencv-python' not in packages():
print("\033[34mWAS NS:\033[0m Installing CV2...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
import cv2 as cv
#Convert tensor to a PIL Image
i = 255. * image.cpu().numpy().squeeze()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
d = 255. * depth.cpu().numpy().squeeze()
depth_img = Image.fromarray(np.clip(d, 0, 255).astype(np.uint8))
#Apply Fake Depth of Field
fdof_image = self.portraitBlur(img, depth_img, radius, samples, mode)
return ( torch.from_numpy(np.array(fdof_image).astype(np.float32) / 255.0).unsqueeze(0), )
def portraitBlur(self, img, mask, radius=5, samples=1, mode = 'mock'):
mask = mask.resize(img.size).convert('L')
if mode == 'mock':
bimg = medianFilter(img, radius, (radius * 1500), 75)
elif mode == 'gaussian':
bimg = img.filter(ImageFilter.GaussianBlur(radius = radius))
elif mode == 'box':
bimg = img.filter(ImageFilter.BoxBlur(radius))
bimg.convert(img.mode)
rimg = None
if samples > 1:
for i in range(samples):
if i == 0:
rimg = Image.composite(img, bimg, mask)
else:
rimg = Image.composite(rimg, bimg, mask)
else:
rimg = Image.composite(img, bimg, mask).convert('RGB')
return rimg
# TODO: Implement lens_blur mode attempt
def lens_blur(img, radius, amount, mask=None):
"""Applies a lens shape blur effect on an image.
Args:
img (numpy.ndarray): The input image as a numpy array.
radius (float): The radius of the lens shape.
amount (float): The amount of blur to be applied.
mask (numpy.ndarray): An optional mask image specifying where to apply the blur.
Returns:
numpy.ndarray: The blurred image as a numpy array.
"""
# Create a lens shape kernel.
kernel = cv2.getGaussianKernel(ksize=int(radius * 10), sigma=0)
kernel = np.dot(kernel, kernel.T)
# Normalize the kernel.
kernel /= np.max(kernel)
# Create a circular mask for the kernel.
mask_shape = (int(radius * 2), int(radius * 2))
mask = np.ones(mask_shape) if mask is None else cv2.resize(mask, mask_shape, interpolation=cv2.INTER_LINEAR)
mask = cv2.GaussianBlur(mask, (int(radius * 2) + 1, int(radius * 2) + 1), radius / 2)
mask /= np.max(mask)
# Adjust kernel and mask size to match input image.
ksize_x = img.shape[1] // (kernel.shape[1] + 1)
ksize_y = img.shape[0] // (kernel.shape[0] + 1)
kernel = cv2.resize(kernel, (ksize_x, ksize_y), interpolation=cv2.INTER_LINEAR)
kernel = cv2.copyMakeBorder(kernel, 0, img.shape[0] - kernel.shape[0], 0, img.shape[1] - kernel.shape[1], cv2.BORDER_CONSTANT, value=0)
mask = cv2.resize(mask, (ksize_x, ksize_y), interpolation=cv2.INTER_LINEAR)
mask = cv2.copyMakeBorder(mask, 0, img.shape[0] - mask.shape[0], 0, img.shape[1] - mask.shape[1], cv2.BORDER_CONSTANT, value=0)
# Apply the lens shape blur effect on the image.
blurred = cv2.filter2D(img, -1, kernel)
blurred = cv2.filter2D(blurred, -1, mask * amount)
if mask is not None:
# Apply the mask to the original image.
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
img_masked = img * mask
# Combine the masked image with the blurred image.
blurred = img_masked * (1 - mask) + blurred
return blurred
# IMAGE MEDIAN FILTER NODE
class WAS_Image_Median_Filter:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"diameter": ("INT", {"default": 2.0, "min": 0.1, "max": 255, "step": 1}),
"sigma_color": ("FLOAT", {"default": 10.0, "min": -255.0, "max": 255.0, "step": 0.1}),
"sigma_space": ("FLOAT", {"default": 10.0, "min": -255.0, "max": 255.0, "step": 0.1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "apply_median_filter"
CATEGORY = "WAS Suite/Image"
def apply_median_filter(self, image, diameter, sigma_color, sigma_space):
# Numpy Image
image = tensor2pil(image)
# Apply Median Filter effect
image = medianFilter(image, diameter, sigma_color, sigma_space)
return ( pil2tensor(image), )
# IMAGE SELECT COLOR
class WAS_Image_Select_Color:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"red": ("INT", {"default": 255.0, "min": 0.0, "max": 255.0, "step": 0.1}),
"green": ("INT", {"default": 255.0, "min": 0.0, "max": 255.0, "step": 0.1}),
"blue": ("INT", {"default": 255.0, "min": 0.0, "max": 255.0, "step": 0.1}),
"variance": ("INT", {"default": 10, "min": 0, "max": 255, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "select_color"
CATEGORY = "WAS Suite/Image"
def select_color(self, image, red=255, green=255, blue=255, variance=10):
if 'opencv-python' not in packages():
print("\033[34mWAS NS:\033[0m Installing CV2...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
image = self.color_pick(tensor2pil(image), red, green, blue, variance)
return ( pil2tensor(image), )
def color_pick(self, image, red=255, green=255, blue=255, variance=10):
# Convert image to RGB mode
image = image.convert('RGB')
# Create a new black image of the same size as the input image
selected_color = Image.new('RGB', image.size, (0,0,0))
# Get the width and height of the image
width, height = image.size
# Loop through every pixel in the image
for x in range(width):
for y in range(height):
# Get the color of the pixel
pixel = image.getpixel((x,y))
r,g,b = pixel
# Check if the pixel is within the specified color range
if ((r >= red-variance) and (r <= red+variance) and
(g >= green-variance) and (g <= green+variance) and
(b >= blue-variance) and (b <= blue+variance)):
# Set the pixel in the selected_color image to the RGB value of the pixel
selected_color.putpixel((x,y),(r,g,b))
# Return the selected color image
return selected_color
# IMAGE CONVERT TO CHANNEL
class WAS_Image_Select_Channel:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"channel": (['red','green','blue'],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "select_channel"
CATEGORY = "WAS Suite/Image"
def select_channel(self, image, channel='red'):
image = self.convert_to_single_channel(tensor2pil(image), channel)
return ( pil2tensor(image), )
def convert_to_single_channel(self, image, channel='red'):
# Convert to RGB mode to access individual channels
image = image.convert('RGB')
# Extract the desired channel and convert to greyscale
if channel == 'red':
channel_img = image.split()[0].convert('L')
elif channel == 'green':
channel_img = image.split()[1].convert('L')
elif channel == 'blue':
channel_img = image.split()[2].convert('L')
else:
raise ValueError("Invalid channel option. Please choose 'red', 'green', or 'blue'.")
# Convert the greyscale channel back to RGB mode
channel_img = Image.merge('RGB', (channel_img, channel_img, channel_img))
return channel_img
# IMAGE CONVERT TO CHANNEL
class WAS_Image_RGB_Merge:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"red_channel": ("IMAGE",),
"green_channel": ("IMAGE",),
"blue_channel": ("IMAGE",),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "merge_channels"
CATEGORY = "WAS Suite/Image"
def merge_channels(self, red_channel, green_channel, blue_channel):
# Apply mix rgb channels
image = self.mix_rgb_channels(tensor2pil(red_channel).convert('L'), tensor2pil(green_channel).convert('L'), tensor2pil(blue_channel).convert('L'))
return ( pil2tensor(image), )
def mix_rgb_channels(self, red, green, blue):
# Create an empty image with the same size as the channels
width, height = red.size; merged_img = Image.new('RGB', (width, height))
# Merge the channels into the new image
merged_img = Image.merge('RGB', (red, green, blue))
return merged_img
# Image Save (NSP Compatible)
# Originally From ComfyUI/nodes.py
class WAS_Image_Save:
def __init__(self):
self.output_dir = os.path.join(os.getcwd()+'/ComfyUI', "output")
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE", ),
"output_path": ("STRING", {"default": './ComfyUI/output', "multiline": False}),
"filename_prefix": ("STRING", {"default": "ComfyUI"}),
"extension": (['png', 'jpeg', 'tiff', 'gif'], ),
"quality": ("INT", {"default": 100, "min": 1, "max": 100, "step": 1}),
},
"hidden": {
"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
},
}
RETURN_TYPES = ()
FUNCTION = "save_images"
OUTPUT_NODE = True
CATEGORY = "WAS Suite/IO"
def save_images(self, images, output_path='', filename_prefix="ComfyUI", extension='png', quality=100, prompt=None, extra_pnginfo=None):
def map_filename(filename):
prefix_len = len(filename_prefix)
prefix = filename[:prefix_len + 1]
try:
digits = int(filename[prefix_len + 1:].split('_')[0])
except:
digits = 0
return (digits, prefix)
# Setup custom path or default
if output_path.strip() != '':
if not os.path.exists(output_path.strip()):
print(f'\033[34mWAS NS\033[0m Error: The path `{output_path.strip()}` specified doesn\'t exist! Defaulting to `{self.output_dir}` directory.')
else:
self.output_dir = os.path.normpath(output_path.strip())
print(self.output_dir)
# Define counter for files found
try:
counter = max(filter(lambda a: a[1][:-1] == filename_prefix and a[1][-1] == "_", map(map_filename, os.listdir(self.output_dir))))[0] + 1
except ValueError:
counter = 1
except FileNotFoundError:
os.mkdir(self.output_dir)
counter = 1
paths = list()
for image in images:
i = 255. * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
file = f"{filename_prefix}_{counter:05}_.{extension}"
if extension == 'png':
img.save(os.path.join(self.output_dir, file), pnginfo=metadata, optimize=True)
elif extension == 'webp':
img.save(os.path.join(self.output_dir, file), quality=quality)
elif extension == 'jpeg':
img.save(os.path.join(self.output_dir, file), quality=quality, optimize=True)
elif extension == 'tiff':
img.save(os.path.join(self.output_dir, file), quality=quality, optimize=True)
else:
img.save(os.path.join(self.output_dir, file))
paths.append(file)
counter += 1
return { "ui": { "images": paths } }
# LOAD IMAGE NODE
class WAS_Load_Image:
def __init__(self):
self.input_dir = os.path.join(os.getcwd()+'/ComfyUI', "input")
@classmethod
def INPUT_TYPES(s):
return {"required":
{"image_path": ("STRING", {"default": './ComfyUI/input/example.png', "multiline": False}),}
}
CATEGORY = "WAS Suite/IO"
RETURN_TYPES = ("IMAGE", "MASK")
FUNCTION = "load_image"
def load_image(self, image_path):
try:
i = Image.open(image_path)
except OSError:
print(f'\033[34mWAS NS\033[0m Error: The image `{output_path.strip()}` specified doesn\'t exist!')
i = Image.new(mode='RGB', size=(512,512), color=(0,0,0))
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
return (image, mask)
@classmethod
def IS_CHANGED(s, image_path):
m = hashlib.sha256()
with open(image_path, 'rb') as f:
m.update(f.read())
return m.digest().hex()
# TENSOR TO IMAGE NODE
class WAS_Tensor_Batch_to_Image:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images_batch": ("IMAGE",),
"batch_image_number": ("INT", {"default": 0, "min": 0, "max": 64, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "tensor_batch_to_image"
CATEGORY = "WAS Suite/Latent"
def tensor_batch_to_image(self, images_batch=None, batch_image_number=0):
count = 0
for _ in images_batch:
if batch_image_number == count:
return ( images_batch[batch_image_number].unsqueeze(0), )
count = count+1
print(f"\033[34mWAS NS\033[0m Error: Batch number `{batch_image_number}` is not defined, returning last image")
return( images_batch[-1].unsqueeze(0), )
#! LATENT NODES
# IMAGE TO MASK
class WAS_Image_To_Mask:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {"required":
{"image": ("IMAGE",),
"channel": (["alpha", "red", "green", "blue"], ),}
}
CATEGORY = "WAS Suite/Latent"
RETURN_TYPES = ("MASK",)
FUNCTION = "image_to_mask"
def image_to_mask(self, image, channel):
img = tensor2pil(image)
mask = None
c = channel[0].upper()
if c in img.getbands():
mask = np.array(img.getchannel(c)).astype(np.float32) / 255.0
mask = torch.from_numpy(mask)
if c == 'A':
mask = 1. - mask
else:
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
return ( mask, )
# LATENT UPSCALE NODE
class WAS_Latent_Upscale:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {"required": { "samples": ("LATENT",), "mode": (["bilinear", "bicubic", "trilinear"],),
"factor": ("FLOAT", {"default": 2.0, "min": 0.1, "max": 8.0, "step": 0.1}),
"align": (["true", "false"], )}}
RETURN_TYPES = ("LATENT",)
FUNCTION = "latent_upscale"
CATEGORY = "WAS Suite/Latent"
def latent_upscale(self, samples, mode, factor, align):
s = samples.copy()
s["samples"] = torch.nn.functional.interpolate(s['samples'], scale_factor=factor, mode=mode, align_corners=( True if align == 'true' else False ))
return (s,)
# LATENT NOISE INJECTION NODE
class WAS_Latent_Noise:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"samples": ("LATENT",),
"noise_std": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 1.0, "step": 0.01}),
}
}
RETURN_TYPES = ("LATENT",)
FUNCTION = "inject_noise"
CATEGORY = "WAS Suite/Latent"
def inject_noise(self, samples, noise_std):
s = samples.copy()
noise = torch.randn_like(s["samples"]) * noise_std
s["samples"] = s["samples"] + noise
return (s,)
# MIDAS DEPTH APPROXIMATION NODE
class MiDaS_Depth_Approx:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"use_cpu": (["false", "true"],),
"midas_model": (["DPT_Large", "DPT_Hybrid", "DPT_Small"],),
"invert_depth": (["false", "true"],),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "midas_approx"
CATEGORY = "WAS Suite/Image"
def midas_approx(self, image, use_cpu, midas_model, invert_depth):
global MIDAS_INSTALLED
if not MIDAS_INSTALLED:
self.install_midas()
import cv2 as cv
# Convert the input image tensor to a PIL Image
i = 255. * image.cpu().numpy().squeeze()
img = i
print("\033[34mWAS NS:\033[0m Downloading and loading MiDaS Model...")
midas = torch.hub.load("intel-isl/MiDaS", midas_model, trust_repo=True)
device = torch.device("cuda") if torch.cuda.is_available() and use_cpu == 'false' else torch.device("cpu")
print('\033[34mWAS NS:\033[0m MiDaS is using device:', device)
midas.to(device).eval()
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if midas_model == "DPT_Large" or midas_model == "DPT_Hybrid":
transform = midas_transforms.dpt_transform
else:
transform = midas_transforms.small_transform
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
input_batch = transform(img).to(device)
print('\033[34mWAS NS:\033[0m Approximating depth from image.')
with torch.no_grad():
prediction = midas(input_batch)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
if invert_depth == 'true':
depth = ( 255 - prediction.cpu().numpy().astype(np.uint8) )
depth = depth.astype(np.float32)
else:
depth = prediction.cpu().numpy().astype(np.float32)
depth = depth * 255 / (np.max(depth)) / 255
# Invert depth map
depth = cv.cvtColor(depth, cv.COLOR_GRAY2RGB)
tensor = torch.from_numpy( depth )[None,]
tensors = ( tensor, )
del midas, device, midas_transforms
del transform, img, input_batch, prediction
return tensors
def install_midas(self):
global MIDAS_INSTALLED
if 'timm' not in packages():
print("\033[34mWAS NS:\033[0m Installing timm...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'timm'])
if 'opencv-python' not in packages():
print("\033[34mWAS NS:\033[0m Installing CV2...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
MIDAS_INSTALLED = True
# MIDAS REMOVE BACKGROUND/FOREGROUND NODE
class MiDaS_Background_Foreground_Removal:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"use_cpu": (["false", "true"],),
"midas_model": (["DPT_Large", "DPT_Hybrid", "DPT_Small"],),
"remove": (["background", "foregroud"],),
"threshold": (["false", "true"],),
"threshold_low": ("FLOAT", {"default": 10, "min": 0, "max": 255, "step": 1}),
"threshold_mid": ("FLOAT", {"default": 200, "min": 0, "max": 255, "step": 1}),
"threshold_high": ("FLOAT", {"default": 210, "min": 0, "max": 255, "step": 1}),
"smoothing": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 16.0, "step": 0.01}),
"background_red": ("INT", {"default": 0, "min": 0, "max": 255, "step": 1}),
"background_green": ("INT", {"default": 0, "min": 0, "max": 255, "step": 1}),
"background_blue": ("INT", {"default": 0, "min": 0, "max": 255, "step": 1}),
},
}
RETURN_TYPES = ("IMAGE","IMAGE")
FUNCTION = "midas_remove"
CATEGORY = "WAS Suite/Image"
def midas_remove(self,
image,
midas_model,
use_cpu='false',
remove='background',
threshold='false',
threshold_low=0,
threshold_mid=127,
threshold_high=255,
smoothing=0.25,
background_red=0,
background_green=0,
background_blue=0):
global MIDAS_INSTALLED
if not MIDAS_INSTALLED:
self.install_midas()
import cv2 as cv
# Convert the input image tensor to a numpy and PIL Image
i = 255. * image.cpu().numpy().squeeze()
img = i
# Original image
img_original = tensor2pil(image).convert('RGB')
print("\033[34mWAS NS:\033[0m Downloading and loading MiDaS Model...")
midas = torch.hub.load("intel-isl/MiDaS", midas_model, trust_repo=True)
device = torch.device("cuda") if torch.cuda.is_available() and use_cpu == 'false' else torch.device("cpu")
print('\033[34mWAS NS:\033[0m MiDaS is using device:', device)
midas.to(device).eval()
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
if midas_model == "DPT_Large" or midas_model == "DPT_Hybrid":
transform = midas_transforms.dpt_transform
else:
transform = midas_transforms.small_transform
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
input_batch = transform(img).to(device)
print('\033[34mWAS NS:\033[0m Approximating depth from image.')
with torch.no_grad():
prediction = midas(input_batch)
prediction = torch.nn.functional.interpolate(
prediction.unsqueeze(1),
size=img.shape[:2],
mode="bicubic",
align_corners=False,
).squeeze()
# Invert depth map
if remove == 'foreground':
depth = ( 255 - prediction.cpu().numpy().astype(np.uint8) )
depth = depth.astype(np.float32)
else:
depth = prediction.cpu().numpy().astype(np.float32)
depth = depth * 255 / (np.max(depth)) / 255
depth = Image.fromarray(np.uint8(depth * 255))
# Threshold depth mask
if threshold == 'true':
levels = self.AdjustLevels(threshold_low, threshold_mid, threshold_high)
depth = levels.adjust(depth.convert('RGB')).convert('L')
if smoothing > 0:
depth = depth.filter(ImageFilter.GaussianBlur(radius=smoothing))
depth = depth.resize(img_original.size).convert('L')
# Validate background color arguments
background_red = int(background_red) if isinstance(background_red, (int, float)) else 0
background_green = int(background_green) if isinstance(background_green, (int, float)) else 0
background_blue = int(background_blue) if isinstance(background_blue, (int, float)) else 0
# Create background color tuple
background_color = ( background_red, background_green, background_blue )
# Create background image
background = Image.new(mode="RGB", size=img_original.size, color=background_color)
# Composite final image
result_img = Image.composite(img_original, background, depth)
del midas, device, midas_transforms
del transform, img, img_original, input_batch, prediction
return ( pil2tensor(result_img), pil2tensor(depth.convert('RGB')) )
class AdjustLevels:
def __init__(self, min_level, mid_level, max_level):
self.min_level = min_level
self.mid_level = mid_level
self.max_level = max_level
def adjust(self, im):
# load the image
# convert the image to a numpy array
im_arr = np.array(im)
# apply the min level adjustment
im_arr[im_arr < self.min_level] = self.min_level
# apply the mid level adjustment
im_arr = (im_arr - self.min_level) * (255 / (self.max_level - self.min_level))
im_arr[im_arr < 0] = 0
im_arr[im_arr > 255] = 255
im_arr = im_arr.astype(np.uint8)
# apply the max level adjustment
im = Image.fromarray(im_arr)
im = ImageOps.autocontrast(im, cutoff=self.max_level)
return im
def install_midas(self):
global MIDAS_INSTALLED
if 'timm' not in packages():
print("\033[34mWAS NS:\033[0m Installing timm...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'timm'])
if 'opencv-python' not in packages():
print("\033[34mWAS NS:\033[0m Installing CV2...")
subprocess.check_call([sys.executable, '-m', 'pip', '-q', 'install', 'opencv-python'])
MIDAS_INSTALLED = True
#! CONDITIONING NODES
# NSP CLIPTextEncode NODE
class WAS_NSP_CLIPTextEncoder:
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"noodle_key": ("STRING", {"default": '__', "multiline": False}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"text": ("STRING", {"multiline": True}),
"clip": ("CLIP",),
}
}
OUTPUT_NODE = True
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "nsp_encode"
CATEGORY = "WAS Suite/Conditioning"
def nsp_encode(self, clip, text, noodle_key = '__', seed = 0):
# Fetch the NSP Pantry
local_pantry = os.getcwd()+'/ComfyUI/custom_nodes/nsp_pantry.json'
if not os.path.exists(local_pantry):
response = urlopen('https://raw.githubusercontent.com/WASasquatch/noodle-soup-prompts/main/nsp_pantry.json')
tmp_pantry = json.loads(response.read())
# Dump JSON locally
pantry_serialized = json.dumps(tmp_pantry, indent=4)
with open(local_pantry, "w") as f:
f.write(pantry_serialized)
del response, tmp_pantry
# Load local pantry
with open(local_pantry, 'r') as f:
nspterminology = json.load(f)
if seed > 0 or seed < 1:
random.seed(seed)
# Parse Text
new_text = text
for term in nspterminology:
# Target Noodle
tkey = f'{noodle_key}{term}{noodle_key}'
# How many occurances?
tcount = new_text.count(tkey)
# Apply random results for each noodle counted
for _ in range(tcount):
new_text = new_text.replace(tkey, random.choice(nspterminology[term]), 1)
seed = seed+1
random.seed(seed)
print('\033[34mWAS NS\033[0m CLIPTextEncode NSP:', new_text)
return ([[clip.encode(new_text), {}]],{"ui":{"prompt":new_text}})
#! SAMPLING NODES
# KSAMPLER
class WAS_KSampler:
@classmethod
def INPUT_TYPES(s):
return {"required":
{"model": ("MODEL",),
"seed": ("SEED",),
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
"scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
"positive": ("CONDITIONING", ),
"negative": ("CONDITIONING", ),
"latent_image": ("LATENT", ),
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
}
}
RETURN_TYPES = ("LATENT",)
FUNCTION = "sample"
CATEGORY = "WAS Suite/Sampling"
def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0):
return nodes.common_ksampler(model, seed['seed'], steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
# SEED NODE
class WAS_Seed:
@classmethod
def INPUT_TYPES(s):
return {"required":
{"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})}
}
RETURN_TYPES = ("SEED",)
FUNCTION = "seed"
CATEGORY = "WAS Suite/Constant"
def seed(self, seed):
return ( {"seed": seed,}, )
#! TEXT NODES
# Text Multiline Node
class WAS_Text_Multiline:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"default": '', "multiline": True}),
}
}
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_multiline"
CATEGORY = "WAS Suite/Text"
def text_multiline(self, text):
return ( text, )
# Text String Node
class WAS_Text_String:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"default": '', "multiline": False}),
}
}
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_string"
CATEGORY = "WAS Suite/Text"
def text_string(self, text):
return ( text, )
# Text Random Line
class WAS_Text_Random_Line:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("ASCII",),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
}
}
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_random_line"
CATEGORY = "WAS Suite/Text"
def text_random_line(self, text, seed):
lines = text.split("\n")
random.seed(seed)
choice = random.choice(lines)
print('\033[34mWAS NS\033[0m Random Line:', choice)
return ( choice, )
# Text Concatenate
class WAS_Text_Concatenate:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text_a": ("ASCII",),
"text_b": ("ASCII",),
"linebreak_addition": (['true','false'], ),
}
}
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_concatenate"
CATEGORY = "WAS Suite/Text"
def text_concatenate(self, text_a, text_b, linebreak_addition):
return ( text_a + ("\n" if linebreak_addition == 'true' else '') + text_b, )
# Text Search and Replace
class WAS_Search_and_Replace:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("ASCII",),
"find": ("STRING", {"default": '', "multiline": False}),
"replace": ("STRING", {"default": '', "multiline": False}),
}
}
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_search_and_replace"
CATEGORY = "WAS Suite/Text"
def text_search_and_replace(self, text, find, replace):
return ( self.replace_substring(text, find, replace), )
def replace_substring(self, text, find, replace):
import re
text = re.sub(find, replace, text)
return text
# Text Parse NSP
class WAS_Text_Parse_NSP:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"noodle_key": ("STRING", {"default": '__', "multiline": False}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"text": ("ASCII",),
}
}
OUTPUT_NODE = True
RETURN_TYPES = ("ASCII",)
FUNCTION = "text_parse_nsp"
CATEGORY = "WAS Suite/Text"
def text_parse_nsp(self, text, noodle_key = '__', seed = 0):
# Fetch the NSP Pantry
local_pantry = os.getcwd()+'/ComfyUI/custom_nodes/nsp_pantry.json'
if not os.path.exists(local_pantry):
response = urlopen('https://raw.githubusercontent.com/WASasquatch/noodle-soup-prompts/main/nsp_pantry.json')
tmp_pantry = json.loads(response.read())
# Dump JSON locally
pantry_serialized = json.dumps(tmp_pantry, indent=4)
with open(local_pantry, "w") as f:
f.write(pantry_serialized)
del response, tmp_pantry
# Load local pantry
with open(local_pantry, 'r') as f:
nspterminology = json.load(f)
if seed > 0 or seed < 1:
random.seed(seed)
# Parse Text
new_text = text
for term in nspterminology:
# Target Noodle
tkey = f'{noodle_key}{term}{noodle_key}'
# How many occurances?
tcount = new_text.count(tkey)
# Apply random results for each noodle counted
for _ in range(tcount):
new_text = new_text.replace(tkey, random.choice(nspterminology[term]), 1)
seed = seed+1
random.seed(seed)
print('\033[34mWAS NS\033[0m Text Parse NSP:', new_text)
return ( new_text, )
# Text Search and Replace
class WAS_Text_Save:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("ASCII",),
"path": ("STRING", {"default": '', "multiline": False}),
"filename": ("STRING", {"default": f'text_[time]', "multiline": False}),
}
}
OUTPUT_NODE = True
RETURN_TYPES = ()
FUNCTION = "save_text_file"
CATEGORY = "WAS Suite/Text"
def save_text_file(self, text, path, filename):
# Ensure path exists
if not os.path.exists(path):
print(f'\033[34mWAS NS\033[0m Error: The path `{path}` doesn\'t exist!')
# Ensure content to save
if text.strip == '':
print(f'\033[34mWAS NS\033[0m Error: There is no text specified to save! Text is empty.')
# Replace tokens
tokens = {
'[time]': f'{round(time.time())}',
}
for k in tokens.keys():
text = self.replace_substring(text, k, tokens[k])
# Write text file
self.writeTextFile(os.path.join(path, filename + '.txt'), text)
return( text, )
# Save Text FileNotFoundError
def writeTextFile(self, file, content):
try:
with open(file, 'w') as f:
f.write(content)
except OSError:
print(f'\033[34mWAS Node Suite\033[0m Error: Unable to save file `{file}`')
# Replace a substring
def replace_substring(self, text, find, replace):
import re
text = re.sub(find, replace, text)
return text
# Text to Conditioning
class WAS_Text_to_Conditioning:
def __init__(s):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"clip": ("CLIP",),
"text": ("ASCII",),
}
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "text_to_conditioning"
CATEGORY = "WAS Suite/Text"
def text_to_conditioning(self, clip, text):
return ( [[clip.encode(text), {}]], )
# NODE MAPPING
NODE_CLASS_MAPPINGS = {
# IMAGE
"Image Filter Adjustments": WAS_Image_Filters,
"Image Style Filter": WAS_Image_Style_Filter,
"Image Blending Mode": WAS_Image_Blending_Mode,
"Image Blend": WAS_Image_Blend,
"Image Blend by Mask": WAS_Image_Blend_Mask,
"Image Remove Color": WAS_Image_Remove_Color,
"Image Threshold": WAS_Image_Threshold,
"Image Chromatic Aberration": WAS_Image_Chromatic_Aberration,
"Image Bloom Filter": WAS_Image_Bloom_Filter,
"Image Blank": WAS_Image_Blank,
"Image Film Grain": WAS_Film_Grain,
"Image Flip": WAS_Image_Flip,
"Image Rotate": WAS_Image_Rotate,
"Image Nova Filter": WAS_Image_Nova_Filter,
"Image Canny Filter": WAS_Canny_Filter,
"Image Edge Detection Filter": WAS_Image_Edge,
"Image fDOF Filter": WAS_Image_fDOF,
"Image Median Filter": WAS_Image_Median_Filter,
"Image Save": WAS_Image_Save,
"Image Load": WAS_Load_Image,
"Image Levels Adjustment": WAS_Image_Levels,
"Image High Pass Filter": WAS_Image_High_Pass_Filter,
"Tensor Batch to Image": WAS_Tensor_Batch_to_Image,
"Image Select Color": WAS_Image_Select_Color,
"Image Select Channel": WAS_Image_Select_Channel,
"Image Mix RGB Channels": WAS_Image_RGB_Merge,
# LATENT
"Latent Upscale by Factor (WAS)": WAS_Latent_Upscale,
"Latent Noise Injection": WAS_Latent_Noise,
"Image to Latent Mask": WAS_Image_To_Mask,
# MIDAS
"MiDaS Depth Approximation": MiDaS_Depth_Approx,
"MiDaS Mask Image": MiDaS_Background_Foreground_Removal,
# CONDITIONING
"CLIPTextEncode (NSP)": WAS_NSP_CLIPTextEncoder,
# SAMPLING
"KSampler (WAS)": WAS_KSampler,
"Seed": WAS_Seed,
# TEXT
"Text Multiline": WAS_Text_Multiline,
"Text String": WAS_Text_String,
"Text Random Line": WAS_Text_Random_Line,
"Text to Conditioning": WAS_Text_to_Conditioning,
"Text Concatenate": WAS_Text_Concatenate,
"Text Find and Replace": WAS_Search_and_Replace,
"Text Parse Noodle Soup Prompts": WAS_Text_Parse_NSP,
"Save Text File": WAS_Text_Save,
}
print('\033[34mWAS Node Suite: \033[92mLoaded\033[0m') |