本文整理汇总了Python中matplotlib.colors.hsv_to_rgb函数的典型用法代码示例。如果您正苦于以下问题:Python hsv_to_rgb函数的具体用法?Python hsv_to_rgb怎么用?Python hsv_to_rgb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hsv_to_rgb函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_color_range
def generate_color_range(self):
# color and marker range:
self.colorrange = []
self.markerrange = []
mr2 = []
# first color range:
cc0 = plt.cm.gist_rainbow(np.linspace(0.0, 1.0, 8.0))
# shuffle it:
for k in range((len(cc0) + 1) // 2):
self.colorrange.extend(cc0[k::(len(cc0) + 1) // 2])
self.markerrange.extend(len(cc0) * 'o')
mr2.extend(len(cc0) * 'v')
# second darker color range:
cc1 = plt.cm.gist_rainbow(np.linspace(0.33 / 7.0, 1.0, 7.0))
cc1 = mc.hsv_to_rgb(mc.rgb_to_hsv(np.array([cc1])) * np.array([1.0, 0.9, 0.7, 0.0]))[0]
cc1[:, 3] = 1.0
# shuffle it:
for k in range((len(cc1) + 1) // 2):
self.colorrange.extend(cc1[k::(len(cc1) + 1) // 2])
self.markerrange.extend(len(cc1) * '^')
mr2.extend(len(cc1) * '*')
# third lighter color range:
cc2 = plt.cm.gist_rainbow(np.linspace(0.67 / 6.0, 1.0, 6.0))
cc2 = mc.hsv_to_rgb(mc.rgb_to_hsv(np.array([cc2])) * np.array([1.0, 0.5, 1.0, 0.0]))[0]
cc2[:, 3] = 1.0
# shuffle it:
for k in range((len(cc2) + 1) // 2):
self.colorrange.extend(cc2[k::(len(cc2) + 1) // 2])
self.markerrange.extend(len(cc2) * 'D')
mr2.extend(len(cc2) * 'x')
self.markerrange.extend(mr2)
示例2: test_rgb_hsv_round_trip
def test_rgb_hsv_round_trip():
for a_shape in [(500, 500, 3), (500, 3), (1, 3), (3,)]:
np.random.seed(0)
tt = np.random.random(a_shape)
assert_array_almost_equal(tt,
mcolors.hsv_to_rgb(mcolors.rgb_to_hsv(tt)))
assert_array_almost_equal(tt,
mcolors.rgb_to_hsv(mcolors.hsv_to_rgb(tt)))
示例3: image
def image(self, img):
"""Colorize an image. Input can either be a single image or a stack of images.
In either case, the first dimension must be the quantity to be used for colorizing.
Parameters
----------
img : array
The image to colorize. Must be of shape (c, x, y, z) or (c, x, y), where
c is the dimension containing the information for colorizing.
Returns
-------
out : array
Color assignments for images, either (x, y, z, 3) or (x, y, 3)
"""
d = shape(img)
self.checkargs(d[0])
if img.ndim > 4 or img.ndim < 3:
raise Exception("image data must have 3 or 4 dimensions, first is for coloring, remainder are xy(z)")
if (self.totype == 'rgb') or (self.totype == 'hsv'):
out = abs(img) * self.scale
if img.ndim == 4:
out = transpose(out, (1, 2, 3, 0))
if img.ndim == 3:
out = transpose(out, (1, 2, 0))
elif self.totype == 'polar':
theta = ((arctan2(-img[0], -img[1]) + pi/2) % (pi*2)) / (2 * pi)
rho = sqrt(img[0]**2 + img[1]**2)
if img.ndim == 4:
saturation = ones((d[1],d[2]))
out = zeros((d[1], d[2], d[3], 3))
for i in range(0, d[3]):
out[:, :, i, :] = colors.hsv_to_rgb(dstack((theta[:, :, i], saturation, self.scale*rho[:, :, i])))
if img.ndim == 3:
saturation = ones((d[1], d[2]))
out = colors.hsv_to_rgb(dstack((theta, saturation, self.scale*rho)))
else:
out = cm.get_cmap(self.totype, 256)(img[0] * self.scale)
if img.ndim == 4:
out = out[:, :, :, 0:3]
if img.ndim == 3:
out = out[:, :, 0:3]
return clip(out, 0, 1)
示例4: plot_candidates
def plot_candidates(self):
"""Plot a representation of candidate periodicity
Size gives the periodicity strength,
color the order of preference
"""
fig, ax = pl.subplots(2, sharex=True)
hues = np.arange(self.ncand)/float(self.ncand)
hsv = np.swapaxes(np.atleast_3d([[hues, np.ones(len(hues)),
np.ones(len(hues))]]), 1, 2)
cols = hsv_to_rgb(hsv).squeeze()
for per in self.periods:
nc = len(per.cand_period)
ax[0].scatter(per.time*np.ones(nc), per.cand_period,
s=per.cand_strength*100,
c=cols[0:nc], alpha=.5)
ax[0].plot(*zip(*[[per.time, float(per.get_preferred_period())]
for per in self.periods]), color='k')
ax[1].plot(self.get_times(), self.get_strength())
示例5: draw_3d
def draw_3d(verts, ymin, ymax, line_at_zero=True, colors=True):
'''Given verts as a list of plots, each plot being a list
of (x, y) vertices, generate a 3-d figure where each plot
is shown as a translucent polygon.
If line_at_zero, a line will be drawn through the zero point
of each plot, otherwise the baseline will be at the bottom of
the plot regardless of where the zero line is.
'''
# add_collection3d() wants a collection of closed polygons;
# each polygon needs a base and won't generate it automatically.
# So for each subplot, add a base at ymin.
if line_at_zero:
zeroline = 0
else:
zeroline = ymin
for p in verts:
p.insert(0, (p[0][0], zeroline))
p.append((p[-1][0], zeroline))
if colors:
# All the matplotlib color sampling examples I can find,
# like cm.rainbow/linspace, make adjacent colors similar,
# the exact opposite of what most people would want.
# So cycle hue manually.
hue = 0
huejump = .27
facecolors = []
edgecolors = []
for v in verts:
hue = (hue + huejump) % 1
c = mcolors.hsv_to_rgb([hue, 1, 1])
# random.uniform(.8, 1),
# random.uniform(.7, 1)])
edgecolors.append(c)
# Make the facecolor translucent:
facecolors.append(mcolors.to_rgba(c, alpha=.7))
else:
facecolors = (1, 1, 1, .8)
edgecolors = (0, 0, 1, 1)
poly = PolyCollection(verts,
facecolors=facecolors, edgecolors=edgecolors)
zs = range(len(data))
# zs = range(len(data)-1, -1, -1)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
plt.tight_layout(pad=2.0, w_pad=10.0, h_pad=3.0)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim3d(0, len(data[1]))
ax.set_ylim3d(-1, len(data))
ax.set_zlim3d(ymin, ymax)
示例6: plot
def plot(data, scatter=False, sample_axis=False, hsv=None, **args):
data = np.array(data)
if len(data.shape) > 1:
dimensions = data.shape[1]
else:
dimensions = 1
sample_axis = True
if sample_axis:
data = np.column_stack((range(0, len(data)), data))
dimensions += 1
if dimensions == 3:
_3d()
f = ax.plot if not scatter else ax.scatter
if hsv is not None:
args['c'] = colors.hsv_to_rgb(hsv[:3])
if len(hsv) == 4:
args['alpha'] = hsv[3]
if 'label' in args:
global legend
legend = True
args['label'] = args['label'].upper()
if dimensions == 2:
f(data[:,0], data[:,1], **args)
if dimensions == 3:
f(data[:,0], data[:,1], data[:,2], **args)
示例7: flow_visualize
def flow_visualize(flow, mode='Y'):
if mode == 'Y':
# Ccbcr color wheel
img = fl.flow_to_image(flow)
plt.imshow(img)
plt.show()
elif mode == 'RGB':
(h, w) = flow.shape[0:2]
du = flow[:, :, 0]
dv = flow[:, :, 1]
valid = flow[:, :, 2]
max_flow = max(np.max(du), np.max(dv))
img = np.zeros((h, w, 3), dtype=np.float64)
# angle layer
img[:, :, 0] = np.arctan2(dv, du) / (2 * np.pi)
# magnitude layer, normalized to 1
img[:, :, 1] = np.sqrt(du * du + dv * dv) * 8 / max_flow
# phase layer
img[:, :, 2] = 8 - img[:, :, 1]
# clip to [0,1]
small_idx = img[:, :, 0:3] < 0
large_idx = img[:, :, 0:3] > 1
img[small_idx] = 0
img[large_idx] = 1
# convert to rgb
img = cl.hsv_to_rgb(img)
# remove invalid point
img[:, :, 0] = img[:, :, 0] * valid
img[:, :, 1] = img[:, :, 1] * valid
img[:, :, 2] = img[:, :, 2] * valid
# show
plt.imshow(img)
plt.show()
return
示例8: random_cmap
def random_cmap(ncolors=256, random_state=None):
"""
Generate a matplotlib colormap consisting of random (muted) colors.
A random colormap is very useful for plotting segmentation images.
Parameters
----------
ncolors : int, optional
The number of colors in the colormap. The default is 256.
random_state : int or `~numpy.random.RandomState`, optional
The pseudo-random number generator state used for random
sampling. Separate function calls with the same
``random_state`` will generate the same colormap.
Returns
-------
cmap : `matplotlib.colors.Colormap`
The matplotlib colormap with random colors.
"""
from matplotlib import colors
prng = check_random_state(random_state)
h = prng.uniform(low=0.0, high=1.0, size=ncolors)
s = prng.uniform(low=0.2, high=0.7, size=ncolors)
v = prng.uniform(low=0.5, high=1.0, size=ncolors)
hsv = np.dstack((h, s, v))
rgb = np.squeeze(colors.hsv_to_rgb(hsv))
return colors.ListedColormap(rgb)
示例9: imgcolor
def imgcolor(arr ,normal = True,
#spectrum =True,
BW = False,
alpha = False,
color = [1,0,0]
):
acopy = array(arr)
if normal:
acopy -= np.min(acopy)
acopy /= np.max(acopy)
if BW:
cell = array([1,1,1])
a3d = array(acopy[:,:,newaxis] * cell)
return a3d
elif alpha:
cell = array([0,0,0,1])
a4d = array(acopy[:,:,newaxis] * cell)
cell2 = concatenate((color,[0]))
a4d = a4d + cell2
return a4d
else:
#Assume spectrum....
a3d = array([[array([j,1,1]) for j in i] for i in acopy])
rgb = mplcolors.hsv_to_rgb(a3d)
return rgb
示例10: plotDataPoints
def plotDataPoints(X, idx, K):
V = H = np.linspace(0, 1, K).reshape((-1, 1))
S = np.ones_like(V)
HSV = np.hstack((H, S, V))
RGB = hsv_to_rgb(HSV)
colors = np.array([RGB[int(i[0])] for i in idx])
scatter(X[:, 0], X[:, 1], s=np.pi * 5 ** 2, alpha=0.1, c=colors)
示例11: color_from_external_spec
def color_from_external_spec(self,feat):
field_name = self.config['map']['field_name']
field_value = feat.GetField(field_name)
hsv = self.config['map'][field_value].split(",")
hsv = [float(num) for num in hsv]
mapcolor = colors.hsv_to_rgb(hsv)
return mapcolor
示例12: chord_idx_to_colors
def chord_idx_to_colors(idx, hue_offset=0, max_idx=156,
no_chord_idx=156, x_chord_idx=-1):
"""Transform a chord class index to an (R, G, B) color.
Parameters
----------
idx : array_like
Chord class index.
max_idx : int, default=156
Maximum index, for color scaling purposes.
no_chord_idx : int, default=156
Index of the no-chord class.
x_chord_idx : int, default=-1
Index of the X-chord class (ignored).
Returns
-------
colors : np.ndarray, shape=(1, len(idx), 3)
Matrix of color values.
"""
hue = ((idx + hue_offset) % 12) / 12.0
value = 0.9 - 0.7*(((idx).astype(int) / 12) / (max_idx / 12.0))
hsv = np.array([hue, (hue*0) + 0.6, value]).T
hsv[idx == no_chord_idx, :] = np.array([0, 0.8, 0.0])
hsv[idx == x_chord_idx, :] = np.array([0.0, 0.0, 0.5])
return hsv_to_rgb(hsv.reshape(1, -1, 3))
示例13: plot_clusters
def plot_clusters(ax, x, y, labels=None):
ax.scatter(x, y, s=50,
c='b' if labels is None else [hsv_to_rgb((l/(max(labels)+1), 1, 0.9)) for l in labels])
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim(-3, 10)
ax.set_ylim(-3, 10)
示例14: hsv_hist
def hsv_hist(filename):
hsv = pl.hist_hsv(filename)
fig, ax = plt.subplots(4, 1, figsize=(10, 5))
types = ['hue', 'saturation', 'value']
cl = ['r', 'g', 'b']
V, H = np.mgrid[0.45:0.55:10j, 0:1:300j]
S = np.ones_like(V)
HSV = np.dstack((H, S, V))
RGB = hsv_to_rgb(HSV)
ax[0].imshow(RGB, origin="lower", extent=[0, 360, 0, 1], aspect=10)
ax[0].xaxis.set_major_locator(plt.NullLocator())
ax[0].yaxis.set_major_locator(plt.NullLocator())
idx_array = np.arange(0, 256, 1)
for i, t in enumerate(types):
ax[i+1].fill_between(idx_array, 0, hsv[i, :], color=cl[i], label=t)
ax[i+1].set_xlim(0, 255)
ax[i+1].legend()
plt.show()
示例15: shadow_filter
def shadow_filter(image, dpi):
"""This filter creates a metallic look on patches.
image : the image of the patch
dpi : the resultion of the patch"""
# Get the shape of the image
nx, ny, depth = image.shape
# Create a mash grid
xx, yy = np.mgrid[0:nx, 0:ny]
# Draw a circular "shadow"
circle = (xx + nx * 4) ** 2 + (yy + ny) ** 2
# Normalize
circle -= circle.min()
circle = circle / circle.max()
# Steepness
value = circle.clip(0.3, 0.6) + 0.4
saturation = 1 - circle.clip(0.7, 0.8)
# Normalize
saturation -= saturation.min() - 0.1
saturation = saturation / saturation.max()
# Convert the rgb part (without alpha) to hsv
hsv = mc.rgb_to_hsv(image[:, :, :3])
# Multiply the value of hsv image with the shadow
hsv[:, :, 2] = hsv[:, :, 2] * value
# Highlights with saturation
hsv[:, :, 1] = hsv[:, :, 1] * saturation
# Copy the hsv back into the image (we haven't touched alpha)
image[:, :, :3] = mc.hsv_to_rgb(hsv)
# the return values are: new_image, offset_x, offset_y
return image, 0, 0