def __changeMode(self, *args):
newMode = self.colorModeVar.get()
if newMode != self.colorModeLocal:
x = self.colorX.get()
y = self.colorY.get()
z = self.colorZ.get()
col=0
if newMode == 0: # HSV->RGB
col = [ int(round(x*255.0)) for x in colorsys.hsv_to_rgb(x/255.0, y/255.0, z/255.0)]
else: # RGB -> HSV
col = [ int(round(x*255.0)) for x in colorsys.rgb_to_hsv(x/255.0, y/255.0, z/255.0)]
self.colorX.set(col[0])
self.colorY.set(col[1])
self.colorZ.set(col[2])
self.colorModeLocal = newMode
python类rgb_to_hsv()的实例源码
def setColor(self, r, g, b):
"""
:param r: red, integer 0-255
:param g: green, integer 0-255
:param b: blue, integer 0-255
:return: None
"""
self.updateEnabled = False
if self.colorModeLocal == 1: # hsv
col = [ int(round(x*255)) for x in colorsys.rgb_to_hsv(float(r)/255,float(g)/255,float(b)/255)]
self.colorX.set(col[0])
self.colorY.set(col[1])
self.colorZ.set(col[2])
self.colorSwatch.itemconfig(self.crect, fill='#%02x%02x%02x'%(r, g, b))
else: # RGB
self.colorX.set(r)
self.colorY.set(g)
self.colorZ.set(b)
self.colorSwatch.itemconfig(self.crect, fill='#%02x%02x%02x'%(r, g, b))
self.updateEnabled = True
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def set_outline(self, color=[255, 0, 0], width=2):
'enables the draw_outline and sets line color and width'
self.perm_outline = True
if color == 0 and hasattr(self, "door_outline") is False: # if color is 0 calculate colour from base colour
# convert to hsv
c = self.color
h, s, v = ex.rgb_to_hsv(c[0], c[1], c[2])
outline_color = ex.hsv_to_rgb(h, s + 50, v - 50)
self.perm_outline_color = outline_color
elif color == 1:
c = self.color
h, s, v = ex.rgb_to_hsv(c[0], c[1], c[2])
outline_color = ex.hsv_to_rgb(h, s + 20, v - 20)
self.perm_outline_color = outline_color
elif hasattr(self, "door_outline") is False:
self.perm_outline_color = color
else:
pass
# self.perm_outline_color = color
# self.perm_outline_color = [255,0,0]
self.perm_outline_width = width
self.init_pow = width
def hue_change(img, intensity, value):
"""
Change to purple/green hue
:param img: PIL image object
:param intensity: float > 0.1, larger the value, the less intense and more washout
:param value: float, the colour to hue change too on a scale from -360 to 0
:return: PIL image object
"""
original_width, original_height = img.size
# Don't apply hue change if already grayscaled.
if img.mode == 'L':
return img
else:
ld = img.load()
for y in range(original_height):
for x in range(original_width):
r, g, b = ld[x, y]
h, s, v = rgb_to_hsv(r/255, g/255, b/255)
h = (h + value/360.0) % 1.0
s = s**intensity
r, g, b = hsv_to_rgb(h, s, v)
ld[x, y] = (int(r * 255.9999), int(g * 255.9999), int(b * 255.9999))
return img
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def rgbToHSV(data):
"""Convert image from RGB to HSV
Parameters
----------
data : numpy array [rows x columns x channels], input RGB image
Returns
-------
output : numpy array [rows x columns x channels], output HSV image
"""
dataSize = data.shape
output = np.zeros([np.prod(dataSize[0:2]),3])
data = data.reshape([np.prod(dataSize[0:2]),-1])
for i in range(0,np.prod(dataSize[0:2])):
output[i,:] = rgb_to_hsv(data[i,0],data[i,1],data[i,2])
return output.reshape(dataSize)
def colour(self, ctx):
"""Generates a random colo(u)r."""
colour = discord.Colour(random.randint(0, 0xFFFFFF))
as_str = str(colour)
rgb = colour.to_rgb()
h, s, v = colorsys.rgb_to_hsv(*(v / 255 for v in rgb))
hsv = h * 360, s * 100, v * 100
colour_embed = (discord.Embed(title=as_str, colour=colour)
.set_thumbnail(url=f'http://colorhexa.com/{as_str[1:]}.png')
.add_field(name="RGB", value='%d, %d, %d' % rgb)
.add_field(name="HSV", value='%.03f, %.03f, %.03f' % hsv))
if webcolors:
colour_embed.description = get_colour_name(rgb)
await ctx.send(embed=colour_embed)
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def main():
# Load image and convert it to RGBA, so it contains alpha channel
file_path = sys.argv[1]
name, ext = os.path.splitext(file_path)
im = Image.open(file_path)
im = im.convert('RGBA')
# Go through all pixels and turn each 'green' pixel to transparent
pix = im.load()
width, height = im.size
for x in range(width):
for y in range(height):
r, g, b, a = pix[x, y]
h, s, v = rgb_to_hsv(r, g, b)
min_h, min_s, min_v = GREEN_RANGE_MIN_HSV
max_h, max_s, max_v = GREEN_RANGE_MAX_HSV
if min_h <= h <= max_h and min_s <= s <= max_s and min_v <= v <= max_v:
pix[x, y] = (0, 0, 0, 0)
im.save(name + '.png')
def get_state(channel):
global status
for chan in range(1, 5):
for pixel in range(16):
if mote.get_pixel(chan, pixel) != (0, 0, 0):
status['state'][chan] = 1
else:
status['state'][chan] = 0
col = mote.get_pixel(chan, 0)
br = rgb_to_hsv(*col)[2]
status['colour'][chan] = list(col)
status['brightness'][chan] = br
if channel == 'all':
return jsonify(status)
else:
channel_status = {}
for k in status:
channel_status[k] = {int(channel): status[k][int(channel)]}
return jsonify(channel_status)
## Sets all channels, or a given channel, "on" or "off"
def set_brightness(channel, br):
global status
if channel == 'all':
for ch in status['colour']:
c = status['colour'][ch]
r, g, b = c
h, s, v = rgb_to_hsv(r, g, b)
v = int(br) / 100.0
r, g, b = [int(c * 255) for c in hsv_to_rgb(h, s, v)]
status['colour'][ch] = [r, g, b]
if not all(status['state'].values()) == 0:
mote_on(status)
else:
c = status['colour'][int(channel)]
r, g, b = c
h, s, v = rgb_to_hsv(r, g, b)
v = int(br) / 100.0
r, g, b = [int(c * 255) for c in hsv_to_rgb(h, s, v)]
status['colour'][int(channel)] = [r, g, b]
if not status['state'][int(channel)] == 0:
mote_on(status)
return jsonify(status)
## Returns the current API version to the requester
def __rgb2hlv(I_rgb, repetitions=1):
I_hlv = []
for p in prange(0,len(I_rgb)):
r = I_rgb[p, pgc.CH_RED]
g = I_rgb[p, pgc.CH_GREEN]
b = I_rgb[p, pgc.CH_BLUE]
lum = np.sqrt(.241 * r + .691 * g + .068 * b)
h, s, v = colorsys.rgb_to_hsv(r, g, b)
h2 = int(h * repetitions)
lum2 = int(lum * repetitions)
v2 = int(v * repetitions)
if h2 % 2 == 1:
v2 = repetitions - v2
lum = repetitions - lum2
I_hlv.append((h2, lum, v2))
return np.array(I_hlv, dtype=[('h', '<i4'), ('l', '<i4'), ('v', '<i4')])
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def from_rgb_to_paletton_hue(r, g, b, color_wheel):
from colorsys import rgb_to_hsv
h, s, v = rgb_to_hsv(r, g, b)
wheel_hues = tuple(
rgb_to_hsv(*color_wheel[k][:3])[0] for k in sorted(color_wheel.keys())
)
if h in wheel_hues:
paletton_hue = wheel_hues.index(h) * 15
else:
i = sorted(wheel_hues + (h,)).index(h)
wheel_start = (i - 1) * 15
wheel_end = i * 15 if i < len(wheel_hues) else 360
h1 = wheel_hues[i-1]
h2 = wheel_hues[i] if i < len(wheel_hues) else 1.
k = (h - h1) / (h2 - h1)
log.debug(
"k=%s, h=%s, h1=%s, h2=%s, i1=%s, i2=%s",
k, h, h1, h2, wheel_start, wheel_end
)
paletton_hue = round(
wheel_start + k * (wheel_end - wheel_start)
)
paletton_hue %= 360
return paletton_hue
def __init__(self):
self.ctr = 0
self.joiner = u'\n\t\t\t'
self.header = u'\t\t<CropObjectClass>'
self.footer = u'</CropObjectClass>'
self.default_color = u'#FF6060'
self.color_RGB = (1.0, 0.4, 0.4) # Used for output
self.color_HSV = colorsys.rgb_to_hsv(*self.color_RGB) # Used internally
self.delta_hue = 0.017
self.delta_hue_group = 0.37
#: Each group has its own list of colors. Their starts
# are separated by self.delta_hue_group. The last member
# of each group_colordict value is the next color for that
# group.
self.group_colordict = collections.OrderedDict()
def test_hsv_values(self):
values = [
# rgb, hsv
((0.0, 0.0, 0.0), ( 0 , 0.0, 0.0)), # black
((0.0, 0.0, 1.0), (4./6., 1.0, 1.0)), # blue
((0.0, 1.0, 0.0), (2./6., 1.0, 1.0)), # green
((0.0, 1.0, 1.0), (3./6., 1.0, 1.0)), # cyan
((1.0, 0.0, 0.0), ( 0 , 1.0, 1.0)), # red
((1.0, 0.0, 1.0), (5./6., 1.0, 1.0)), # purple
((1.0, 1.0, 0.0), (1./6., 1.0, 1.0)), # yellow
((1.0, 1.0, 1.0), ( 0 , 0.0, 1.0)), # white
((0.5, 0.5, 0.5), ( 0 , 0.0, 0.5)), # grey
]
for (rgb, hsv) in values:
self.assertTripleEqual(hsv, colorsys.rgb_to_hsv(*rgb))
self.assertTripleEqual(rgb, colorsys.hsv_to_rgb(*hsv))
def _command(self, action, value, success, failure, **kwargs):
if action == Device.TURNON:
self.light.brightness = 1
self.light.power = True
elif action == Device.TURNOFF:
self.light.power = False
elif action == Device.DIM:
self.light.brightness = value/255.0
self.light.power = True
elif action == Device.RGBW:
r = (value >> 24) & 0xFF
g = (value >> 16) & 0xFF
b = (value >> 8) & 0xFF
(h, s, l) = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
self.light.color = lifx.color.modify_color(self.light.color, hue=h*360.0, saturation=s)
self.light.power = True
else:
failure(0)
return
success()
def get_color(im):
'''
Get the main color of a picture, by this color we can judge the status of a video is finished or not.
'''
im = Image.open(im)
im = im.convert('RGBA')
# generate thumbnails, reduce cpu pressure
im.thumbnail((200, 200))
max_score = None
dominant_color = None
for count, (r, g, b, a) in im.getcolors(im.size[0] * im.size[1]):
saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
y = (y - 16.0) / (235 - 16)
score = (saturation + 0.1) * count
if score > max_score:
max_score = score
dominant_color = (r, g, b)
return dominant_color
def HSVColor(img):
if isinstance(img, Image.Image):
r,g,b = img.split()
Hdat = []
Sdat = []
Vdat = []
for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()) :
h,s,v = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)
Hdat.append(int(h*255.))
Sdat.append(int(s*255.))
Vdat.append(int(v*255.))
r.putdata(Hdat)
g.putdata(Sdat)
b.putdata(Vdat)
return Image.merge('RGB',(r,g,b))
else:
return None
def test_rgb2hsv_conversion(self):
rgb = img_as_float(self.img_rgb)[::16, ::16]
hsv = rgb2hsv(rgb).reshape(-1, 3)
# ground truth from colorsys
gt = np.array([colorsys.rgb_to_hsv(pt[0], pt[1], pt[2])
for pt in rgb.reshape(-1, 3)]
)
assert_almost_equal(hsv, gt)
def test_hsv2rgb_conversion(self):
rgb = self.img_rgb.astype("float32")[::16, ::16]
# create HSV image with colorsys
hsv = np.array([colorsys.rgb_to_hsv(pt[0], pt[1], pt[2])
for pt in rgb.reshape(-1, 3)]).reshape(rgb.shape)
# convert back to RGB and compare with original.
# relative precision for RGB -> HSV roundtrip is about 1e-6
assert_almost_equal(rgb, hsv2rgb(hsv), decimal=4)
def hue(self):
return colorsys.rgb_to_hsv(self.__rgb[0] / 0xFF,
self.__rgb[1] / 0xFF,
self.__rgb[2] / 0xFF)[0]
def saturation(self):
return colorsys.rgb_to_hsv(self.__rgb[0] / 0xFF,
self.__rgb[1] / 0xFF,
self.__rgb[2] / 0xFF)[1]
def value(self):
return colorsys.rgb_to_hsv(self.__rgb[0] / 0xFF,
self.__rgb[1] / 0xFF,
self.__rgb[2] / 0xFF)[2]
def rgb_updated(self, value):
# Update the interface after RBG change.
r = self.r_scale['value']
g = self.g_scale['value']
b = self.b_scale['value']
self.update_rgb(r, g, b)
h, s, v = colorsys.rgb_to_hsv(r, g, b)
self.update_hsv(h, s, v)
self.update_color_area()
def convertRgbToHsv(rgb):
"""Converts rgb values to hsv
rgb is in 0-1 range, hsv is in (0-360, 0-1, 0-1) ranges
:return hsv: Red Green Blue values 0-1
:rtype hsv: list
:param rgb: Hue Saturation Value Hue is in 0-360 range, Sat/Value 0-1 range
:type rgb: list
"""
hsv = list(colorsys.rgb_to_hsv((rgb[0]), rgb[1], rgb[2]))
hsv[0] *= 360.0
return hsv