vedo.colors
Colors definitions and printing methods.
1#!/usr/bin/env python3 2# -*- coding: utf-8 -*- 3import os 4import sys 5import time 6 7import numpy as np 8 9try: 10 import vedo.vtkclasses as vtk 11except ImportError: 12 import vtkmodules.all as vtk 13 14import vedo 15 16__docformat__ = "google" 17 18__doc__ = """ 19Colors definitions and printing methods. 20 21 22""" 23 24__all__ = [ 25 "printc", 26 "printd", 27 "get_color", 28 "get_color_name", 29 "color_map", 30 "build_palette", 31 "build_lut", 32 "getColor", # deprecated will disappear 33 "colorMap", # deprecated 34 "buildLUT", # deprecated 35] 36 37 38try: 39 import matplotlib.cm as _cm_mpl 40 _has_matplotlib = True 41 cmaps = {} 42except ModuleNotFoundError: 43 from vedo.cmaps import cmaps 44 _has_matplotlib = False 45 # see below, this is dealt with in color_map() 46 47######################################################### 48# handy global shortcuts for terminal printing 49# Ex.: print(colors.red + "hello" + colors.reset) 50######################################################### 51red = "\x1b[1m\x1b[31;1m" 52green = "\x1b[1m\x1b[32;1m" 53yellow = "\x1b[1m\x1b[33;1m" 54blue = "\x1b[1m\x1b[34;1m" 55reset = "\x1b[0m" 56 57 58######################################################### 59# basic color schemes 60######################################################### 61colors = { 62 # order kind of matters because of pyplot.plot() 63 "blue9": "#a8cbfe", # bootstrap5 colors 64 "blue8": "#81b4fe", 65 "blue7": "#5a9cfe", 66 "blue6": "#3485fd", 67 "blue5": "#0d6efd", 68 "blue4": "#0b5cd5", 69 "blue3": "#094bac", 70 "blue2": "#073984", 71 "blue1": "#05285b", 72 "indigo9": "#c8a9fa", 73 "indigo8": "#af83f8", 74 "indigo7": "#975cf6", 75 "indigo6": "#7e36f4", 76 "indigo5": "#6610f2", 77 "indigo4": "#560dcb", 78 "indigo3": "#450ba5", 79 "indigo2": "#35087e", 80 "indigo1": "#250657", 81 "purple9": "#cbbbe9", 82 "purple8": "#b49ddf", 83 "purple7": "#9d7ed5", 84 "purple6": "#8660cb", 85 "purple5": "#6f42c1", 86 "purple4": "#5d37a2", 87 "purple3": "#4b2d83", 88 "purple2": "#3a2264", 89 "purple1": "#281845", 90 "pink9": "#f0b6d3", 91 "pink8": "#ea95bf", 92 "pink7": "#e374ab", 93 "pink6": "#dd5498", 94 "pink5": "#d63384", 95 "pink4": "#b42b6f", 96 "pink3": "#92235a", 97 "pink2": "#6f1b45", 98 "pink1": "#4d1230", 99 "red9": "#f2b6bc", 100 "red8": "#ed969e", 101 "red7": "#e77681", 102 "red6": "#e25563", 103 "red5": "#dc3545", 104 "red4": "#b92d3a", 105 "red3": "#96242f", 106 "red2": "#721c24", 107 "red1": "#4f1319", 108 "orange9": "#fed1aa", 109 "orange8": "#febc85", 110 "orange7": "#fea75f", 111 "orange6": "#fd933a", 112 "orange5": "#fd7e14", 113 "orange4": "#d56a11", 114 "orange3": "#ac560e", 115 "orange2": "#84420a", 116 "orange1": "#5b2d07", 117 "yellow9": "#ffe9a6", 118 "yellow8": "#ffdf7e", 119 "yellow7": "#ffd556", 120 "yellow6": "#ffcb2f", 121 "yellow5": "#ffc107", 122 "yellow4": "#d6a206", 123 "yellow3": "#ad8305", 124 "yellow2": "#856404", 125 "yellow1": "#5c4503", 126 "green9": "#b2dfbc", 127 "green8": "#8fd19e", 128 "green7": "#6dc381", 129 "green6": "#4ab563", 130 "green5": "#28a745", 131 "green4": "#228c3a", 132 "green3": "#1b722f", 133 "green2": "#155724", 134 "green1": "#0e3c19", 135 "teal9": "#afecda", 136 "teal8": "#8be3c9", 137 "teal7": "#67dab8", 138 "teal6": "#44d2a8", 139 "teal5": "#20c997", 140 "teal4": "#1ba97f", 141 "teal3": "#168967", 142 "teal2": "#11694f", 143 "teal1": "#0c4836", 144 "cyan9": "#abdee5", 145 "cyan8": "#86cfda", 146 "cyan7": "#61c0cf", 147 "cyan6": "#3cb1c3", 148 "cyan5": "#17a2b8", 149 "cyan4": "#13889b", 150 "cyan3": "#106e7d", 151 "cyan2": "#0c5460", 152 "cyan1": "#083a42", 153 "gray9": "#f8f9fa", 154 "gray8": "#e9edef", 155 "gray7": "#dee2e6", 156 "gray6": "#ced4da", 157 "gray5": "#adb5bd", 158 "gray4": "#6c757d", 159 "gray3": "#495057", 160 "gray2": "#343a40", 161 "gray1": "#212529", 162 "aliceblue": "#F0F8FF", # matplotlib scheme 163 "antiquewhite": "#FAEBD7", 164 "aqua": "#00FFFF", 165 "aquamarine": "#7FFFD4", 166 "azure": "#F0FFFF", 167 "beige": "#F5F5DC", 168 "bisque": "#FFE4C4", 169 "black": "#000000", 170 "blanchedalmond": "#FFEBCD", 171 "blue": "#0f00fb", # "0000FF", 172 "blueviolet": "#8A2BE2", 173 "brown": "#A52A2A", 174 "burlywood": "#DEB887", 175 "cadetblue": "#5F9EA0", 176 "chartreuse": "#7FFF00", 177 "chocolate": "#D2691E", 178 "coral": "#FF7F50", 179 "cornflowerblue": "#6495ED", 180 "cornsilk": "#FFF8DC", 181 "crimson": "#DC143C", 182 "cyan": "#00FFFF", 183 "darkblue": "#00008B", 184 "darkcyan": "#008B8B", 185 "darkgoldenrod": "#B8860B", 186 "darkgray": "#A9A9A9", 187 "darkgreen": "#006400", 188 "darkkhaki": "#BDB76B", 189 "darkmagenta": "#8B008B", 190 "darkolivegreen": "#556B2F", 191 "darkorange": "#FF8C00", 192 "darkorchid": "#9932CC", 193 "darkred": "#8B0000", 194 "darksalmon": "#E9967A", 195 "darkseagreen": "#8FBC8F", 196 "darkslateblue": "#483D8B", 197 "darkslategray": "#2F4F4F", 198 "darkturquoise": "#00CED1", 199 "darkviolet": "#9400D3", 200 "deeppink": "#FF1493", 201 "deepskyblue": "#00BFFF", 202 "dimgray": "#696969", 203 "dodgerblue": "#1E90FF", 204 "firebrick": "#B22222", 205 "floralwhite": "#FFFAF0", 206 "forestgreen": "#228B22", 207 "fuchsia": "#FF00FF", 208 "gainsboro": "#DCDCDC", 209 "ghostwhite": "#F8F8FF", 210 "gold": "#FFD700", 211 "goldenrod": "#DAA520", 212 "gray": "#808080", 213 "green": "#047f10", # "#008000", 214 "greenyellow": "#ADFF2F", 215 "honeydew": "#F0FFF0", 216 "hotpink": "#FF69B4", 217 "indianred": "#CD5C5C", 218 "indigo": "#4B0082", 219 "ivory": "#FFFFF0", 220 "khaki": "#F0E68C", 221 "lavender": "#E6E6FA", 222 "lavenderblush": "#FFF0F5", 223 "lawngreen": "#7CFC00", 224 "lemonchiffon": "#FFFACD", 225 "lightblue": "#ADD8E6", 226 "lightcoral": "#F08080", 227 "lightcyan": "#E0FFFF", 228 "lightgray": "#D3D3D3", 229 "lightgreen": "#90EE90", 230 "lightpink": "#FFB6C1", 231 "lightsalmon": "#FFA07A", 232 "lightseagreen": "#20B2AA", 233 "lightskyblue": "#87CEFA", 234 "lightsteelblue": "#B0C4DE", 235 "lightyellow": "#FFFFE0", 236 "lime": "#00FF00", 237 "limegreen": "#32CD32", 238 "linen": "#FAF0E6", 239 "magenta": "#FF00FF", 240 "maroon": "#800000", 241 "mediumaquamarine": "#66CDAA", 242 "mediumblue": "#0000CD", 243 "mediumorchid": "#BA55D3", 244 "mediumpurple": "#9370DB", 245 "mediumseagreen": "#3CB371", 246 "mediumslateblue": "#7B68EE", 247 "mediumspringgreen": "#00FA9A", 248 "mediumturquoise": "#48D1CC", 249 "mediumvioletred": "#C71585", 250 "midnightblue": "#191970", 251 "mintcream": "#F5FFFA", 252 "mistyrose": "#FFE4E1", 253 "moccasin": "#FFE4B5", 254 "navajowhite": "#FFDEAD", 255 "navy": "#000080", 256 "oldlace": "#FDF5E6", 257 "olive": "#808000", 258 "olivedrab": "#6B8E23", 259 "orange": "#FFA500", 260 "orangered": "#FF4500", 261 "orchid": "#DA70D6", 262 "palegoldenrod": "#EEE8AA", 263 "palegreen": "#98FB98", 264 "paleturquoise": "#AFEEEE", 265 "palevioletred": "#DB7093", 266 "papayawhip": "#FFEFD5", 267 "peachpuff": "#FFDAB9", 268 "peru": "#CD853F", 269 "pink": "#FFC0CB", 270 "plum": "#DDA0DD", 271 "powderblue": "#B0E0E6", 272 "purple": "#800080", 273 "rebeccapurple": "#663399", 274 "red": "#fe1e1f", # "#FF0000", 275 "rosybrown": "#BC8F8F", 276 "royalblue": "#4169E1", 277 "saddlebrown": "#8B4513", 278 "salmon": "#FA8072", 279 "sandybrown": "#F4A460", 280 "seagreen": "#2E8B57", 281 "seashell": "#FFF5EE", 282 "sienna": "#A0522D", 283 "silver": "#C0C0C0", 284 "skyblue": "#87CEEB", 285 "slateblue": "#6A5ACD", 286 "slategray": "#708090", 287 "snow": "#FFFAFA", 288 "blackboard": "#393939", 289 "springgreen": "#00FF7F", 290 "steelblue": "#4682B4", 291 "tan": "#D2B48C", 292 "teal": "#008080", 293 "thistle": "#D8BFD8", 294 "tomato": "#FF6347", 295 "turquoise": "#40E0D0", 296 "violet": "#EE82EE", 297 "wheat": "#F5DEB3", 298 "white": "#FFFFFF", 299 "whitesmoke": "#F5F5F5", 300 "yellow": "#ffff36", # "#FFFF00", 301 "yellowgreen": "#9ACD32", 302} 303 304 305color_nicks = { # color nicknames 306 "bb": "blackboard", 307 "lb": "lightblue", # light 308 "lg": "lightgreen", 309 "lr": "orangered", 310 "lc": "lightcyan", 311 "ls": "lightsalmon", 312 "ly": "lightyellow", 313 "dr": "darkred", # dark 314 "db": "darkblue", 315 "dg": "darkgreen", 316 "dm": "darkmagenta", 317 "dc": "darkcyan", 318 "ds": "darksalmon", 319 "dv": "darkviolet", 320 "b1": "blue1", # bootstrap5 colors 321 "b2": "blue2", 322 "b3": "blue3", 323 "b4": "blue4", 324 "b5": "blue5", 325 "b6": "blue6", 326 "b7": "blue7", 327 "b8": "blue8", 328 "b9": "blue9", 329 "i1": "indigo1", 330 "i2": "indigo2", 331 "i3": "indigo3", 332 "i4": "indigo4", 333 "i5": "indigo5", 334 "i6": "indigo6", 335 "i7": "indigo7", 336 "i8": "indigo8", 337 "i9": "indigo9", 338 "p1": "purple1", 339 "p2": "purple2", 340 "p3": "purple3", 341 "p4": "purple4", 342 "p5": "purple5", 343 "p6": "purple6", 344 "p7": "purple7", 345 "p8": "purple8", 346 "p9": "purple9", 347 "r1": "red1", 348 "r2": "red2", 349 "r3": "red3", 350 "r4": "red4", 351 "r5": "red5", 352 "r6": "red6", 353 "r7": "red7", 354 "r8": "red8", 355 "r9": "red9", 356 "o1": "orange1", 357 "o2": "orange2", 358 "o3": "orange3", 359 "o4": "orange4", 360 "o5": "orange5", 361 "o6": "orange6", 362 "o7": "orange7", 363 "o8": "orange8", 364 "o9": "orange9", 365 "y1": "yellow1", 366 "y2": "yellow2", 367 "y3": "yellow3", 368 "y4": "yellow4", 369 "y5": "yellow5", 370 "y6": "yellow6", 371 "y7": "yellow7", 372 "y8": "yellow8", 373 "y9": "yellow9", 374 "g1": "green1", 375 "g2": "green2", 376 "g3": "green3", 377 "g4": "green4", 378 "g5": "green5", 379 "g6": "green6", 380 "g7": "green7", 381 "g8": "green8", 382 "g9": "green9", 383 "k1": "gray1", 384 "k2": "gray2", 385 "k3": "gray3", 386 "k4": "gray4", 387 "k5": "gray5", 388 "k6": "gray6", 389 "k7": "gray7", 390 "k8": "gray8", 391 "k9": "gray9", 392 "a": "aqua", 393 "b": "blue", 394 "c": "cyan", 395 "d": "gold", 396 "f": "fuchsia", 397 "g": "green", 398 "i": "indigo", 399 "k": "black", 400 "m": "magenta", 401 "n": "navy", 402 "l": "lavender", 403 "o": "orange", 404 "p": "purple", 405 "r": "red", 406 "s": "salmon", 407 "t": "tomato", 408 "v": "violet", 409 "y": "yellow", 410 "w": "white", 411} 412 413 414# available colormap names: 415cmaps_names = ( 416 "Accent", "Accent_r", "Blues", "Blues_r", 417 "BrBG", "BrBG_r", "BuGn", "BuGn_r", 418 "BuPu", "BuPu_r", "CMRmap", "CMRmap_r", 419 "Dark2", "Dark2_r", "GnBu", "GnBu_r", 420 "Greens", "Greens_r", "Greys", "Greys_r", 421 "OrRd", "OrRd_r", "Oranges", "Oranges_r", 422 "PRGn", "PRGn_r", "Paired", "Paired_r", 423 "Pastel1", "Pastel1_r", "Pastel2", "Pastel2_r", 424 "PiYG", "PiYG_r", "PuBu", "PuBuGn", 425 "PuBuGn_r", "PuBu_r", "PuOr", "PuOr_r", 426 "PuRd", "PuRd_r", "Purples", "Purples_r", 427 "RdBu", "RdBu_r", "RdGy", "RdGy_r", 428 "RdPu", "RdPu_r", "RdYlBu", "RdYlBu_r", 429 "RdYlGn", "RdYlGn_r", "Reds", "Reds_r", 430 "Set1", "Set1_r", "Set2", "Set2_r", 431 "Set3", "Set3_r", "Spectral", "Spectral_r", 432 "Wistia", "Wistia_r", "YlGn", "YlGnBu", 433 "YlGnBu_r", "YlGn_r", "YlOrBr", "YlOrBr_r", 434 "YlOrRd", "YlOrRd_r", "afmhot", "afmhot_r", 435 "autumn", "autumn_r", "binary", "binary_r", 436 "bone", "bone_r", "brg", "brg_r", 437 "bwr", "bwr_r", "cividis", "cividis_r", 438 "cool", "cool_r", "coolwarm", "coolwarm_r", 439 "copper", "copper_r", "cubehelix", "cubehelix_r", 440 "flag", "flag_r", "gist_earth","gist_earth_r", 441 "gist_gray", "gist_gray_r", "gist_heat", "gist_heat_r", 442 "gist_ncar", "gist_ncar_r", "gist_rainbow", "gist_rainbow_r", 443 "gist_stern","gist_stern_r","gist_yarg", "gist_yarg_r", 444 "gnuplot", "gnuplot2", "gnuplot2_r", "gnuplot_r", 445 "gray_r", "hot", "hot_r", 446 "hsv", "hsv_r", "inferno", "inferno_r", 447 "jet", "jet_r", "magma", "magma_r", 448 "nipy_spectral", "nipy_spectral_r", "ocean", "ocean_r", 449 "pink_r", "plasma", "plasma_r", 450 "prism", "prism_r", "rainbow", "rainbow_r", 451 "seismic", "seismic_r", "spring", "spring_r", 452 "summer", "summer_r", "tab10", "tab10_r", 453 "tab20", "tab20_r", "tab20b", "tab20b_r", 454 "tab20c", "tab20c_r", "terrain", "terrain_r", 455 "twilight", "twilight_r", "twilight_shifted", "twilight_shifted_r", 456 "viridis", "viridis_r", "winter", "winter_r" 457) 458 459 460# default color palettes when using an index 461palettes = ( 462 ( 463 (1.0, 0.832, 0.000), # gold 464 (0.960, 0.509, 0.188), 465 (0.901, 0.098, 0.194), 466 (0.235, 0.85, 0.294), 467 (0.46, 0.48, 0.000), 468 (0.274, 0.941, 0.941), 469 (0.0, 0.509, 0.784), 470 (0.1, 0.1, 0.900), 471 (0.902, 0.7, 1.000), 472 (0.941, 0.196, 0.901), 473 ), 474 ( 475 (1.0, 0.832, 0), # gold 476 (0.59, 0.0, 0.09), # dark red 477 (0.5, 0.5, 0), # yellow-green 478 (0.0, 0.66, 0.42), # green blue 479 (0.5, 1.0, 0.0), # green 480 (0.0, 0.18, 0.65), # blue 481 (0.4, 0.0, 0.4), # plum 482 (0.4, 0.0, 0.6), 483 (0.2, 0.4, 0.6), 484 (0.1, 0.3, 0.2), 485 ), 486 ( 487 (0.010, 0.0706, 0.098), # -> black 488 (0.0196, 0.369, 0.447), 489 (0.0745, 0.573, 0.584), 490 (0.584, 0.820, 0.741), 491 (0.914, 0.847, 0.663), 492 (0.929, 0.616, 0.149), 493 (0.788, 0.412, 0.110), 494 (0.729, 0.259, 0.0902), 495 (0.678, 0.153, 0.110), 496 (0.604, 0.153, 0.165), # -> red3 497 ), 498 ( 499 (0.345, 0.188, 0.071), # -> orange1 500 (0.498, 0.314, 0.161), 501 (0.573, 0.404, 0.239), 502 (0.651, 0.545, 0.400), 503 (0.714, 0.678, 0.569), 504 (0.761, 0.773, 0.671), 505 (0.643, 0.675, 0.533), 506 (0.396, 0.427, 0.298), 507 (0.255, 0.282, 0.204), 508 (0.200, 0.239, 0.165), # -> blackboard 509 ), 510 ( 511 (0.937, 0.969, 0.820), # -> beige 512 (0.729, 0.851, 0.714), 513 (0.671, 0.639, 0.396), 514 (0.447, 0.180, 0.180), 515 (0.259, 0.055, 0.082), # -> red1 516 (0.937, 0.969, 0.820), # -> beige 517 (0.729, 0.851, 0.714), 518 (0.671, 0.639, 0.396), 519 (0.447, 0.180, 0.180), 520 (0.259, 0.055, 0.082), # -> red1 521 ), 522 ( 523 (0.933, 0.298, 0.443), # -> red6 524 (0.996, 0.824, 0.431), 525 (0.082, 0.835, 0.631), 526 (0.094, 0.537, 0.690), 527 (0.035, 0.231, 0.294), # -> cyan1 528 (0.933, 0.298, 0.443), # -> red6 529 (0.996, 0.824, 0.431), 530 (0.082, 0.835, 0.631), 531 (0.094, 0.537, 0.690), 532 (0.035, 0.231, 0.294), # -> cyan1 533 ), 534) 535 536 537emoji = { 538 r"\bomb": "\U0001F4A5", 539 r"\sparks": "\U00002728", 540 r"\ethumbup": "\U0001F44d", 541 r"\etarget": "\U0001F3af", 542 r"\save": "\U0001F4be", 543 r"\noentry": "\U000026d4", 544 r"\video": "\U0001F4fd ", 545 r"\lightning": "\U000026a1", 546 r"\camera": "\U0001F4f8", 547 r"\times": "\U0000274c", 548 r"\world": "\U0001F30d", 549 r"\erainbow": "\U0001F308", 550 r"\idea": "\U0001F4a1", 551 r"\pin": "\U0001F4CC", 552 r"\construction": "\U0001F6A7", 553 r"\rightarrow": "\U000027a1", 554 r"\erocket": "\U0001F680", 555 r"\hourglass": "\U000023f3", 556 r"\prohibited": "\U0001F6ab", 557 r"\checked": "\U00002705", 558 r"\smile": "\U0001F642", 559 r"\sad": "\U0001F612", 560 r"\star": "\U00002B50", 561 r"\zzz": "\U0001F4a4", 562 r"\mu": "\U000003BC", 563 r"\pi": "\U000003C0", 564 r"\sigma": "\U000003C3", 565} 566 567 568# terminal color print 569def _has_colors(stream): 570 if not hasattr(stream, "isatty"): 571 return False 572 if not stream.isatty(): 573 return False 574 return True 575_terminal_has_colors = _has_colors(sys.stdout) 576 577 578def _is_sequence(arg): 579 # Check if input is iterable. 580 if hasattr(arg, "strip"): 581 return False 582 if hasattr(arg, "__getslice__"): 583 return True 584 if hasattr(arg, "__iter__"): 585 return True 586 return False 587 588 589def getColor(rgb=None, hsv=None): 590 """Deprecated. Use `get_color()`""" 591 return get_color(rgb, hsv) 592 593def get_color(rgb=None, hsv=None): 594 """ 595 Convert a color or list of colors to (r,g,b) format from many different input formats. 596 597 Set `hsv` to input as (hue, saturation, value). 598 599 Example: 600 - `RGB = (255, 255, 255)` corresponds to white 601 - `rgb = (1,1,1)` is again white 602 - `hex = #FFFF00` is yellow 603 - `string = 'white'` 604 - `string = 'w'` is white nickname 605 - `string = 'dr'` is darkred 606 - `string = 'red4'` is a shade of red 607 - `int = 7` picks color nr. 7 in a predefined color list 608 - `int = -7` picks color nr. 7 in a different predefined list 609 610 611 Examples: 612 - [colorcubes.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/colorcubes.py) 613 614  615 """ 616 # recursion, return a list if input is list of colors: 617 if _is_sequence(rgb) and (len(rgb) > 3 or _is_sequence(rgb[0])): 618 seqcol = [] 619 for sc in rgb: 620 seqcol.append(get_color(sc)) 621 return seqcol 622 623 # because they are most common: 624 if isinstance(rgb, str): 625 if rgb == "r": 626 return (0.9960784313725, 0.11764705882352, 0.121568627450980) 627 elif rgb == "g": 628 return (0.0156862745098, 0.49803921568627, 0.062745098039215) 629 elif rgb == "b": 630 return (0.0588235294117, 0.0, 0.984313725490196) 631 632 if str(rgb).isdigit(): 633 rgb = int(rgb) 634 635 if hsv: 636 c = hsv2rgb(hsv) 637 else: 638 c = rgb 639 640 if _is_sequence(c): 641 if c[0] <= 1 and c[1] <= 1 and c[2] <= 1: 642 return c # already rgb 643 if len(c) == 3: 644 return list(np.array(c) / 255.0) # RGB 645 return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3]) # RGBA 646 647 elif isinstance(c, str): # is string 648 c = c.replace("grey", "gray").replace(" ", "") 649 if 0 < len(c) < 3: # single/double letter color 650 if c.lower() in color_nicks: 651 c = color_nicks[c.lower()] 652 else: 653 vedo.logger.warning( 654 f"Unknown color nickname {c}\nAvailable abbreviations: {color_nicks}" 655 ) 656 return (0.5, 0.5, 0.5) 657 658 if c.lower() in colors: # matplotlib name color 659 c = colors[c.lower()] 660 # from now format is hex! 661 662 if c.startswith("#"): # hex to rgb 663 h = c.lstrip("#") 664 rgb255 = list(int(h[i : i + 2], 16) for i in (0, 2, 4)) 665 rgbh = np.array(rgb255) / 255.0 666 if np.sum(rgbh) > 3: 667 vedo.logger.error(f"in get_color(): Wrong hex color {c}") 668 return (0.5, 0.5, 0.5) 669 return tuple(rgbh) 670 671 else: # vtk name color 672 namedColors = vtk.vtkNamedColors() 673 rgba = [0, 0, 0, 0] 674 namedColors.GetColor(c, rgba) 675 return (rgba[0] / 255.0, rgba[1] / 255.0, rgba[2] / 255.0) 676 677 elif isinstance(c, (int, float)): # color number 678 return palettes[vedo.settings.palette % len(palettes)][abs(int(c)) % 10] 679 680 return (0.5, 0.5, 0.5) 681 682 683def get_color_name(c): 684 """Find the name of the closest color.""" 685 c = np.array(get_color(c)) # reformat to rgb 686 mdist = 99.0 687 kclosest = "" 688 for key in colors: 689 ci = np.array(get_color(key)) 690 d = np.linalg.norm(c - ci) 691 if d < mdist: 692 mdist = d 693 kclosest = str(key) 694 return kclosest 695 696def hsv2rgb(hsv): 697 """Convert HSV to RGB color.""" 698 ma = vtk.vtkMath() 699 rgb = [0, 0, 0] 700 ma.HSVToRGB(hsv, rgb) 701 return rgb 702 703 704def rgb2hsv(rgb): 705 """Convert RGB to HSV color.""" 706 ma = vtk.vtkMath() 707 hsv = [0, 0, 0] 708 ma.RGBToHSV(get_color(rgb), hsv) 709 return hsv 710 711 712def rgb2hex(rgb): 713 """Convert RGB to Hex color.""" 714 h = "#%02x%02x%02x" % (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)) 715 return h 716 717 718def hex2rgb(hx): 719 """Convert Hex to rgb color.""" 720 h = hx.lstrip("#") 721 rgb255 = [int(h[i : i + 2], 16) for i in (0, 2, 4)] 722 return (rgb255[0] / 255.0, rgb255[1] / 255.0, rgb255[2] / 255.0) 723 724 725def colorMap(value, name="jet", vmin=None, vmax=None): 726 """Deprecated, use `color_map()`""" 727 print("Deprecated call to colorMap(), use color_map() instead") 728 return color_map(value, name, vmin, vmax) 729 730def color_map(value, name="jet", vmin=None, vmax=None): 731 """ 732 Map a real value in range [vmin, vmax] to a (r,g,b) color scale. 733 734 Return the (r,g,b) color, or a list of (r,g,b) colors. 735 736 Arguments: 737 value : *(float, list)* 738 scalar value to transform into a color 739 name : *(str, matplotlib.colors.LinearSegmentedColormap)* 740 color map name 741 742 Very frequently used color maps are: 743 744  745 746 A more complete color maps list: 747 748  749 750 .. note:: Can also directly use and customize a matplotlib color map 751 752 Example: 753 ```python 754 from vedo import color_map 755 import matplotlib.cm as cm 756 print( color_map(0.2, cm.flag, 0, 1) ) 757 # (1.0, 0.809016994374948, 0.6173258487801733) 758 ``` 759 760 Examples: 761 - [plot_bars.py](https://github.com/marcomusy/vedo/tree/master/examples/pyplot/plot_bars.py) 762 763 <img src="https://vedo.embl.es/images/pyplot/plot_bars.png" width="400"/> 764 765 """ 766 cut = _is_sequence(value) # to speed up later 767 768 if cut: 769 values = np.asarray(value) 770 if vmin is None: vmin = np.min(values) 771 if vmax is None: vmax = np.max(values) 772 values = np.clip(values, vmin, vmax) 773 values = (values - vmin) / (vmax - vmin) 774 else: 775 if vmin is None: 776 vedo.logger.warning("in color_map() you must specify vmin! Assume 0.") 777 vmin = 0 778 if vmax is None: 779 vedo.logger.warning("in color_map() you must specify vmax! Assume 1.") 780 vmax = 1 781 values = [(value - vmin) / (vmax - vmin)] 782 783 if _has_matplotlib: 784 # matplotlib is available, use it! ########################### 785 if isinstance(name, str): 786 mp = _cm_mpl.get_cmap(name=name) 787 else: 788 mp = name # assume matplotlib.colors.LinearSegmentedColormap 789 result = mp(values)[:, [0, 1, 2]] 790 791 else: 792 # matplotlib not available ################################### 793 invert = False 794 if name.endswith("_r"): 795 invert = True 796 name = name.replace("_r", "") 797 try: 798 cmap = cmaps[name] 799 except KeyError: 800 vedo.logger.error(f"in color_map(), no color map with name {name} or {name}_r") 801 vedo.logger.error(f"Available color maps are:\n{cmaps.keys()}") 802 return np.array([0.5, 0.5, 0.5]) 803 804 result = [] 805 n = len(cmap) - 1 806 for v in values: 807 iv = int(v * n) 808 if invert: 809 iv = n - iv 810 rgb = hex2rgb(cmap[iv]) 811 result.append(rgb) 812 result = np.array(result) 813 814 if cut: 815 return result 816 return result[0] 817 818 819def build_palette(color1, color2, n, hsv=True): 820 """ 821 Generate N colors starting from `color1` to `color2` 822 by linear interpolation in HSV or RGB spaces. 823 824 Arguments: 825 N : (int) 826 number of output colors. 827 color1 : (color) 828 first color. 829 color2 : (color) 830 second color. 831 hsv : (bool) 832 if `False`, interpolation is calculated in RGB space. 833 834 Examples: 835 - [mesh_custom.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/mesh_custom.py) 836 837  838 """ 839 if hsv: 840 color1 = rgb2hsv(color1) 841 color2 = rgb2hsv(color2) 842 c1 = np.array(get_color(color1)) 843 c2 = np.array(get_color(color2)) 844 cols = [] 845 for f in np.linspace(0, 1, n, endpoint=True): 846 c = c1 * (1 - f) + c2 * f 847 if hsv: 848 c = np.array(hsv2rgb(c)) 849 cols.append(c) 850 return np.array(cols) 851 852def buildLUT( 853 colorlist, 854 vmin=None, 855 vmax=None, 856 belowColor=None, 857 aboveColor=None, 858 nanColor=None, 859 belowAlpha=1, 860 aboveAlpha=1, 861 nanAlpha=1, 862 interpolate=False, 863): 864 """Deprecated. Please use `build_lut()`""" 865 print("Deprecated call to buildLUT(). Please use build_lut() instead") 866 return build_lut( 867 colorlist, 868 vmin, 869 vmax, 870 belowColor, 871 aboveColor, 872 nanColor, 873 belowAlpha, 874 aboveAlpha, 875 nanAlpha, 876 interpolate, 877 ) 878 879def build_lut( 880 colorlist, 881 vmin=None, 882 vmax=None, 883 below_color=None, 884 above_color=None, 885 nan_color=None, 886 below_alpha=1, 887 above_alpha=1, 888 nan_alpha=1, 889 interpolate=False, 890): 891 """ 892 Generate colors in a lookup table (LUT). 893 894 Return the `vtkLookupTable` object. This can be fed into `cmap()` method. 895 896 Arguments: 897 colorlist : (list) 898 a list in the form `[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]`. 899 vmin : (float) 900 specify minimum value of scalar range 901 vmax : (float) 902 specify maximum value of scalar range 903 below_color : (color) 904 color for scalars below the minimum in range 905 below_alpha : (float) 906 opacity for scalars below the minimum in range 907 above_color : (color) 908 color for scalars above the maximum in range 909 above_alpha : (float) 910 alpha for scalars above the maximum in range 911 nan_color : (color) 912 color for invalid (nan) scalars 913 nan_alpha : (float) 914 alpha for invalid (nan) scalars 915 interpolate : (bool) 916 interpolate or not intermediate scalars 917 918 Examples: 919 - [mesh_lut.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/mesh_lut.py) 920 921  922 """ 923 ctf = vtk.vtkColorTransferFunction() 924 ctf.SetColorSpaceToRGB() 925 ctf.SetScaleToLinear() 926 alpha_x, alpha_vals = [], [] 927 for sc in colorlist: 928 if len(sc) >= 3: 929 scalar, col, alf = sc[:3] 930 else: 931 alf = 1 932 scalar, col = sc 933 r, g, b = get_color(col) 934 ctf.AddRGBPoint(scalar, r, g, b) 935 alpha_x.append(scalar) 936 alpha_vals.append(alf) 937 938 lut = vtk.vtkLookupTable() 939 lut.SetNumberOfTableValues(256) 940 941 x0, x1 = ctf.GetRange() # range of the introduced values 942 if vmin is not None: 943 x0 = vmin 944 if vmax is not None: 945 x1 = vmax 946 ctf.SetRange(x0, x1) 947 lut.SetRange(x0, x1) 948 949 if below_color is not None: 950 lut.SetBelowRangeColor(list(get_color(below_color)) + [below_alpha]) 951 lut.SetUseBelowRangeColor(True) 952 if above_color is not None: 953 lut.SetAboveRangeColor(list(get_color(above_color)) + [above_alpha]) 954 lut.SetUseAboveRangeColor(True) 955 if nan_color is not None: 956 lut.SetNanColor(list(get_color(nan_color)) + [nan_alpha]) 957 958 rgba = (1, 1, 1, 1) 959 for i in range(256): 960 p = i / 255 961 x = (1 - p) * x0 + p * x1 962 if interpolate: 963 alf = np.interp(x, alpha_x, alpha_vals) 964 rgba = list(ctf.GetColor(x)) + [alf] 965 else: 966 for c in colorlist: 967 if x <= c[0]: 968 if len(c) == 3: 969 alf = c[2] 970 else: 971 alf = 1 972 rgba = list(get_color(c[1])) + [alf] 973 break 974 lut.SetTableValue(i, rgba) 975 976 lut.Build() 977 return lut 978 979 980######################################################################### 981def printc( 982 *strings, 983 c=None, 984 bc=None, 985 bold=True, 986 italic=False, 987 blink=False, 988 underline=False, 989 strike=False, 990 dim=False, 991 invert=False, 992 box="", 993 end="\n", 994 flush=True, 995): 996 """ 997 Print to terminal in color (any color!). 998 999 Arguments: 1000 c : (color) 1001 foreground color name or (r,g,b) 1002 bc : (color) 1003 background color name or (r,g,b) 1004 bold : (bool) 1005 boldface [True] 1006 italic : (bool) 1007 italic [False] 1008 blink : (bool) 1009 blinking text [False] 1010 underline : (bool) 1011 underline text [False] 1012 strike : (bool) 1013 strike through text [False] 1014 dim : (bool) 1015 make text look dimmer [False] 1016 invert : (bool) 1017 invert background and forward colors [False] 1018 box : (bool) 1019 print a box with specified text character [''] 1020 flush : (bool) 1021 flush buffer after printing [True] 1022 end : (str) 1023 the end character to be printed [newline] 1024 1025 Example: 1026 ```python 1027 from vedo.colors import printc 1028 printc('anything', c='tomato', bold=False, end=' ') 1029 printc('anything', 455.5, c='lightblue') 1030 printc(299792.48, c=4) 1031 ``` 1032 1033 Examples: 1034 - [printc.py](https://github.com/marcomusy/vedo/tree/master/examples/other/printc.py) 1035 1036  1037 """ 1038 if not vedo.settings.enable_print_color: 1039 print(*strings, end=end, flush=flush) 1040 return 1041 1042 if not vedo.notebook_backend: 1043 if not _terminal_has_colors: 1044 print(*strings, end=end, flush=flush) 1045 return 1046 1047 try: # ------------------------------------------------------------- 1048 1049 txt = str() 1050 ns = len(strings) - 1 1051 separator = " " 1052 offset = 0 1053 for i, s in enumerate(strings): 1054 if i == ns: 1055 separator = "" 1056 if "\\" in repr(s): # "in" for some reasons changes s 1057 for k in emoji: 1058 if k in str(s): 1059 s = s.replace(k, emoji[k]) 1060 offset += 1 1061 for k, rp in vedo.shapes._reps: # check symbols in shapes._reps 1062 if k in str(s): 1063 s = s.replace(k, rp) 1064 offset += 1 1065 1066 txt += str(s) + separator 1067 1068 special, cseq = "", "" 1069 oneletter_colors = { 1070 "k": "\u001b[30m", # because these are supported by most terminals 1071 "r": "\u001b[31m", 1072 "g": "\u001b[32m", 1073 "y": "\u001b[33m", 1074 "b": "\u001b[34m", 1075 "m": "\u001b[35m", 1076 "c": "\u001b[36m", 1077 "w": "\u001b[37m", 1078 } 1079 1080 if c is not None: 1081 if c is True: 1082 c = "g" 1083 elif c is False: 1084 c = "r" 1085 1086 if isinstance(c, str) and c in oneletter_colors: 1087 cseq += oneletter_colors[c] 1088 else: 1089 r, g, b = get_color(c) # not all terms support this syntax 1090 cseq += f"\x1b[38;2;{int(r*255)};{int(g*255)};{int(b*255)}m" 1091 1092 if bc: 1093 if bc in oneletter_colors: 1094 cseq += oneletter_colors[bc] 1095 else: 1096 r, g, b = get_color(bc) 1097 cseq += f"\x1b[48;2;{int(r*255)};{int(g*255)};{int(b*255)}m" 1098 1099 if box is True: 1100 box = "-" 1101 if underline and not box: 1102 special += "\x1b[4m" 1103 if strike and not box: 1104 special += "\x1b[9m" 1105 if dim: 1106 special += "\x1b[2m" 1107 if invert: 1108 special += "\x1b[7m" 1109 if bold: 1110 special += "\x1b[1m" 1111 if italic: 1112 special += "\x1b[3m" 1113 if blink: 1114 special += "\x1b[5m" 1115 1116 if box and "\n" not in txt: 1117 box = box[0] 1118 boxv = box 1119 if box in ["_", "=", "-", "+", "~"]: 1120 boxv = "|" 1121 1122 if box in ('_', '.'): 1123 outtxt = special + cseq + " " + box * (len(txt) + offset + 2) + " \n" 1124 outtxt += boxv + " " * (len(txt) + 2) + boxv + "\n" 1125 else: 1126 outtxt = special + cseq + box * (len(txt) + offset + 4) + "\n" 1127 1128 outtxt += boxv + " " + txt + " " + boxv + "\n" 1129 1130 if box == "_": 1131 outtxt += "|" + box * (len(txt) + offset + 2) + "|" + reset + end 1132 else: 1133 outtxt += box * (len(txt) + offset + 4) + reset + end 1134 1135 sys.stdout.write(outtxt) 1136 1137 else: 1138 1139 out = special + cseq + txt + reset 1140 sys.stdout.write(out + end) 1141 1142 except: # ------------------------------------------------------------- fallback 1143 1144 try: 1145 print(*strings, end=end) 1146 except UnicodeEncodeError as e: 1147 print(e, end=end) 1148 pass 1149 1150 if flush: 1151 sys.stdout.flush() 1152 1153 1154def printd(*strings, q=False): 1155 """ 1156 Print debug information about the environment where the printd() is called. 1157 Local variables are printed out with their current values. 1158 1159 Use `q` to quit (exit) python session after the printd call. 1160 """ 1161 from inspect import currentframe, getframeinfo 1162 1163 cf = currentframe().f_back 1164 cfi = getframeinfo(cf) 1165 1166 fname = os.path.basename(getframeinfo(cf).filename) 1167 print("\x1b[7m\x1b[3m\x1b[37m"+fname+" line:\x1b[1m"+str(cfi.lineno)+reset, end='') 1168 print('\x1b[3m\x1b[37m\x1b[2m', "\U00002501"*30, time.ctime(), reset) 1169 if strings: 1170 print(" \x1b[37m\x1b[1mMessage : ", *strings) 1171 print(" \x1b[37m\x1b[1mFunction:\x1b[0m\x1b[37m " + str(cfi.function)) 1172 print(" \x1b[1mLocals :" + reset) 1173 for loc in cf.f_locals.keys(): 1174 obj = cf.f_locals[loc] 1175 var = repr(obj) 1176 if 'module ' in var: continue 1177 if 'function ' in var: continue 1178 if 'class ' in var: continue 1179 if loc.startswith('_'): continue 1180 if hasattr(obj, 'name'): 1181 if not obj.name: 1182 oname = str(type(obj)) 1183 else: 1184 oname = obj.name 1185 var = oname + ", at " + vedo.utils.precision(obj.GetPosition(), 3) 1186 1187 var = var.replace("vtkmodules.", "") 1188 print(" \x1b[37m", loc, "\t\t=", var[:60].replace("\n", ""), reset) 1189 if vedo.utils.is_sequence(obj) and len(obj) > 4: 1190 print(' \x1b[37m\x1b[2m\x1b[3m len:', len(obj), 1191 ' min:', vedo.utils.precision(min(obj), 4), 1192 ' max:', vedo.utils.precision(max(obj), 4), 1193 reset) 1194 1195 if q: 1196 print(f" \x1b[1m\x1b[37mExiting python now (q={bool(q)}).\x1b[0m\x1b[37m") 1197 sys.exit(0) 1198 sys.stdout.flush()
982def printc( 983 *strings, 984 c=None, 985 bc=None, 986 bold=True, 987 italic=False, 988 blink=False, 989 underline=False, 990 strike=False, 991 dim=False, 992 invert=False, 993 box="", 994 end="\n", 995 flush=True, 996): 997 """ 998 Print to terminal in color (any color!). 999 1000 Arguments: 1001 c : (color) 1002 foreground color name or (r,g,b) 1003 bc : (color) 1004 background color name or (r,g,b) 1005 bold : (bool) 1006 boldface [True] 1007 italic : (bool) 1008 italic [False] 1009 blink : (bool) 1010 blinking text [False] 1011 underline : (bool) 1012 underline text [False] 1013 strike : (bool) 1014 strike through text [False] 1015 dim : (bool) 1016 make text look dimmer [False] 1017 invert : (bool) 1018 invert background and forward colors [False] 1019 box : (bool) 1020 print a box with specified text character [''] 1021 flush : (bool) 1022 flush buffer after printing [True] 1023 end : (str) 1024 the end character to be printed [newline] 1025 1026 Example: 1027 ```python 1028 from vedo.colors import printc 1029 printc('anything', c='tomato', bold=False, end=' ') 1030 printc('anything', 455.5, c='lightblue') 1031 printc(299792.48, c=4) 1032 ``` 1033 1034 Examples: 1035 - [printc.py](https://github.com/marcomusy/vedo/tree/master/examples/other/printc.py) 1036 1037  1038 """ 1039 if not vedo.settings.enable_print_color: 1040 print(*strings, end=end, flush=flush) 1041 return 1042 1043 if not vedo.notebook_backend: 1044 if not _terminal_has_colors: 1045 print(*strings, end=end, flush=flush) 1046 return 1047 1048 try: # ------------------------------------------------------------- 1049 1050 txt = str() 1051 ns = len(strings) - 1 1052 separator = " " 1053 offset = 0 1054 for i, s in enumerate(strings): 1055 if i == ns: 1056 separator = "" 1057 if "\\" in repr(s): # "in" for some reasons changes s 1058 for k in emoji: 1059 if k in str(s): 1060 s = s.replace(k, emoji[k]) 1061 offset += 1 1062 for k, rp in vedo.shapes._reps: # check symbols in shapes._reps 1063 if k in str(s): 1064 s = s.replace(k, rp) 1065 offset += 1 1066 1067 txt += str(s) + separator 1068 1069 special, cseq = "", "" 1070 oneletter_colors = { 1071 "k": "\u001b[30m", # because these are supported by most terminals 1072 "r": "\u001b[31m", 1073 "g": "\u001b[32m", 1074 "y": "\u001b[33m", 1075 "b": "\u001b[34m", 1076 "m": "\u001b[35m", 1077 "c": "\u001b[36m", 1078 "w": "\u001b[37m", 1079 } 1080 1081 if c is not None: 1082 if c is True: 1083 c = "g" 1084 elif c is False: 1085 c = "r" 1086 1087 if isinstance(c, str) and c in oneletter_colors: 1088 cseq += oneletter_colors[c] 1089 else: 1090 r, g, b = get_color(c) # not all terms support this syntax 1091 cseq += f"\x1b[38;2;{int(r*255)};{int(g*255)};{int(b*255)}m" 1092 1093 if bc: 1094 if bc in oneletter_colors: 1095 cseq += oneletter_colors[bc] 1096 else: 1097 r, g, b = get_color(bc) 1098 cseq += f"\x1b[48;2;{int(r*255)};{int(g*255)};{int(b*255)}m" 1099 1100 if box is True: 1101 box = "-" 1102 if underline and not box: 1103 special += "\x1b[4m" 1104 if strike and not box: 1105 special += "\x1b[9m" 1106 if dim: 1107 special += "\x1b[2m" 1108 if invert: 1109 special += "\x1b[7m" 1110 if bold: 1111 special += "\x1b[1m" 1112 if italic: 1113 special += "\x1b[3m" 1114 if blink: 1115 special += "\x1b[5m" 1116 1117 if box and "\n" not in txt: 1118 box = box[0] 1119 boxv = box 1120 if box in ["_", "=", "-", "+", "~"]: 1121 boxv = "|" 1122 1123 if box in ('_', '.'): 1124 outtxt = special + cseq + " " + box * (len(txt) + offset + 2) + " \n" 1125 outtxt += boxv + " " * (len(txt) + 2) + boxv + "\n" 1126 else: 1127 outtxt = special + cseq + box * (len(txt) + offset + 4) + "\n" 1128 1129 outtxt += boxv + " " + txt + " " + boxv + "\n" 1130 1131 if box == "_": 1132 outtxt += "|" + box * (len(txt) + offset + 2) + "|" + reset + end 1133 else: 1134 outtxt += box * (len(txt) + offset + 4) + reset + end 1135 1136 sys.stdout.write(outtxt) 1137 1138 else: 1139 1140 out = special + cseq + txt + reset 1141 sys.stdout.write(out + end) 1142 1143 except: # ------------------------------------------------------------- fallback 1144 1145 try: 1146 print(*strings, end=end) 1147 except UnicodeEncodeError as e: 1148 print(e, end=end) 1149 pass 1150 1151 if flush: 1152 sys.stdout.flush()
Print to terminal in color (any color!).
Arguments:
- c : (color) foreground color name or (r,g,b)
- bc : (color) background color name or (r,g,b)
- bold : (bool) boldface [True]
- italic : (bool) italic [False]
- blink : (bool) blinking text [False]
- underline : (bool) underline text [False]
- strike : (bool) strike through text [False]
- dim : (bool) make text look dimmer [False]
- invert : (bool) invert background and forward colors [False]
- box : (bool) print a box with specified text character ['']
- flush : (bool) flush buffer after printing [True]
- end : (str) the end character to be printed [newline]
Example:
from vedo.colors import printc printc('anything', c='tomato', bold=False, end=' ') printc('anything', 455.5, c='lightblue') printc(299792.48, c=4)
Examples:
1155def printd(*strings, q=False): 1156 """ 1157 Print debug information about the environment where the printd() is called. 1158 Local variables are printed out with their current values. 1159 1160 Use `q` to quit (exit) python session after the printd call. 1161 """ 1162 from inspect import currentframe, getframeinfo 1163 1164 cf = currentframe().f_back 1165 cfi = getframeinfo(cf) 1166 1167 fname = os.path.basename(getframeinfo(cf).filename) 1168 print("\x1b[7m\x1b[3m\x1b[37m"+fname+" line:\x1b[1m"+str(cfi.lineno)+reset, end='') 1169 print('\x1b[3m\x1b[37m\x1b[2m', "\U00002501"*30, time.ctime(), reset) 1170 if strings: 1171 print(" \x1b[37m\x1b[1mMessage : ", *strings) 1172 print(" \x1b[37m\x1b[1mFunction:\x1b[0m\x1b[37m " + str(cfi.function)) 1173 print(" \x1b[1mLocals :" + reset) 1174 for loc in cf.f_locals.keys(): 1175 obj = cf.f_locals[loc] 1176 var = repr(obj) 1177 if 'module ' in var: continue 1178 if 'function ' in var: continue 1179 if 'class ' in var: continue 1180 if loc.startswith('_'): continue 1181 if hasattr(obj, 'name'): 1182 if not obj.name: 1183 oname = str(type(obj)) 1184 else: 1185 oname = obj.name 1186 var = oname + ", at " + vedo.utils.precision(obj.GetPosition(), 3) 1187 1188 var = var.replace("vtkmodules.", "") 1189 print(" \x1b[37m", loc, "\t\t=", var[:60].replace("\n", ""), reset) 1190 if vedo.utils.is_sequence(obj) and len(obj) > 4: 1191 print(' \x1b[37m\x1b[2m\x1b[3m len:', len(obj), 1192 ' min:', vedo.utils.precision(min(obj), 4), 1193 ' max:', vedo.utils.precision(max(obj), 4), 1194 reset) 1195 1196 if q: 1197 print(f" \x1b[1m\x1b[37mExiting python now (q={bool(q)}).\x1b[0m\x1b[37m") 1198 sys.exit(0) 1199 sys.stdout.flush()
Print debug information about the environment where the printd() is called. Local variables are printed out with their current values.
Use q
to quit (exit) python session after the printd call.
594def get_color(rgb=None, hsv=None): 595 """ 596 Convert a color or list of colors to (r,g,b) format from many different input formats. 597 598 Set `hsv` to input as (hue, saturation, value). 599 600 Example: 601 - `RGB = (255, 255, 255)` corresponds to white 602 - `rgb = (1,1,1)` is again white 603 - `hex = #FFFF00` is yellow 604 - `string = 'white'` 605 - `string = 'w'` is white nickname 606 - `string = 'dr'` is darkred 607 - `string = 'red4'` is a shade of red 608 - `int = 7` picks color nr. 7 in a predefined color list 609 - `int = -7` picks color nr. 7 in a different predefined list 610 611 612 Examples: 613 - [colorcubes.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/colorcubes.py) 614 615  616 """ 617 # recursion, return a list if input is list of colors: 618 if _is_sequence(rgb) and (len(rgb) > 3 or _is_sequence(rgb[0])): 619 seqcol = [] 620 for sc in rgb: 621 seqcol.append(get_color(sc)) 622 return seqcol 623 624 # because they are most common: 625 if isinstance(rgb, str): 626 if rgb == "r": 627 return (0.9960784313725, 0.11764705882352, 0.121568627450980) 628 elif rgb == "g": 629 return (0.0156862745098, 0.49803921568627, 0.062745098039215) 630 elif rgb == "b": 631 return (0.0588235294117, 0.0, 0.984313725490196) 632 633 if str(rgb).isdigit(): 634 rgb = int(rgb) 635 636 if hsv: 637 c = hsv2rgb(hsv) 638 else: 639 c = rgb 640 641 if _is_sequence(c): 642 if c[0] <= 1 and c[1] <= 1 and c[2] <= 1: 643 return c # already rgb 644 if len(c) == 3: 645 return list(np.array(c) / 255.0) # RGB 646 return (c[0] / 255.0, c[1] / 255.0, c[2] / 255.0, c[3]) # RGBA 647 648 elif isinstance(c, str): # is string 649 c = c.replace("grey", "gray").replace(" ", "") 650 if 0 < len(c) < 3: # single/double letter color 651 if c.lower() in color_nicks: 652 c = color_nicks[c.lower()] 653 else: 654 vedo.logger.warning( 655 f"Unknown color nickname {c}\nAvailable abbreviations: {color_nicks}" 656 ) 657 return (0.5, 0.5, 0.5) 658 659 if c.lower() in colors: # matplotlib name color 660 c = colors[c.lower()] 661 # from now format is hex! 662 663 if c.startswith("#"): # hex to rgb 664 h = c.lstrip("#") 665 rgb255 = list(int(h[i : i + 2], 16) for i in (0, 2, 4)) 666 rgbh = np.array(rgb255) / 255.0 667 if np.sum(rgbh) > 3: 668 vedo.logger.error(f"in get_color(): Wrong hex color {c}") 669 return (0.5, 0.5, 0.5) 670 return tuple(rgbh) 671 672 else: # vtk name color 673 namedColors = vtk.vtkNamedColors() 674 rgba = [0, 0, 0, 0] 675 namedColors.GetColor(c, rgba) 676 return (rgba[0] / 255.0, rgba[1] / 255.0, rgba[2] / 255.0) 677 678 elif isinstance(c, (int, float)): # color number 679 return palettes[vedo.settings.palette % len(palettes)][abs(int(c)) % 10] 680 681 return (0.5, 0.5, 0.5)
Convert a color or list of colors to (r,g,b) format from many different input formats.
Set hsv
to input as (hue, saturation, value).
Example:
RGB = (255, 255, 255)
corresponds to whitergb = (1,1,1)
is again whitehex = #FFFF00
is yellowstring = 'white'
string = 'w'
is white nicknamestring = 'dr'
is darkredstring = 'red4'
is a shade of redint = 7
picks color nr. 7 in a predefined color listint = -7
picks color nr. 7 in a different predefined list
Examples:
684def get_color_name(c): 685 """Find the name of the closest color.""" 686 c = np.array(get_color(c)) # reformat to rgb 687 mdist = 99.0 688 kclosest = "" 689 for key in colors: 690 ci = np.array(get_color(key)) 691 d = np.linalg.norm(c - ci) 692 if d < mdist: 693 mdist = d 694 kclosest = str(key) 695 return kclosest
Find the name of the closest color.
731def color_map(value, name="jet", vmin=None, vmax=None): 732 """ 733 Map a real value in range [vmin, vmax] to a (r,g,b) color scale. 734 735 Return the (r,g,b) color, or a list of (r,g,b) colors. 736 737 Arguments: 738 value : *(float, list)* 739 scalar value to transform into a color 740 name : *(str, matplotlib.colors.LinearSegmentedColormap)* 741 color map name 742 743 Very frequently used color maps are: 744 745  746 747 A more complete color maps list: 748 749  750 751 .. note:: Can also directly use and customize a matplotlib color map 752 753 Example: 754 ```python 755 from vedo import color_map 756 import matplotlib.cm as cm 757 print( color_map(0.2, cm.flag, 0, 1) ) 758 # (1.0, 0.809016994374948, 0.6173258487801733) 759 ``` 760 761 Examples: 762 - [plot_bars.py](https://github.com/marcomusy/vedo/tree/master/examples/pyplot/plot_bars.py) 763 764 <img src="https://vedo.embl.es/images/pyplot/plot_bars.png" width="400"/> 765 766 """ 767 cut = _is_sequence(value) # to speed up later 768 769 if cut: 770 values = np.asarray(value) 771 if vmin is None: vmin = np.min(values) 772 if vmax is None: vmax = np.max(values) 773 values = np.clip(values, vmin, vmax) 774 values = (values - vmin) / (vmax - vmin) 775 else: 776 if vmin is None: 777 vedo.logger.warning("in color_map() you must specify vmin! Assume 0.") 778 vmin = 0 779 if vmax is None: 780 vedo.logger.warning("in color_map() you must specify vmax! Assume 1.") 781 vmax = 1 782 values = [(value - vmin) / (vmax - vmin)] 783 784 if _has_matplotlib: 785 # matplotlib is available, use it! ########################### 786 if isinstance(name, str): 787 mp = _cm_mpl.get_cmap(name=name) 788 else: 789 mp = name # assume matplotlib.colors.LinearSegmentedColormap 790 result = mp(values)[:, [0, 1, 2]] 791 792 else: 793 # matplotlib not available ################################### 794 invert = False 795 if name.endswith("_r"): 796 invert = True 797 name = name.replace("_r", "") 798 try: 799 cmap = cmaps[name] 800 except KeyError: 801 vedo.logger.error(f"in color_map(), no color map with name {name} or {name}_r") 802 vedo.logger.error(f"Available color maps are:\n{cmaps.keys()}") 803 return np.array([0.5, 0.5, 0.5]) 804 805 result = [] 806 n = len(cmap) - 1 807 for v in values: 808 iv = int(v * n) 809 if invert: 810 iv = n - iv 811 rgb = hex2rgb(cmap[iv]) 812 result.append(rgb) 813 result = np.array(result) 814 815 if cut: 816 return result 817 return result[0]
Map a real value in range [vmin, vmax] to a (r,g,b) color scale.
Return the (r,g,b) color, or a list of (r,g,b) colors.
Arguments:
- value : (float, list) scalar value to transform into a color
- name : (str, matplotlib.colors.LinearSegmentedColormap) color map name
Very frequently used color maps are:
A more complete color maps list:
Can also directly use and customize a matplotlib color map
Example:
from vedo import color_map import matplotlib.cm as cm print( color_map(0.2, cm.flag, 0, 1) ) # (1.0, 0.809016994374948, 0.6173258487801733)
Examples:
820def build_palette(color1, color2, n, hsv=True): 821 """ 822 Generate N colors starting from `color1` to `color2` 823 by linear interpolation in HSV or RGB spaces. 824 825 Arguments: 826 N : (int) 827 number of output colors. 828 color1 : (color) 829 first color. 830 color2 : (color) 831 second color. 832 hsv : (bool) 833 if `False`, interpolation is calculated in RGB space. 834 835 Examples: 836 - [mesh_custom.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/mesh_custom.py) 837 838  839 """ 840 if hsv: 841 color1 = rgb2hsv(color1) 842 color2 = rgb2hsv(color2) 843 c1 = np.array(get_color(color1)) 844 c2 = np.array(get_color(color2)) 845 cols = [] 846 for f in np.linspace(0, 1, n, endpoint=True): 847 c = c1 * (1 - f) + c2 * f 848 if hsv: 849 c = np.array(hsv2rgb(c)) 850 cols.append(c) 851 return np.array(cols)
Generate N colors starting from color1
to color2
by linear interpolation in HSV or RGB spaces.
Arguments:
- N : (int) number of output colors.
- color1 : (color) first color.
- color2 : (color) second color.
- hsv : (bool)
if
False
, interpolation is calculated in RGB space.
Examples:
880def build_lut( 881 colorlist, 882 vmin=None, 883 vmax=None, 884 below_color=None, 885 above_color=None, 886 nan_color=None, 887 below_alpha=1, 888 above_alpha=1, 889 nan_alpha=1, 890 interpolate=False, 891): 892 """ 893 Generate colors in a lookup table (LUT). 894 895 Return the `vtkLookupTable` object. This can be fed into `cmap()` method. 896 897 Arguments: 898 colorlist : (list) 899 a list in the form `[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]`. 900 vmin : (float) 901 specify minimum value of scalar range 902 vmax : (float) 903 specify maximum value of scalar range 904 below_color : (color) 905 color for scalars below the minimum in range 906 below_alpha : (float) 907 opacity for scalars below the minimum in range 908 above_color : (color) 909 color for scalars above the maximum in range 910 above_alpha : (float) 911 alpha for scalars above the maximum in range 912 nan_color : (color) 913 color for invalid (nan) scalars 914 nan_alpha : (float) 915 alpha for invalid (nan) scalars 916 interpolate : (bool) 917 interpolate or not intermediate scalars 918 919 Examples: 920 - [mesh_lut.py](https://github.com/marcomusy/vedo/tree/master/examples/basic/mesh_lut.py) 921 922  923 """ 924 ctf = vtk.vtkColorTransferFunction() 925 ctf.SetColorSpaceToRGB() 926 ctf.SetScaleToLinear() 927 alpha_x, alpha_vals = [], [] 928 for sc in colorlist: 929 if len(sc) >= 3: 930 scalar, col, alf = sc[:3] 931 else: 932 alf = 1 933 scalar, col = sc 934 r, g, b = get_color(col) 935 ctf.AddRGBPoint(scalar, r, g, b) 936 alpha_x.append(scalar) 937 alpha_vals.append(alf) 938 939 lut = vtk.vtkLookupTable() 940 lut.SetNumberOfTableValues(256) 941 942 x0, x1 = ctf.GetRange() # range of the introduced values 943 if vmin is not None: 944 x0 = vmin 945 if vmax is not None: 946 x1 = vmax 947 ctf.SetRange(x0, x1) 948 lut.SetRange(x0, x1) 949 950 if below_color is not None: 951 lut.SetBelowRangeColor(list(get_color(below_color)) + [below_alpha]) 952 lut.SetUseBelowRangeColor(True) 953 if above_color is not None: 954 lut.SetAboveRangeColor(list(get_color(above_color)) + [above_alpha]) 955 lut.SetUseAboveRangeColor(True) 956 if nan_color is not None: 957 lut.SetNanColor(list(get_color(nan_color)) + [nan_alpha]) 958 959 rgba = (1, 1, 1, 1) 960 for i in range(256): 961 p = i / 255 962 x = (1 - p) * x0 + p * x1 963 if interpolate: 964 alf = np.interp(x, alpha_x, alpha_vals) 965 rgba = list(ctf.GetColor(x)) + [alf] 966 else: 967 for c in colorlist: 968 if x <= c[0]: 969 if len(c) == 3: 970 alf = c[2] 971 else: 972 alf = 1 973 rgba = list(get_color(c[1])) + [alf] 974 break 975 lut.SetTableValue(i, rgba) 976 977 lut.Build() 978 return lut
Generate colors in a lookup table (LUT).
Return the vtkLookupTable
object. This can be fed into cmap()
method.
Arguments:
- colorlist : (list)
a list in the form
[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]
. - vmin : (float) specify minimum value of scalar range
- vmax : (float) specify maximum value of scalar range
- below_color : (color) color for scalars below the minimum in range
- below_alpha : (float) opacity for scalars below the minimum in range
- above_color : (color) color for scalars above the maximum in range
- above_alpha : (float) alpha for scalars above the maximum in range
- nan_color : (color) color for invalid (nan) scalars
- nan_alpha : (float) alpha for invalid (nan) scalars
- interpolate : (bool) interpolate or not intermediate scalars
Examples:
590def getColor(rgb=None, hsv=None): 591 """Deprecated. Use `get_color()`""" 592 return get_color(rgb, hsv)
Deprecated. Use get_color()
726def colorMap(value, name="jet", vmin=None, vmax=None): 727 """Deprecated, use `color_map()`""" 728 print("Deprecated call to colorMap(), use color_map() instead") 729 return color_map(value, name, vmin, vmax)
Deprecated, use color_map()
853def buildLUT( 854 colorlist, 855 vmin=None, 856 vmax=None, 857 belowColor=None, 858 aboveColor=None, 859 nanColor=None, 860 belowAlpha=1, 861 aboveAlpha=1, 862 nanAlpha=1, 863 interpolate=False, 864): 865 """Deprecated. Please use `build_lut()`""" 866 print("Deprecated call to buildLUT(). Please use build_lut() instead") 867 return build_lut( 868 colorlist, 869 vmin, 870 vmax, 871 belowColor, 872 aboveColor, 873 nanColor, 874 belowAlpha, 875 aboveAlpha, 876 nanAlpha, 877 interpolate, 878 )
Deprecated. Please use build_lut()