我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorsys.rgb_to_hsv()。
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
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 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 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 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 _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
def tohsv(self): """Convert to HSV color format.""" return rgb_to_hsv(self.r * RGB_CHANNEL_SCALE, self.g * RGB_CHANNEL_SCALE, self.b * RGB_CHANNEL_SCALE)
def recolor(tree, add): """ Recursive part of recolor_strokes and recolor_background """ for child in tree: if 'style' in child.attrib: styles = { a : b for (a, b) in ( x.split(":", 1) for x in child.attrib['style'].split(';') if ":" in x )} if "fill" in styles or "stroke" in styles: for key in ("fill", "stroke"): if key in styles: # Convert color to HSV r,g,b,a = html_to_rgb(styles[key]) h,s,v = colorsys.rgb_to_hsv(r,g,b) # Shift hue h += add while h > 1.0 : h -= 1.0 # Convert it back r,g,b = colorsys.hsv_to_rgb(h,s,v) # Store styles[key] = rgb_to_html(r,g,b) child.attrib["style"] = ";".join(( ":".join((x,styles[x])) for x in styles )) recolor(child, add) # Generate different colors for controller icons
def fzero_fountain(start_col=16, color=(0, 255, 255), border_color=(255, 0, 0), border_thickness=10, height=50): """ F-Zero Launcher - make a f-zero speed boost arrow around the start_col """ # get 5 pixels to either side to select the 11 columns in this section cols = map(lambda c: c % STATE.layout.columns, range(start_col - 5, start_col + 5 + 1)) # group them by levels to make an f-zero speed boost arrow levels = [[cols[5]], [cols[4], cols[6]], [cols[3], cols[7]], [cols[2], cols[8]], [cols[1], cols[9]], [cols[0], cols[10]]] def make_line((i, col)): # fade the colors on the edges def get_color(): hsv = colorsys.rgb_to_hsv(color[0] // 255, color[1] // 255, color[2] // 255) rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2] - (i * 0.12)) return (rgb[0] * 255, rgb[1] * 255, rgb[2] * 255) return RisingLine( height=height, start_col=col, delay=i * 80, color=get_color(), border_color=border_color, border_thickness=border_thickness)
def _rgb2hs(self, rgb): r = rgb[0] / 255.0 g = rgb[1] / 255.0 b = rgb[2] / 255.0 h, s, v = colorsys.rgb_to_hsv(r, g, b) h = int(self._mapRange(h, 0.0, 1.0, 0, 65535)) s = int(self._mapRange(s, 0.0, 1.0, 0, 254)) return (h, s)
def _get_mark(self): """color of the glyph box in the font view. This accepts a 6 hex digit number. XXX the FL implementation accepts a """ import colorsys r = (self._object.color&0xff0000)>>16 g = (self._object.color&0xff00)>>8 g = (self._object.color&0xff)>>4 return colorsys.rgb_to_hsv( r, g, b)[0]
def _get_hsv(hexrgb): hexrgb = hexrgb.lstrip("#") # in case you have Web color specs r, g, b = (int(hexrgb[i:i+2], 16) / 255.0 for i in range(0,5,2)) return colorsys.rgb_to_hsv(r, g, b)
def rgb_to_hsv(red, green, blue): """Convert an RGB tuple to an HSV tuple.""" hue, saturation, value = colorsys.rgb_to_hsv(red/255, green/255, blue/255) return int(hue*360), int(saturation*100), int(value*100)
def test_hsv_roundtrip(self): for r in frange(0.0, 1.0, 0.2): for g in frange(0.0, 1.0, 0.2): for b in frange(0.0, 1.0, 0.2): rgb = (r, g, b) self.assertTripleEqual( rgb, colorsys.hsv_to_rgb(*colorsys.rgb_to_hsv(*rgb)) )
def rgb_to_hsv(r, g, b, a=255): hsv = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0) hsv255 = [int(each * 255) for each in hsv] return hsv255
def brighter(self): if self.highlight: color = [each / 255.0 for each in self.initcolor] hsv = colorsys.rgb_to_hsv(color[0], color[1], color[2]) rgb = colorsys.hsv_to_rgb(hsv[0], 0.2, 1) return [int(each * 255) for each in rgb] else: return self.initcolor
def rgb(self, color): """Set the color of the device, as represented by either a hex string or a list of 0-255 RGB values""" try: red, green, blue = color except ValueError: try: hexcolor = color reg_match = re.match("^([A-Fa-f0-9]{6})$", hexcolor) if reg_match: red = int(hexcolor[:2], 16) green = int(hexcolor[2:-2], 16) blue = int(hexcolor[-2:], 16) else: print("Error: Color must be in valid hex format.") return except ValueError: print("Error: Color must have one hex value or three 0-255 values.") return if not 0 <= red <= 255: print("Error: Red value out of range! (0-255)") return if not 0 <= green <= 255: print("Error: Green value out of range! (0-255)") return if not 0 <= blue <= 255: print("Error: Blue value out of range! (0-255)") return hsv = colorsys.rgb_to_hsv(red / 255, green / 255, blue / 255) hue = int(hsv[0] * 360) saturation = int(hsv[1] * 100) brightness = int(hsv[2] * 100) data = {"hue": {"value": hue}, "sat": {"value": saturation}, "brightness": {"value": brightness}} self.__put("state", data) ########################################### # Layout methods ###########################################
def add_color_to_palette(self): if (self.curr_palette_string.get() == ""): self.palette = [] # this is in case the default palette has already been used in a previous build color = tkColorChooser.askcolor() dprint("New color added to palette", color) rgb_color = color[0] hsv_color = colorsys.rgb_to_hsv(rgb_color[0]/255.0, rgb_color[1]/255.0, rgb_color[2]/255.0) hsv = {"hue": int(hsv_color[0]*360), "saturation": int(hsv_color[1]*100), "brightness": int(hsv_color[2]*100)} self.palette.append(hsv) self.curr_palette_string.set(self.curr_palette_string.get() + json.dumps(hsv) + '\n')
def hwb(self): """Hue, Whiteness, Blackness.""" hsv = colorsys.rgb_to_hsv(self.r, self.g, self.b) h = hsv[0] w = (1.0 - hsv[1]) * hsv[2] b = 1.0 - hsv[2] return [h, w, b]
def rgb2val(rgb, minval, maxval): """ This function converts a rgb of value into its original value with reference to the minimum and maximum value. Parameters ---------- rgb : tuple of floats The rgb value to be converted. minval : float The minimum value of the falsecolour rgb. maxval : float The maximum value of the falsecolour rgb. Returns ------- original value : float The orignal float value. """ hsv = colorsys.rgb_to_hsv(rgb[0],rgb[1],rgb[2]) y = hsv[0]*360 orig_val_part1 = ((-1*y) + 250)/250.0 orig_val_part2 = maxval-minval orig_val = (orig_val_part1*orig_val_part2)+minval return orig_val #======================================================================================================== #OCCTOPOLOGY INPUTS #========================================================================================================
def rgb_to_hsv(r, g ,b): """Convert R(0-255) G(0-255) B(0-255) to H(0-360) S(0-255) V(0-255). """ rgb = [x / 255.0 for x in (r, g, b)] h, s, v = colorsys.rgb_to_hsv(*rgb) return (h * 360, s * 255, v * 255)
def drawContours(self, path): # print("load contours",path) try: self.canvas.delete("contour") except tk.TclError: pass import re self.contours = np.load(path) ex = self.scene["ex"] lf = len(self.contours.files) for a in self.contours.files: cs = self.contours[a] h = int(re.findall('\d+', a)[0]) h /= lf # print("file",a,h) # print("contours",len(cs)) col = colorsys.rgb_to_hsv(0.7, 0.9, 0.85) hue = col[0] - h / 2 hue = m.fmod(hue, 1) col = (hue, max(0, min(col[1], 1)), max(0, min(col[2], 1))) col = colorsys.hsv_to_rgb(*col) hexcol = rgb2hex(col) for c in cs: if len(c): cc = [((x[1] - 512) / 1024 * ex * 2, (x[0] - 512) / 1024 * ex * 2) for x in c] if la.norm(c[-1] - c[0]) < 0.01: self.canvas.create_polygon(cc, fill="", outline=hexcol, width=7, tag="contour") else: self.canvas.create_line(cc, fill=hexcol, width=7, tag="contour") try: self.canvas.tag_lower("contour") except tk.TclError: pass sys.stdout.flush()