本文整理汇总了Python中matplotlib.colors.hsv_to_rgb函数的典型用法代码示例。如果您正苦于以下问题:Python hsv_to_rgb函数的具体用法?Python hsv_to_rgb怎么用?Python hsv_to_rgb使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hsv_to_rgb函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:jfsehuanes,项目名称:thunderfish,代码行数:31,代码来源:fishfinder.py
示例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)))
开发者ID:bastibe,项目名称:matplotlib,代码行数:8,代码来源:test_colors.py
示例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)
开发者ID:NEILKUANG,项目名称:thunder,代码行数:49,代码来源:colorize.py
示例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())
开发者ID:goiosunsw,项目名称:PyPeVoc,代码行数:25,代码来源:Periodicity.py
示例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)
开发者ID:akkana,项目名称:scripts,代码行数:60,代码来源:multiplot3d.py
示例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)
开发者ID:O-C-R,项目名称:housepy,代码行数:25,代码来源:chart.py
示例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
开发者ID:liruoteng,项目名称:FlowNet,代码行数:35,代码来源:kittitool.py
示例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)
开发者ID:laurenmarietta,项目名称:photutils,代码行数:32,代码来源:colormaps.py
示例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
开发者ID:bh0085,项目名称:compbio,代码行数:28,代码来源:colors.py
示例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)
开发者ID:baohx,项目名称:ml-008-python-version,代码行数:7,代码来源:ex7_pca.py
示例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
开发者ID:fraserkeppie,项目名称:welly,代码行数:7,代码来源:ogr_reader_polygons.py
示例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))
开发者ID:ejhumphrey,项目名称:ace-lessons,代码行数:27,代码来源:visualize.py
示例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)
开发者ID:roboloni,项目名称:artificial_responsability,代码行数:7,代码来源:Plots.py
示例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()
开发者ID:giulioungaretti,项目名称:ArtScope,代码行数:25,代码来源:colorextract.py
示例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
开发者ID:TRiedling,项目名称:adsy-python,代码行数:30,代码来源:plotenhance.py
示例16: colormap
def colormap(x, col0=None, col1=None):
"""Colorize a 2D grayscale array.
Arguments:
* x:an NxM array with values in [0,1].
* col0=None: a tuple (H, S, V) corresponding to color 0. By default, a
rainbow color gradient is used.
* col1=None: a tuple (H, S, V) corresponding to color 1.
Returns:
* y: an NxMx3 array with a rainbow color palette.
"""
x = np.clip(x, 0., 1.)
shape = x.shape
if col0 is None:
col0 = (.67, .91, .65)
if col1 is None:
col1 = (0., 1., 1.)
col0 = np.array(col0).reshape((1, 1, -1))
col1 = np.array(col1).reshape((1, 1, -1))
col0 = np.tile(col0, x.shape + (1,))
col1 = np.tile(col1, x.shape + (1,))
x = np.tile(x.reshape(shape + (1,)), (1, 1, 3))
return hsv_to_rgb(col0 + (col1 - col0) * x)
开发者ID:shabnamkadir,项目名称:spiky,代码行数:31,代码来源:correlationmatrixview.py
示例17: plot_data_points
def plot_data_points(X, centroid_indices, num_centroids):
""" Plots input data with colors according to current cluster assignments.
Args:
X: Matrix of data features.
centroid_indices: Vector where each entry contains index of closest
centroid to corresponding example.
num_centroids: Number of centroids.
Returns:
None.
Raises:
An error occurs if the number of data examples is 0.
"""
num_data = X.shape[0]
if (num_data == 0): raise Error('num_data == 0')
palette = numpy.zeros((num_centroids+1, 3))
for centroid_idx in range(0, num_centroids+1):
hsv_h = centroid_idx/(num_centroids+1)
hsv_s = 1
hsv_v = 1
palette[centroid_idx, :] = colors.hsv_to_rgb(numpy.r_[hsv_h, hsv_s,
hsv_v])
curr_colors = numpy.zeros((num_data, 3))
for data_idx in range(0, num_data):
curr_centroid_idx = centroid_indices[data_idx].astype(int)
curr_colors[curr_centroid_idx, 0] = palette[curr_centroid_idx, 0]
curr_colors[curr_centroid_idx, 1] = palette[curr_centroid_idx, 1]
curr_colors[curr_centroid_idx, 2] = palette[curr_centroid_idx, 2]
pyplot.scatter(X[data_idx, 0], X[data_idx, 1], s=80, marker='o',
facecolors='none',
edgecolors=curr_colors[curr_centroid_idx, :])
return None
开发者ID:cklcit03,项目名称:machine-learning,代码行数:34,代码来源:ex7.py
示例18: color_from_internal_spec
def color_from_internal_spec(self, feat, label, hue, sat, val):
geology_code = feat.GetField("LEGEND_ID")
geology_hue = feat.GetField(hue)/256
geology_sat = 0.25*feat.GetField(sat)/256
geology_val = feat.GetField(val)/256
mapcolor = colors.hsv_to_rgb([geology_hue,geology_sat,geology_val])
return mapcolor
开发者ID:fraserkeppie,项目名称:welly,代码行数:7,代码来源:ogr_reader_polygons.py
示例19: compute_color_map
def compute_color_map():
"""Compute a default QM colormap which can be used as mayavi/vtk lookup table.
"""
k = linspace(-pi, pi, 256, endpoint=True)
hsv_colors = ones((1, k.shape[0], 3))
hsv_colors[:, :, 0] = 0.5 * fmod(k + 2 * pi, 2 * pi) / pi
return 255 * squeeze(hsv_to_rgb(hsv_colors))
开发者ID:GaZ3ll3,项目名称:WaveBlocksND,代码行数:7,代码来源:surfcf.py
示例20: hsv_to_rgb_tuple
def hsv_to_rgb_tuple(hsv_tuple):
"""
Convert 3 tuple that represents a HSV color
to a 3 tuple in RGB color space (values between 0..1).
If you have an array of color values use: ``matplotlib.colors.hsv_to_rgb``.
"""
colarr = hsv_to_rgb(np.array([[hsv_tuple]]))
return tuple(colarr[0, 0, :])
开发者ID:eike-welk,项目名称:clair,代码行数:8,代码来源:diagram.py
注:本文中的matplotlib.colors.hsv_to_rgb函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论