本文整理汇总了Python中matplotlib.colors.to_rgb方法的典型用法代码示例。如果您正苦于以下问题:Python colors.to_rgb方法的具体用法?Python colors.to_rgb怎么用?Python colors.to_rgb使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.colors
的用法示例。
在下文中一共展示了colors.to_rgb方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_cn
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def test_cn():
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['blue', 'r'])
assert mcolors.to_hex("C0") == '#0000ff'
assert mcolors.to_hex("C1") == '#ff0000'
matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
['xkcd:blue', 'r'])
assert mcolors.to_hex("C0") == '#0343df'
assert mcolors.to_hex("C1") == '#ff0000'
matplotlib.rcParams['axes.prop_cycle'] = cycler('color', ['8e4585', 'r'])
assert mcolors.to_hex("C0") == '#8e4585'
# if '8e4585' gets parsed as a float before it gets detected as a hex
# colour it will be interpreted as a very large number.
# this mustn't happen.
assert mcolors.to_rgb("C0")[0] != np.inf
示例2: lighten_color
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def lighten_color(color, amount=0.5):
"""
Lightens the given color by multiplying (1-luminosity) by the given amount.
Input can be matplotlib color string, hex string, or RGB tuple.
Examples:
>> lighten_color('g', 0.3)
>> lighten_color('#F034A3', 0.6)
>> lighten_color((.3,.55,.1), 0.5)
"""
import matplotlib.colors as mc
import colorsys
try:
c = mc.cnames[color]
except:
c = color
c = colorsys.rgb_to_hls(*mc.to_rgb(c))
return colorsys.hls_to_rgb(c[0], 1 - amount * (1 - c[1]), c[2])
示例3: darken_color
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def darken_color(color, amount=0.5):
"""
Darkens the given color by multiplying luminosity by the given amount.
Input can be matplotlib color string, hex string, or RGB tuple.
Examples:
>> lighten_color('g', 0.3)
>> lighten_color('#F034A3', 0.6)
>> lighten_color((.3,.55,.1), 0.5)
"""
import matplotlib.colors as mc
import colorsys
try:
c = mc.cnames[color]
except:
c = color
c = colorsys.rgb_to_hls(*mc.to_rgb(c))
return colorsys.hls_to_rgb(c[0], amount * c[1], c[2])
示例4: _jitter
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def _jitter(self, color):
"""
Randomly modifies given color to produce a slightly different color than the color given.
Args:
color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color
picked. The values in the list are in the [0.0, 1.0] range.
Returns:
jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the
color after being jittered. The values in the list are in the [0.0, 1.0] range.
"""
color = mplc.to_rgb(color)
vec = np.random.rand(3)
# better to do it in another color space
vec = vec / np.linalg.norm(vec) * 0.5
res = np.clip(vec + color, 0, 1)
return tuple(res)
示例5: _change_color_brightness
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def _change_color_brightness(self, color, brightness_factor):
"""
Depending on the brightness_factor, gives a lighter or darker color i.e. a color with
less or more saturation than the original color.
Args:
color: color of the polygon. Refer to `matplotlib.colors` for a full list of
formats that are accepted.
brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of
0 will correspond to no change, a factor in [-1.0, 0) range will result in
a darker color and a factor in (0, 1.0] range will result in a lighter color.
Returns:
modified_color (tuple[double]): a tuple containing the RGB values of the
modified color. Each value in the tuple is in the [0.0, 1.0] range.
"""
assert brightness_factor >= -1.0 and brightness_factor <= 1.0
color = mplc.to_rgb(color)
polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))
modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])
modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness
modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness
modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2])
return modified_color
示例6: color_to_rgb
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def color_to_rgb(color):
"""Converts a color to a RGB tuple from (0-255)."""
if isinstance(color, tuple):
# if a RGB tuple already
return color
else:
# to_rgb() returns colors from (0-1)
color = tuple(int(x * 255) for x in to_rgb(color))
return color
示例7: set_color
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def set_color(self, color: Union[str, Sequence], index: int = None):
""" set a color to the given index """
# update the color according to the index
if index is not None:
self.init_colors[index] = to_rgb(color)
# or update the whole list
else:
# ensure that the colors are rgb
self.init_colors = [to_rgb(c) for c in color]
# linearize the lightness
self.linearize_lightness()
# notify that we have to reinitialize the colormap
self._isinit = False
示例8: test_bar_color_cycle
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def test_bar_color_cycle():
to_rgb = mcolors.to_rgb
fig, ax = plt.subplots()
for j in range(5):
ln, = ax.plot(range(3))
brs = ax.bar(range(3), range(3))
for br in brs:
assert to_rgb(ln.get_color()) == to_rgb(br.get_facecolor())
示例9: colors_per_labels
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def colors_per_labels(labels: Sequence[str]) -> Sequence[Color]:
"""
Creates an list of colors associated to a label.
I recommend to call this function to associate a color to labels and then
use the draw_boxes function passing the output of this function as the
list of colors
Examples
--------
>>> labels = ['cat', 'dog', 'dog', 'cat']
>>> colors_per_labels(labels)
... ['green', 'red, 'red, 'green']
>>> labels = ['cat', 'dog', 'dog', 'cat']
>>> colors = colors_per_labels(labels)
>>> draw_boxes(image, labels, colors=colors)
"""
import matplotlib.colors as mcolors
colors = [mcolors.to_rgb(c) for c in mcolors.TABLEAU_COLORS]
colors = (tuple([int(255 * c) for c in color]) for color in colors)
unique_labels = set(labels)
color_x_label: Mapping[str, Color] = dict(
zip(labels, cycle(colors))) # type: ignore[arg-type]
return [color_x_label[o] for o in labels]
示例10: _plot_reconstruction
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def _plot_reconstruction(self, updater, fetched):
inp = fetched['inp']
output = fetched['output']
_, image_height, image_width, _ = inp.shape
obj = fetched['obj'].reshape(self.N, -1)
anchor_box = updater.network.anchor_box
yt, xt, ys, xs = np.split(fetched['normalized_box'], 4, axis=-1)
yt, xt, ys, xs = coords_to_pixel_space(
yt, xt, ys, xs, (image_height, image_width), anchor_box, top_left=True)
box = np.concatenate([yt, xt, ys, xs], axis=-1)
box = box.reshape(self.N, -1, 4)
on_colour = np.array(to_rgb("xkcd:azure"))
off_colour = np.array(to_rgb("xkcd:red"))
for n, (pred, gt) in enumerate(zip(output, inp)):
fig = plt.figure(figsize=(5, 5))
ax = plt.gca()
self.imshow(ax, gt)
ax.set_axis_off()
# Plot proposed bounding boxes
for o, (top, left, height, width) in zip(obj[n], box[n]):
if not self.show_zero_boxes and o <= 1e-6:
continue
colour = o * on_colour + (1-o) * off_colour
rect = patches.Rectangle(
(left, top), width, height, linewidth=2, edgecolor=colour, facecolor='none')
ax.add_patch(rect)
plt.subplots_adjust(left=.01, right=.99, top=.99, bottom=0.01, wspace=0.1, hspace=0.1)
self.savefig("ground_truth/" + str(n), fig, updater, is_dir=False)
示例11: tf_find_connected_components
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def tf_find_connected_components(inp, bg, threshold, colors=None, cosine_threshold=None):
assert len(inp.shape) == 4
if isinstance(colors, str):
colors = colors.split()
mask = tf.reduce_sum(tf.abs(inp - bg), axis=3) >= threshold
if colors is None or cosine_threshold is None:
output = _find_connected_componenents_body(mask)
output['color'] = output['obj']
return output
objects = []
for color in colors:
if isinstance(color, str):
color = tf.constant(to_rgb(color), tf.float32)
similarity = tf_cosine_similarity(inp, color)
color_mask = tf.logical_and(similarity >= cosine_threshold, mask)
objects.append(
_find_connected_componenents_body(color_mask)
)
output = dict(
normalized_box=tf.concat([o['normalized_box'] for o in objects], axis=1),
obj=tf.concat([o['obj'] for o in objects], axis=1),
n_objects=tf.reduce_sum(tf.stack([o['n_objects'] for o in objects], axis=1), axis=1),
color=tf.concat([float(i+1) * o['obj'] for i, o in enumerate(objects)], axis=1),
)
output['max_objects'] = tf.reduce_max(output['n_objects'])
return output
示例12: rgb_custom_colormap
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def rgb_custom_colormap(colors=None, alpha=None, N=256):
"""Creates a custom colormap. Colors can be given as names or rgb values.
Arguments
---------
colors: : `list` or `array` (default `['royalblue', 'white', 'forestgreen']`)
List of colors, either as names or rgb values.
alpha: `list`, `np.ndarray` or `None` (default: `None`)
Alpha of the colors. Must be same length as colors.
N: `int` (default: `256`)
y coordinate
Returns
-------
A ListedColormap
"""
if colors is None:
colors = ["royalblue", "white", "forestgreen"]
c = []
if "transparent" in colors:
if alpha is None:
alpha = [1 if i != "transparent" else 0 for i in colors]
colors = [i if i != "transparent" else "white" for i in colors]
for color in colors:
if isinstance(color, str):
color = to_rgb(color if color.startswith("#") else cnames[color])
c.append(color)
if alpha is None:
alpha = np.ones(len(c))
vals = np.ones((N, 4))
ints = len(c) - 1
n = int(N / ints)
for j in range(ints):
for i in range(3):
vals[n * j : n * (j + 1), i] = np.linspace(c[j][i], c[j + 1][i], n)
vals[n * j : n * (j + 1), -1] = np.linspace(alpha[j], alpha[j + 1], n)
return ListedColormap(vals)
示例13: draw_polygon
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):
"""
Args:
segment: numpy array of shape Nx2, containing all the points in the polygon.
color: color of the polygon. Refer to `matplotlib.colors` for a full list of
formats that are accepted.
edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a
full list of formats that are accepted. If not provided, a darker shade
of the polygon color will be used instead.
alpha (float): blending efficient. Smaller values lead to more transparent masks.
Returns:
output (VisImage): image object with polygon drawn.
"""
if edge_color is None:
# make edge color darker than the polygon color
if alpha > 0.8:
edge_color = self._change_color_brightness(color, brightness_factor=-0.7)
else:
edge_color = color
edge_color = mplc.to_rgb(edge_color) + (1,)
polygon = mpl.patches.Polygon(
segment,
fill=True,
facecolor=mplc.to_rgb(color) + (alpha,),
edgecolor=edge_color,
linewidth=max(self._default_font_size // 15 * self.output.scale, 1),
)
self.output.ax.add_patch(polygon)
return self.output
示例14: test_plot_line_shaded_std
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def test_plot_line_shaded_std():
a = np.arange(10)
noise = np.random.rand(len(a))
ll, ff = plot_line_shaded_std(a, a, noise)
# Test defaults
assert ff.get_edgecolor().size == 0
assert ff.get_alpha() == 0.35
assert (to_rgb(ll[-1].get_color()) == ff.get_facecolor()[0][0:3]).all()
示例15: adjust_lightness
# 需要导入模块: from matplotlib import colors [as 别名]
# 或者: from matplotlib.colors import to_rgb [as 别名]
def adjust_lightness(color, amount=0.7):
"""Lightens the given color by multiplying (1-luminosity) by the given amount.
Input can be matplotlib color string, hex string, or RGB tuple.
Output will be an RGB string."""
import matplotlib.colors as mc
import colorsys
try:
c = mc.cnames[color]
except:
c = color
c = colorsys.rgb_to_hls(*mc.to_rgb(c))
rgb = colorsys.hls_to_rgb(c[0], max(0, min(1, amount * c[1])), c[2])
return 'rgb(%d,%d,%d)' % (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))