Beispiel #1
0
def rgb_shader(t,
               t_min=0,
               t_max=1,
               color1=(0.94, 0.02, 0.55),
               color2=(0.11, 0.78, 0.72)):
    """
    Linear interpolation between 2 colors `color1` and `color2`
    :param t: variable
    :param t_min: lower bound of variable `t`
    :param t_max: upper bound of variable `t`
    :param color1: hex or float color in RGB
    :param color2: hex or float color in RGB
    :return: float color in RGB
    """
    # proportion of `t`
    t = (t - t_min) / (t_max - t_min)
    # if input colors are hex strings, convert them to float triples
    if isinstance(color1, str):
        color1 = hex2float(color1)
    if isinstance(color2, str):
        color2 = hex2float(color2)
    # convert `color1` and `color2` to yiq space for better gradient visuals
    color1 = cs.rgb_to_yiq(*color1)
    color2 = cs.rgb_to_yiq(*color2)
    # return color at `t` using linear interpolation
    return cs.yiq_to_rgb(
        *[t * c2 + (1.00 - t) * c1 for (c1, c2) in zip(color1, color2)])
Beispiel #2
0
def close_color(rgb1, rgb2):
    """xls colors are mapped using a color palette which doesn't accurately represent the
    colors in the spreadsheet, e.g. the color for a BAD formatted cell is off.  Here we
    see if the color they picked is close enough to the actual color to say we passed the test.
    Note: Somehow Excel is able to figure out the real color that was used in a xls file,
    but xlrd and OpenOffice are not, so it's undocumented!"""
    # See also: https://bz.apache.org/ooo/show_bug.cgi?id=110667

    if rgb1 is None or isinstance(rgb1, RGB):  # None is black
        rgb1 = '0'
    if rgb2 is None or isinstance(rgb2, RGB):
        rgb2 = '0'
    rgb1 = int(rgb1, 16) & 0xffffff
    rgb2 = int(rgb2, 16) & 0xffffff
    if rgb1 == rgb2:
        return True
    yiq1 = colorsys.rgb_to_yiq((rgb1 >> 24) & 0xff, (rgb1 >> 16) & 0xff,
                               rgb1 & 0xff)
    yiq2 = colorsys.rgb_to_yiq((rgb2 >> 24) & 0xff, (rgb2 >> 16) & 0xff,
                               rgb2 & 0xff)
    MAX_LUMA_DISTANCE = 6
    MAX_IN_PHASE_DISTANCE = 32
    MAX_QUADRATURE_DISTANCE = 55
    if abs(yiq1[0]-yiq2[0]) < MAX_LUMA_DISTANCE and \
       abs(yiq1[1]-yiq2[1]) < MAX_IN_PHASE_DISTANCE and \
       abs(yiq1[2]-yiq2[2]) < MAX_QUADRATURE_DISTANCE:
        return True
    print(
        f'rgb1 = {rgb1:06x}, yiq1 = {yiq1}, rgb2 = {rgb2:06x}, yiq2 = {yiq2}')
    return False
Beispiel #3
0
def NearestColorIndicesYIQ(c):
	yiq = colorsys.rgb_to_yiq(c[0] * cf, c[1] * cf, c[2] * cf)
	mind0 = 100000000
	mind1 = 100000000
	i0 = 16
	i1 = 16
	for i in range(0, 16):
		yiq2 = colorsys.rgb_to_yiq(colors[i][0] * cf, colors[i][1] * cf, colors[i][2] * cf)
		a0 = yiq[0] - yiq2[0]
		# a0 *= 2.0 # * 2, weil von 0...1, IQ aber -1...1, fixme test - wird aber eher schlechter, mit 0.5 wirds eher besser
		a1 = yiq[1] - yiq2[1]
		a2 = yiq[2] - yiq2[2]
		d = math.sqrt(a0*a0+a1*a1+a2*a2)
		if math.sqrt(yiq[1]*yiq[1] + yiq[2]*yiq[2]) < 0.01 and i not in cigrey:	# fixme Test: Grauwerte nur auf Grau mappen
			d = 10000000
		if d < mind0:
			i1 = i0
			mind1 = mind0
			i0 = i
			mind0 = d
		elif d < mind1:
			i1 = i
			mind1 = d
	# Faktor berechnen
	f = mind0 / (mind0 + mind1)
	return (i0, i1, f)
Beispiel #4
0
def pixel_sort(input_img, target_img, verbose=True):
    if verbose:
        print('Sorting pixels...')

    height, width, _ = target_img.shape
    row_indices = np.array([[i] * width for i in range(height)])
    col_indices = np.array([range(width) for i in range(height)])
    row_indices = np.reshape(row_indices, [height, width, 1])
    col_indices = np.reshape(col_indices, [height, width, 1])

    luma_input = np.apply_along_axis(lambda x: rgb_to_yiq(*x)[0], 2, input_img)
    luma_input = np.reshape(luma_input, [height, width, 1])
    luma_input = np.concatenate([luma_input, row_indices, col_indices], axis=2)
    luma_input = np.reshape(luma_input, [-1, 3])
    luma_input = luma_input[luma_input[:, 0].argsort()]

    luma_target = np.apply_along_axis(lambda x: rgb_to_yiq(*x)[0], 2,
                                      target_img)
    luma_target = np.reshape(luma_target, [height, width, 1])
    luma_target = np.concatenate([luma_target, row_indices, col_indices],
                                 axis=2)
    luma_target = np.reshape(luma_target, [-1, 3])
    luma_target = luma_target[luma_target[:, 0].argsort()]

    output_img = np.zeros([height, width, 3])
    for i in range(luma_target.shape[0]):
        output_img[int(luma_target[i,1]),int(luma_target[i,2]),:] = \
         input_img[int(luma_input[i,1]),int(luma_input[i,2]),:]
    return output_img.astype('uint8')
Beispiel #5
0
def get_combined_yuv(test_image, mark_image):
    channel_Y, _, _ = colorsys.rgb_to_yiq(test_image[:, :, 0],
                                          test_image[:, :, 1], test_image[:, :,
                                                                          2])
    _, channel_U, channel_V = colorsys.rgb_to_yiq(mark_image[:, :, 0],
                                                  mark_image[:, :, 1],
                                                  mark_image[:, :, 2])
    return channel_Y, channel_U, channel_V
    def YIQ_to_RGB(self, components):

        # same comments as above apply
        I_max = colorsys.rgb_to_yiq(1, 0, 0)[1]
        Q_max = colorsys.rgb_to_yiq(1, 0, 1)[2]
        normalised = tuple(x / u for x, u in zip(components, self.supported_colour_models['YIQ'].maximum))
        normalised = (normalised[0], normalised[1] * I_max, normalised[2] * Q_max)
        changed = colorsys.yiq_to_rgb(*normalised)
        denormalised = [l + x * (u - l) for x, l, u in zip(changed, self.supported_colour_models['RGB'].minimum, self.supported_colour_models['RGB'].maximum)]
        return [round(item) for item in denormalised]
Beispiel #7
0
def if_darker(ArregloImagen1,ArregloImagen2,ancho,alto,RGBnuevo,RGBnormalizado1,RGBnormalizado2,YIQ_1,YIQ_2,YIQ):
    for x in range(ancho):
        for y in range(alto):
            YIQ_1[x,y,:]=cs.rgb_to_yiq(RGBnormalizado1[x,y,0],RGBnormalizado1[x,y,1],RGBnormalizado1[x,y,2])               
            YIQ_2[x,y,:]=cs.rgb_to_yiq(RGBnormalizado2[x,y,0],RGBnormalizado2[x,y,1],RGBnormalizado2[x,y,2])
                        
            if YIQ_1[x,y,0]<=YIQ_2[x,y,0]:
                YIQ=YIQ_1
            else:
                YIQ=YIQ_2
                        
            RGBnuevo[x,y]=cs.yiq_to_rgb(YIQ[x,y,0],YIQ[x,y,1],YIQ[x,y,2])
    plt.imshow(RGBnuevo)
    plt.imsave('if_darker.jpg',RGBnuevo)   
    def RGB_to_YIQ(self, components):

        # this colour model is somewhat weird: the components can be negative
        #      0.0000 ≤ Y ≤ 1.0000
        #     -0.5990 ≤ I ≤ 0.5990
        #     -0.5251 ≤ Q ≤ 0.5251
        # after using library function, modify them to be in range: -1 to 1
        # magnitude of maximum and minimum values of `I' and `Q' must be same
        # otherwise, this conversion will not work
        I_max = colorsys.rgb_to_yiq(1, 0, 0)[1]
        Q_max = colorsys.rgb_to_yiq(1, 0, 1)[2]
        normalised = ((x - l) / (u - l) for x, l, u in zip(components, self.supported_colour_models['RGB'].minimum, self.supported_colour_models['RGB'].maximum))
        changed = colorsys.rgb_to_yiq(*normalised)
        changed = (changed[0], changed[1] / I_max, changed[2] / Q_max)
        denormalised = [x * u for x, u in zip(changed, self.supported_colour_models['YIQ'].maximum)]
        return [round(item) for item in denormalised]
Beispiel #9
0
def my_rgb_to_yiq(colorsystem_scale_factor, r,g,b): 
    y,i,q = colorsys.rgb_to_yiq(r/255.0,g/255.0,b/255.0)
    return (
        int(y*colorsystem_scale_factor),
        int(linmap(i,-1,1,0,colorsystem_scale_factor)),
        int(linmap(q,-1,1,0,colorsystem_scale_factor))
    )
Beispiel #10
0
    def add_rgb(self, add_val: ColSpaceVal, color_space: str = 'hsv', quiet: bool = True) -> None:
        """
        Add new color to color dictionary. Key will be hex rgb string, value will be original color
        map value or yiq if orig is rgb.

        :param add_val: Three element tuple of color in given color space.
        :param color_space: Name of color space used to generate colors.
        :param quiet: More output if True
        """
        if color_space == 'yiq':
            rgb_tup = colorsys.yiq_to_rgb(*add_val)
            self.maps[1] = 'yiq'
        elif color_space == 'rgb':
            rgb_tup = add_val
            add_val = colorsys.rgb_to_yiq(*add_val)
            self.maps[1] = 'yiq'
        else:
            rgb_tup = colorsys.hsv_to_rgb(*add_val)
            self.maps[1] = 'hsv'

        if rgb_tup[0] < 0 or rgb_tup[1] < 0 or rgb_tup[2] < 0:
            print('RGB error: {}'.format(rgb_tup))
            return

        hex_rgb = '#{:02x}{:02x}{:02x}'.format(int(rgb_tup[0]*255), int(rgb_tup[1]*255), int(rgb_tup[2]*255))
        if not quiet:
            print('rgb: {}, {}: ({:.2f}, {:.2f}, {:.2f})'.format(hex_rgb, self.maps[1], *add_val))
        self.colors.update({hex_rgb: add_val})
        self.counter += 1
        return
Beispiel #11
0
    def background_color(self):
        try:
            hex_color = self.info['background_color']
        except KeyError:
            return TingApp.default_background_color

        try:
            color = _hex_color_to_tuple(hex_color)
        except:
            logging.exception('Failed to parse hex color, using default')
            return TingApp.default_background_color

        # colorsys works with colors between 0 and 1
        fractional_color = _color_multiply(color, 1/255.0)
        y, i, q = colorsys.rgb_to_yiq(*fractional_color)

        if y > 0.6:
            y = 0.6
            fractional_color = colorsys.yiq_to_rgb(y, i, q)
            color = _color_multiply(fractional_color, 255)
            logging.warning(
                'Background color was too bright (white text must be visible on top of this '
                'color), color "%s" was darkened to "%s"' % (hex_color, _tuple_to_hex_color(color)))

        return color
Beispiel #12
0
    def background_color(self):
        try:
            hex_color = self.info['background_color']
        except KeyError:
            return TingApp.default_background_color

        try:
            color = _hex_color_to_tuple(hex_color)
        except:
            logging.exception('Failed to parse hex color, using default')
            return TingApp.default_background_color

        # colorsys works with colors between 0 and 1
        fractional_color = _color_multiply(color, 1 / 255.0)
        y, i, q = colorsys.rgb_to_yiq(*fractional_color)

        if y > 0.6:
            y = 0.6
            fractional_color = colorsys.yiq_to_rgb(y, i, q)
            color = _color_multiply(fractional_color, 255)
            logging.warning(
                'Background color was too bright (white text must be visible on top of this '
                'color), color "%s" was darkened to "%s"' %
                (hex_color, _tuple_to_hex_color(color)))

        return color
Beispiel #13
0
 def test_rgb2yiq_conversion(self):
     rgb = img_as_float(self.img_rgb)[::16, ::16]
     yiq = rgb2yiq(rgb).reshape(-1, 3)
     gt = np.array([colorsys.rgb_to_yiq(pt[0], pt[1], pt[2])
                    for pt in rgb.reshape(-1, 3)]
                   )
     assert_almost_equal(yiq, gt, decimal=2)
 def test_yiq_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.yiq_to_rgb(*colorsys.rgb_to_yiq(*rgb)))
Beispiel #15
0
 def q(self):
     """ Returns the q-value of this color.
     
         :result: q-value of this color.
         :rtype: float
     """
     return colorsys.rgb_to_yiq(self.r, self.g, self.b)[2]
Beispiel #16
0
def rgb2yiq(image):
    """
    Converts image from RGB colorscheme to YIQ.
    """
    return np.array([
        colorsys.rgb_to_yiq(*pixel) for pixel in image.reshape([-1, 3])
    ]).reshape(image.shape)
Beispiel #17
0
 def q(self):  
     """ Returns the q-value of this color.
     
         :result: q-value of this color.
         :rtype: float
     """        
     return colorsys.rgb_to_yiq(self.r,self.g,self.b)[2]
Beispiel #18
0
 async def color(self, ctx, color: discord.Color):
     """Shows some info about provided color"""
     colorrgb = color.to_rgb()
     colorhsv = colorsys.rgb_to_hsv(colorrgb[0], colorrgb[1], colorrgb[2])
     colorhls = colorsys.rgb_to_hls(colorrgb[0], colorrgb[1], colorrgb[2])
     coloryiq = colorsys.rgb_to_yiq(colorrgb[0], colorrgb[1], colorrgb[2])
     colorcmyk = rgb_to_cmyk(colorrgb[0], colorrgb[1], colorrgb[2])
     em = discord.Embed(title=str(color),
                        description="HEX: {}\n"
                                    "RGB: {}\n"
                                    "CMYK: {}\n"
                                    "HSV: {}\n"
                                    "HLS: {}\n"
                                    "YIQ: {}\n"
                                    "int: {}".format(hex(color.value).replace("0x", "#"),
                                                     colorrgb,
                                                     colorcmyk,
                                                     colorhsv,
                                                     colorhls,
                                                     coloryiq,
                                                     color.value),
                        url='http://www.color-hex.com/color/{}'.format(hex(color.value).lstrip('0x')),
                        colour=color,
                        timestamp=ctx.message.created_at)
     em.set_thumbnail(url="https://xenforo.com/rgba.php?r={}&g={}&b={}&a=255"
                      .format(colorrgb[0], colorrgb[1], colorrgb[2]))
     await ctx.send(embed=em)
Beispiel #19
0
def process (img, side):
    """
    Returns YIQ version of the jpeg/png image, which is either in
    RGB or CMYK color space.
    Rescaled
    """
    import colorsys
    img = img.resize((side, side))
    vals = list(img.getdata())
    l = len(vals)

    c1 = np.zeros(shape=(side, side), dtype=float)
    c2 = np.zeros(shape=(side, side), dtype=float)
    c3 = np.zeros(shape=(side, side), dtype=float)

    k = 0
    for i in range(side):
        for j in range(side):
            if k >= l:
                break

            r = float(vals[k][0]) / 255
            g = float(vals[k][1]) / 255
            b = float(vals[k][2]) / 255
            c1[i, j], c2[i, j], c3[i, j] =  colorsys.rgb_to_yiq(r, g, b)
            k += 1

    return c1, c2, c3
Beispiel #20
0
def serialize(rgb, fmt):
    """Convert a tuple of floats to the named output format.
    """
    if (fmt == 'rgb3'):
        return('#%01x%01x%01x' %
              (int(rgb[0]*15), int(rgb[1]*15), int(rgb[2]*15)))
    elif (fmt == 'rgb6'):
        return('#%02x%02x%02x' %
              (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)))
    elif (fmt == 'rgb9'):
        return('#%03x%03x%03x' %
              (int(rgb[0]*4095), int(rgb[1]*4095), int(rgb[2]*4095)))
    elif (fmt == 'rgdDec'):
        return('rgb(%3d, %3d, %3d)' %
              (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255)))
    elif (fmt == 'rgb%'):
        return('rgb(%5.1f%%, %5.1f%%, %5.1f%%)' %
              (rgb[0], rgb[1], rgb[2]))

    elif (fmt == 'hsv'):
        return('hsv(%5.3f%%, %5.3f%%, %5.3f%%)' %
              colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2]))
    elif (fmt == 'hls'):
        return('hls(%5.1f%%, %5.1f%%, %5.1f%%)' %
              colorsys.rgb_to_hls(rgb[0], rgb[1], rgb[2]))
    elif (fmt == 'yiq'):
        return('yiq(%5.1f%%, %5.1f%%, %5.1f%%)' %
              colorsys.rgb_to_yiq(rgb[0], rgb[1], rgb[2]))
    else:
        raise ValueError('Unknown output format "%s".' % (fmt))
Beispiel #21
0
    def python_value(self, value: str) -> namedtuple:
        if value and isinstance(value, str):

            rgb = self.hex2rgb(value.replace("#", ""))
            hls = rgb_to_hls(rgb.red, rgb.green, rgb.blue)
            hsv = rgb_to_hsv(rgb.red, rgb.green, rgb.blue)
            yiq = rgb_to_yiq(rgb.red, rgb.green, rgb.blue)

            hls = namedtuple("HLS", "h l s")(  # Round,default precision huge
                round(hls[0], 2), round(hls[1], 2), round(hls[2], 2))
            hsv = namedtuple("HSV", "h s v")(round(hsv[0],
                                                   2), round(hsv[1], 2),
                                             round(hsv[2], 2))
            yiq = namedtuple("YIQ", "y i q")(round(yiq[0],
                                                   2), round(yiq[1], 2),
                                             round(yiq[2], 2))
            per = lambda val: int(val * 100 / 255)  # Percent, 0~255 > 0~100%

            return namedtuple("Color", "hex rgb hls hsv yiq css css_prcnt")(
                value,
                rgb,
                hls,
                hsv,
                yiq,
                f"rgb({rgb.red},{rgb.green},{rgb.blue})",  # rgb(int, int, int)
                f"rgb({per(rgb.red)}%,{per(rgb.green)}%,{per(rgb.blue)}%)"
            )  # %

        return value
Beispiel #22
0
 async def color(self, ctx, color: discord.Color):
     """Shows some info about provided color"""
     colorrgb = color.to_rgb()
     colorhsv = colorsys.rgb_to_hsv(colorrgb[0], colorrgb[1], colorrgb[2])
     colorhls = colorsys.rgb_to_hls(colorrgb[0], colorrgb[1], colorrgb[2])
     coloryiq = colorsys.rgb_to_yiq(colorrgb[0], colorrgb[1], colorrgb[2])
     colorcmyk = rgb_to_cmyk(colorrgb[0], colorrgb[1], colorrgb[2])
     em = discord.Embed(
         title=str(color),
         description="HEX: {}\n"
         "RGB: {}\n"
         "CMYK: {}\n"
         "HSV: {}\n"
         "HLS: {}\n"
         "YIQ: {}\n"
         "int: {}".format(
             str(color),
             colorrgb,
             colorcmyk,
             colorhsv,
             colorhls,
             coloryiq,
             color.value,
         ),
         url=f"http://www.color-hex.com/color/{str(color)[1:]}",
         colour=color,
         timestamp=ctx.message.created_at,
     )
     em.set_thumbnail(
         url=f"https://api.alexflipnote.dev/color/image/{str(color)[1:]}")
     em.set_image(
         url=
         f"https://api.alexflipnote.dev/color/image/gradient/{str(color)[1:]}"
     )
     await ctx.send(embed=em)
Beispiel #23
0
 def test_rgb2yiq_conversion(self):
     rgb = img_as_float(self.img_rgb)[::16, ::16]
     yiq = rgb2yiq(rgb).reshape(-1, 3)
     gt = np.array([colorsys.rgb_to_yiq(pt[0], pt[1], pt[2])
                    for pt in rgb.reshape(-1, 3)]
                   )
     assert_almost_equal(yiq, gt, decimal=2)
def detectChassis(r, g, b, chassisPic, x, y):
    yiqValues = colorsys.rgb_to_yiq(r, g, b)
    chassisPic.setRGB(x, y, yiqValues[0], yiqValues[1], yiqValues[2])
    yiqPixel = chassisPic.getRGB(x, y)
    if yiqPixel[0] >= 0.580 and yiqPixel[1] >= 0.043 and yiqPixel[2] >= 0.030:
        return True
    else:
        return False
Beispiel #25
0
def compute_features(pyramid):
    features = []
    for i in range(len(pyramid)):
        image = pyramid[i]
        YIQ = colorsys.rgb_to_yiq(image[:, :, 0], image[:, :, 1], image[:, :,
                                                                        2])
        features.append(YIQ[0])
    return features
Beispiel #26
0
 def image_preprocess(self, original, hinted_image):
     """
     Takes original as well as hinted image and performs colorspace conversion.
     :param original: Original grayscale image
     :param hinted_image: Grayscale image with user scrabbles
     :return: Difference image and YIQ (YUV) colorspace image
     """
     original = original.astype(float) / 255
     hinted_image = hinted_image.astype(float) / 255
     colorIm = abs(original - hinted_image).sum(2) > 0.01
     (Y, _, _) = colorsys.rgb_to_yiq(original[:, :, 0], original[:, :, 1], original[:, :, 2])
     (_, I, Q) = colorsys.rgb_to_yiq(hinted_image[:, :, 0], hinted_image[:, :, 1], hinted_image[:, :, 2])
     ntscIm = np.zeros(original.shape)
     ntscIm[:, :, 0] = Y
     ntscIm[:, :, 1] = I
     ntscIm[:, :, 2] = Q
     return colorIm, ntscIm
Beispiel #27
0
def rgbToYiq(color):
    """ Converts the given RGB color to YIQ color system. """

    r = color[0] / 255.0
    g = color[1] / 255.0
    b = color[2] / 255.0

    (y, i, q) = colorsys.rgb_to_yiq(r, g, b)
    return ColorVector((y * 255, i * 255, q * 255))
Beispiel #28
0
def rgb_to_gray_img(im):
    rows = im.shape[0]
    cols = im.shape[1]
    gray_im = np.zeros((rows, cols))
    for r in range(rows):
        for c in range(cols):
            p = im[r, c]
            gray_im[r, c] = colorsys.rgb_to_yiq(p[0], p[1], p[2])[0]
    return gray_im
Beispiel #29
0
def image_preprocess(input_image, hinted_image):

    input_image = input_image.astype(float) / 255
    hinted_image = hinted_image.astype(float) / 255

    color_pixels = abs(input_image - hinted_image).sum(2) > 0.01

    (Y, _, _) = colorsys.rgb_to_yiq(input_image[:, :, 0], input_image[:, :, 1],
                                    input_image[:, :, 2])
    (_, I, Q) = colorsys.rgb_to_yiq(hinted_image[:, :, 0],
                                    hinted_image[:, :, 1], hinted_image[:, :,
                                                                        2])

    YIQ_image = np.zeros(input_image.shape)
    YIQ_image[:, :, 0] = Y
    YIQ_image[:, :, 1] = I
    YIQ_image[:, :, 2] = Q
    return color_pixels, YIQ_image
Beispiel #30
0
 def test_yiq_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.yiq_to_rgb(*colorsys.rgb_to_yiq(*rgb))
                 )
 def transform(self, default_value, add_luma=0.0):
     if self.inverted:
         dy, di, dq = colorsys.rgb_to_yiq(*hex_to_rgb(default_value))
         dy = 1 - dy
         if dy < 0.5:
             dy += add_luma
         r, g, b = colorsys.yiq_to_rgb(dy, di, dq)
         return rgb_to_hex(r, g, b)
     return default_value
Beispiel #32
0
def rgbToYiq(color):
	""" Converts the given RGB color to YIQ color system. """
	
	r = color[0] / 255.0
	g = color[1] / 255.0
	b = color[2] / 255.0
	
	(y, i, q) = colorsys.rgb_to_yiq(r, g, b)
	return ColorVector((y * 255, i * 255, q * 255))
Beispiel #33
0
def rgb_to_gray_img(im):
  rows = im.shape[0]
  cols = im.shape[1]
  gray_im = np.zeros((rows, cols))
  for r in range(rows):
    for c in range(cols):
      p = im[r, c]
      gray_im[r, c] = colorsys.rgb_to_yiq(p[0], p[1], p[2])[0]
  return gray_im
Beispiel #34
0
 def change_color(color):
     rgb = self._html_color_to_rgb(color)
     if not rgb:
         return color
     yiq = colorsys.rgb_to_yiq(*(x / 255.0 for x in rgb))
     if yiq[0] > 0.5:
         rgb = self._change_brightness(color, float(1 - (yiq[0] - 0.5)))
         return self._rgb_to_html_color(*rgb)
     return color
Beispiel #35
0
 async def color(self, ctx, *, color: discord.Color):
     """Shows some info about provided color."""
     colorrgb = color.to_rgb()
     rgb_coords = [x / 255 for x in colorrgb]
     colorhsv = rgb_to_hsv(*colorrgb)
     h, l, s = colorsys.rgb_to_hls(*rgb_coords)
     colorhls = (colorhsv[0], l * 100, s * 100)
     coloryiq = colorsys.rgb_to_yiq(*rgb_coords)
     colorcmyk = rgb_to_cmyk(*colorrgb)
     colors_text = (
         "`HEX :` {}\n"
         "`RGB :` {}\n"
         "`CMYK:` {}\n"
         "`HSV :` {}\n"
         "`HLS :` {}\n"
         "`YIQ :` {}\n"
         "`Int :` {}".format(
             str(color),
             colorrgb,
             tuple(
                 map(lambda x: isinstance(x, float) and round(x, 2) or x,
                     colorcmyk)),
             tuple(
                 map(lambda x: isinstance(x, float) and round(x, 2) or x,
                     colorhsv)),
             tuple(
                 map(lambda x: isinstance(x, float) and round(x, 2) or x,
                     colorhls)),
             tuple(
                 map(lambda x: isinstance(x, float) and round(x, 2) or x,
                     coloryiq)),
             color.value,
         ))
     em = discord.Embed(
         title=str(color),
         description=_("`Name:` Loading...\n") + colors_text,
         url=f"http://www.color-hex.com/color/{str(color)[1:]}",
         colour=color,
         timestamp=ctx.message.created_at,
     )
     # CAUTION: That can fail soon
     em.set_thumbnail(
         url=f"https://api.alexflipnote.dev/color/image/{str(color)[1:]}")
     em.set_image(
         url=
         f"https://api.alexflipnote.dev/color/image/gradient/{str(color)[1:]}"
     )
     m = await ctx.send(embed=em)
     async with self.session.get("https://www.thecolorapi.com/id",
                                 params={"hex": str(color)[1:]}) as data:
         color_response = await data.json(loads=json.loads)
         em.description = (_("`Name:` {} ({})\n").format(
             color_response.get("name", {}).get("value", "?"),
             color_response.get("name", {}).get("closest_named_hex", "?"),
         ) + colors_text)
     await m.edit(embed=em)
Beispiel #36
0
def comput_pdfs(imfile, imfile_scrib):
    '''
    compute foreground and background pdfs
    :param imfile: input file
    :param imfile_scrib: input file with user scrib
    :return:
    '''
    rgb = mpimg.imread(imfile)[:, :, :3]    #read the img
    yuv = colorsys.rgb_to_yiq(rgb)
    R = mpimg.imread(imfile)[:, :, 1]   #read the red channel
Beispiel #37
0
def interpolacion_yiq(ArregloImagen1,ArregloImagen2,ancho,alto,RGBnuevo,RGBnormalizado1,RGBnormalizado2,YIQ_1,YIQ_2,YIQ):
    for x in range(ancho):
        for y in range(alto):           
            
            YIQ_1[x,y,:]=cs.rgb_to_yiq(RGBnormalizado1[x,y,0],RGBnormalizado1[x,y,1],RGBnormalizado1[x,y,2])               
            YIQ_2[x,y,:]=cs.rgb_to_yiq(RGBnormalizado2[x,y,0],RGBnormalizado2[x,y,1],RGBnormalizado2[x,y,2])
                        
            if  YIQ_1[x,y,0]+YIQ_2[x,y,0] != 0:
                YIQ[x,y,0]=(YIQ_1[x,y,0]+YIQ_2[x,y,0])/2
                YIQ[x,y,1]=(YIQ_1[x,y,0]*YIQ_1[x,y,1]+YIQ_2[x,y,0]*YIQ_2[x,y,1])/(YIQ_1[x,y,0]+YIQ_2[x,y,0])
                YIQ[x,y,2]=(YIQ_1[x,y,0]*YIQ_1[x,y,2]+YIQ_2[x,y,0]*YIQ_2[x,y,2])/(YIQ_1[x,y,0]+YIQ_2[x,y,0])             
            else:
                YIQ[x,y,0]=0
                YIQ[x,y,1]=0
                YIQ[x,y,2]=0
            
            RGBnuevo[x,y]=cs.yiq_to_rgb(YIQ[x,y,0],YIQ[x,y,1],YIQ[x,y,2])
    plt.imshow(RGBnuevo)
    plt.imsave('interpolacion_yiq.jpg',RGBnuevo)                
Beispiel #38
0
 def rgb_to_others(self):
     """
     converts RGB tuple to:
         HLS (Hue Lightness Saturation)
         HSV (Hue Saturation Value)
         YIQ"""
     import colorsys
     r, g, b = [i / self.rgb_scale for i in self.rgb]
     self.hls = colorsys.rgb_to_hls(r, g, b)
     self.hsv = colorsys.rgb_to_hsv(r, g, b)
     self.yiq = colorsys.rgb_to_yiq(r, g, b)
Beispiel #39
0
    def sort(self, space='hsv'):
        conversions = {
            'rgb': lambda x: x,
            'hsv': lambda x: colorsys.rgb_to_hsv(*x),
            'hls': lambda x: colorsys.rgb_to_hls(*x),
            'yiq': lambda x: colorsys.rgb_to_yiq(*x),
        }

        self.colours = sorted(self.colours,
                              key=lambda x: conversions[space](x))
        return self.colours
 def rgb_to_others(self):
     """
     converts RGB tuple to:
         HLS (Hue Lightness Saturation)
         HSV (Hue Saturation Value)
         YIQ"""
     import colorsys
     r,g,b = [i/self.rgb_scale for i in self.rgb]
     self.hls =  colorsys.rgb_to_hls(r,g,b)
     self.hsv = colorsys.rgb_to_hsv(r,g,b)
     self.yiq = colorsys.rgb_to_yiq(r,g,b)
Beispiel #41
0
def forceBrightness(color, brightness):
    src_r, src_g, src_b = color
    u = ledstrip.NCOLS - 1
    src_ar = float(src_r) / u
    src_ag = float(src_g) / u
    src_ab = float(src_b) / u

    # converts to yiq and replaces luma (y) with specified brightness
    _y, i, q = colorsys.rgb_to_yiq(src_ar, src_ag, src_ab)
    dst_ar, dst_ag, dst_ab = colorsys.yiq_to_rgb(brightness, i, q)

    return (int(round(dst_ar * u)), int(round(dst_ag * u)), int(round(dst_ab * u)))
Beispiel #42
0
def rgbtoyiq(rgb):
	"""
	Convert the given colour in RGB space to YIQ space

	Argument is a 3-tuple of float RGB values in the range 0~1.
	Return a 3-tuple of float YIQ values in the range (0~1, -1~1, -1~1).
	"""
	if len(rgb) != 3:
		raise ValueError("expected a 3-tuple")
	for i in rgb:
		if i < 0 or i > 1:
			raise ValueError("expected values in the range 0~1")
	return colorsys.rgb_to_yiq(*rgb)
Beispiel #43
0
def test_yiq3():
    a = [0,0,0,0,0,0]
    a[0] = [145, 149, 152]
    a[1] = [151, 155, 158]
    a[2] = [127, 131, 134]
    a[3] = [86, 90, 93]
    a[4] = [61, 66, 70]
    a[5] = [57, 62, 2]

    #s = np.array([145.0, 149.0, 152.0])/255
    s = np.asarray(a, dtype='float')/255
    s2 = np.random.random(s.shape)
    s3 = np.asarray([s,s2], dtype='float')
    print s3.shape
    tranform = np.array([[0.299, 0.587, 0.114], [0.596, -0.275, -0.321], [0.212, -0.523, 0.311]])
    y = s[0][0]*0.299 + s[0][1]*0.587 + s[0][2]*0.114
    z = np.array([tranform[0][0], tranform[1][0], tranform[2][0]])
    print y
    print colorsys.rgb_to_yiq(*s[-1])
    #print tranform[0], np.dot(s, z)
    #print s
    #print tranform
    print np.dot(s3, tranform.T)
Beispiel #44
0
def get_best_same_color_text(web_hex_str, lum_min=0.1):
    '''Returns biggest YIQ contrast'''
    r,g,b = hex_to_rgb(web_hex_str)
    r,g,b = scale_rgb_tuple((r,g,b), down=True)

    y,i,q =  colorsys.rgb_to_yiq( r,g,b )
    if y>0.5:
        rgb_float = colorsys.yiq_to_rgb(lum_min,i,q)
    else:
        rgb_float = colorsys.yiq_to_rgb(1.0-lum_min,i,q)

    #print 'y,i,q=',y,i,q, '    rgb_float=',rgb_float

    return rgbfloat_to_hex(rgb_float)
Beispiel #45
0
def test_yiq():
    a = [0,0,0,0,0,0]
    a[0] = (145, 149, 152)
    a[1] = (151, 155, 158)
    a[2] = (127, 131, 134)
    a[3] =(86, 90, 93)
    a[4] = (61, 66, 70)
    a[5] = (57, 62, 2)
    for nn in a:
        n = [float(m)/255 for m in nn]
        yiq = colorsys.rgb_to_yiq(*n)
        #r = (int(yiq[0]),int(yiq[1]),int(yiq[2]))
        rgb = colorsys.yiq_to_rgb(*yiq)
        r = (int(rgb[0]*255), int(rgb[1]*255), int(rgb[2]*255))
        print n, yiq, colorsys.yiq_to_rgb(*yiq), r, nn
Beispiel #46
0
 def test_yiq_values(self):
     values = [
         # rgb, yiq
         ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)), # black
         ((0.0, 0.0, 1.0), (0.11, -0.3217, 0.3121)), # blue
         ((0.0, 1.0, 0.0), (0.59, -0.2773, -0.5251)), # green
         ((0.0, 1.0, 1.0), (0.7, -0.599, -0.213)), # cyan
         ((1.0, 0.0, 0.0), (0.3, 0.599, 0.213)), # red
         ((1.0, 0.0, 1.0), (0.41, 0.2773, 0.5251)), # purple
         ((1.0, 1.0, 0.0), (0.89, 0.3217, -0.3121)), # yellow
         ((1.0, 1.0, 1.0), (1.0, 0.0, 0.0)), # white
         ((0.5, 0.5, 0.5), (0.5, 0.0, 0.0)), # grey
     ]
     for (rgb, yiq) in values:
         self.assertTripleEqual(yiq, colorsys.rgb_to_yiq(*rgb))
         self.assertTripleEqual(rgb, colorsys.yiq_to_rgb(*yiq))
Beispiel #47
0
def _add_numbers(ax, matrix, image, threshold=0.25):
    """
    Add the value of the correlation in each cell as text.
    Boxes with overall brightness lower than `threshold` are colored
    white.
    """
    maxval = np.max(matrix[matrix < 1.0])
    minval = np.min(matrix)
    valrg = maxval - minval
    text_args = dict(fontsize=6, ha='center', va='center')
    for binx, biny in _xyiter(matrix):
        val = matrix[binx, biny]
        # use white in the dark squares
        rgb = image.to_rgba(val)[:3]
        greyval = colorsys.rgb_to_yiq(*rgb)[0]
        col = 'w' if greyval < threshold else 'k'
        ax.text(binx, biny, '{:.0f}'.format(val*100), color=col, **text_args)
Beispiel #48
0
def rgb2yiq(rgb):
    r,g,b=rgb
    y,i,q=colorsys.rgb_to_yiq(r/255.0,g/255.0,b/255.0)
    return map(lambda x: int(round(x*100.0)),[y,i,q])
Beispiel #49
0
 def yiq(self):
     """
     Returns a 3-tuple of (y, i, q) float values; y values can be between
     0.0 and 1.0, whilst i and q values can be between -1.0 and 1.0.
     """
     return colorsys.rgb_to_yiq(self.red, self.green, self.blue)
Beispiel #50
0
print 1==0j, 0.0==0j, 1.0==0j, 0j==0.0

#colorsys
import colorsys

print '%.2f' % colorsys.ONE_THIRD
print '%.2f' % colorsys.ONE_SIXTH
print '%.2f' % colorsys.TWO_THIRD

def pr(t):
    print [('%.2f'%x) for x in t]

pr(colorsys.hls_to_rgb(1.0, 0.5, 0.7))
pr(colorsys.rgb_to_hls(1.0, 0.5, 0.7))
pr(colorsys.yiq_to_rgb(1.0, 0.5, 0.7))
pr(colorsys.rgb_to_yiq(1.0, 0.5, 0.7))
pr(colorsys.hsv_to_rgb(1.0, 0.5, 0.7))
pr(colorsys.rgb_to_hsv(1.0, 0.5, 0.7))

#equality
t1 = ('rc', (0, 0)) 
t2 =('rc', (0, 0) )
print t1!=t2
print t1==t2
print {(3,2): 0} == {(3,2): 1}

#generator and arg unpacking
def genpack((i,j),a,b):
    yield i
    yield j
    yield a
def hex_to_yiq(color):
    return colorsys.rgb_to_yiq(*hex_to_rgb(color))
	def fromRGBA(self, rgba):
		return list(colorsys.rgb_to_yiq(rgba[0], rgba[1], rgba[2]))
Beispiel #53
0
def to_yiq(v, i):
    return rgb_to_yiq(*v[:-1])
 def yqi(x):
     to_float = lambda x : x / 255.0
     (r, g, b) = map(to_float, x)
     y, i, q = colorsys.rgb_to_yiq(r,g,b)
     y = y if 0 < y else 1 # 0 -> 1
     return y, q, i
Beispiel #55
0
def RGBToYIQ(red, green, blue):
    return colorsys.rgb_to_yiq(
        float(red) / 0xff, float(green) / 0xff, float(blue) / 0xff)
	start_time = time.time()

	# convert images to YIQ
	A_YIQ = np.zeros(imageA.shape, dtype=np.float32)
	A_prime_YIQ = np.zeros(imageA.shape, dtype=np.float32)
	B_YIQ = np.zeros([heightB,widthB,3], dtype=np.float32)
	B_Y = np.zeros(imageB.shape[0:2], dtype=np.float32)
	A_Y = np.zeros(imageA.shape[0:2], dtype=np.float32)
	A_prime_Y = np.zeros(imageA.shape[0:2], dtype=np.float32)

	for i in xrange(heightA):
		for j in xrange(widthA):
			colors = imageA[i,j]/255.
			colorsp = imageA_prime[i,j]/255.
			YIQA = colorsys.rgb_to_yiq(colors[0],colors[1],colors[2])
			YIQA_prime = colorsys.rgb_to_yiq(colorsp[0],colorsp[1],colorsp[2])
			A_YIQ[i,j] = YIQA
			A_Y[i,j] = YIQA[0]
			A_prime_YIQ[i,j] = YIQA_prime 
			A_prime_Y[i,j] = YIQA_prime[0]

	for i in xrange(heightB):
		for j in xrange(widthB):
			colors = imageB[i,j]/255.
			YIQB = colorsys.rgb_to_yiq(colors[0],colors[1],colors[2])
			B_YIQ[i,j] = YIQB
			B_Y[i,j] = YIQB[0]

	stop_time = time.time()
	print "RGB to YIQ conversion complete"
Beispiel #57
0
#!/usr/bin/env python

import Image, sys, colorsys

filename = sys.argv[1]
im = Image.open(filename)
px = list(im.getdata())
px = map(lambda (r,g,b): (r/255.0, g/255.0, b/255.0), px)
px = map(lambda p: colorsys.rgb_to_yiq(*p), px)
px = sorted(px)
px = map(lambda p: colorsys.yiq_to_rgb(*p), px)
px = map(lambda (r,g,b): (int(r*255.0), int(g*255.0), int(b*255.0)), px)
im.putdata(px)
im.save("new" + filename)
Beispiel #58
0
    def genBuff(self):
        width = self.get_size()
        self.modwidth = width
        darkmulti = (1 - self.darkness / 10)

        #logger.info(darkmulti)
        hh = [0.2, 0.4, 0.7, 0.8, 0.9, 1, 1, 0.98, 0.93, 0.85, 0.80, 0.80,
              0.80, 0.85, 0.93, 0.98, 1, 1, 0.9, 0.8, 0.7, 0.6, 0.4, 0.2]
        #hh=[0.5,0.55,0.6,0.65,0.7,1,0.95,0.92,0.88,0.84,0.80,0.80,
        #0.80,0.84,0.88,0.92,0.95,1,0.7,0.65,0.6,0.55,0.5,0.45]
        #hh=[0.2,0.4,0.7,0.8,0.9,1,1,1,1,1,1,1,1,1,1,1,1,1,0.9,0.8,
        # 0.7,0.6,0.4,0.2]
        self.defaultstyle_old = self.defaultstyle
        self.theme_old = self.theme
        self.flat_old = self.flat
        self.color_old = self.color
        self.darkness_old = self.darkness
        self.cursor_old = self.cursor
        gc = self.brush
        self.bgcolor = self.mod.style.bg[gtk.STATE_NORMAL]
        redf = self.bgcolor.red / 255
        greenf = self.bgcolor.green / 255
        bluef = self.bgcolor.blue / 255
        colortheme = gtk.gdk.Color(self.color)
        c1, self.ivalue, self.qvalue = colorsys.rgb_to_yiq(
            float(colortheme.red) / 256 / 256, float(colortheme.green) / 256 /
            256, float(colortheme.blue) / 256 / 256)
        gc.foreground = self.bgcolor
        gc.line_width = 1
        self.pixmap = gtk.gdk.Pixmap(self.mod.window, width, 24)
        self.pixmap2 = gtk.gdk.Pixmap(self.mod.window, width, 24)
        self.pixmap.draw_rectangle(gc, True, 0, 0, self.modwidth, 24)
        self.pixmap2.draw_rectangle(gc, True, 0, 0, self.modwidth, 24)
        if self.flat:
            if self.theme:
                flatcolor1r = float(colortheme.red) / 256 / 256
                flatcolor1g = float(colortheme.green) / 256 / 256
                flatcolor1b = float(colortheme.blue) / 256 / 256
                flatcolor2r = darkmulti * float(colortheme.red) / 256 / 256
                flatcolor2g = darkmulti * float(colortheme.green) / 256 / 256
                flatcolor2b = darkmulti * float(colortheme.blue) / 256 / 256
            else:
                flatcolor1r = flatcolor1g = flatcolor1b = 0.5
                flatcolor2r = flatcolor2g = flatcolor2b = 0.5 * darkmulti
        #render ---------------------------------------------------------
        for x in range(width):
            #reading color
            r = float(ord(self.moodbar[int(x * 1000 / width) * 3])) / 256
            g = float(ord(self.moodbar[int(x * 1000 / width) * 3 + 1])) / 256
            b = float(ord(self.moodbar[int(x * 1000 / width) * 3 + 2])) / 256
            if (self.theme or self.defaultstyle):
                c1, c2, c3 = colorsys.rgb_to_yiq(r, g, b)

            if (self.theme):
                c2 = c2 + self.ivalue
                if c2 > 1: c2 = 1
                if c2 < -1: c2 = -1
                c3 = c3 + self.qvalue
                if c3 > 1: c3 = 1
                if c3 < -1: c3 = -1
            if self.defaultstyle:
                r, g, b = colorsys.yiq_to_rgb(0.5, c2, c3)
                waluelength = int(c1 * 24)
            else:
                if self.theme:
                    r, g, b = colorsys.yiq_to_rgb(c1, c2, c3)
            if not self.defaultstyle:
                buff = ''
                for h in range(24):
                    buff = buff + chr(int(r * 255 * hh[h] + redf * (
                        1 - hh[h]))) + chr(int(g * 255 * hh[h] + greenf *
                                               (1 - hh[h]))) + chr(int(
                                                   b * 255 * hh[h] + bluef *
                                                   (1 - hh[h])))
                self.pixmap.draw_rgb_image(gc, x, 0, 1, 24,
                                           gtk.gdk.RGB_DITHER_NONE, buff, 3)

                if self.cursor:
                    buff2 = ''
                    for h in range(24 * 3):
                        buff2 = buff2 + chr(int(ord(buff[h]) *
                                                (darkmulti + (1 - darkmulti) *
                                                 (1 - hh[int(h / 3)]))))

                    self.pixmap2.draw_rgb_image(gc, x, 0, 1, 24,
                                                gtk.gdk.RGB_DITHER_NONE, buff2,
                                                3)

            else:
                if self.flat:
                    gc.foreground = self.mod.get_colormap().alloc_color(
                        int(flatcolor1r * 0xFFFF), int(flatcolor1g * 0xFFFF),
                        int(flatcolor1b * 0xFFFF))
                else:
                    gc.foreground = self.mod.get_colormap().alloc_color(
                        int(r * 0xFFFF), int(g * 0xFFFF), int(b * 0xFFFF))
                self.pixmap.draw_line(gc, x, 13 - waluelength, x,
                                      12 + waluelength)

                if self.cursor:
                    if self.flat:
                        gc.foreground = self.mod.get_colormap().alloc_color(
                            int(flatcolor2r * 0xFFFF),
                            int(flatcolor2g * 0xFFFF),
                            int(flatcolor2b * 0xFFFF))
                    else:
                        r, g, b = colorsys.yiq_to_rgb(0.5 * darkmulti, c2, c3)
                        gc.foreground = self.mod.get_colormap().alloc_color(
                            int(r * 0xFFFF), int(g * 0xFFFF), int(b * 0xFFFF))
                    self.pixmap2.draw_line(gc, x, 13 - waluelength, x,
                                           12 + waluelength)

        #if not self.defaultstyle:
        #    self.pixmap2.draw_drawable(gc,self.pixmap, 0, 0, 0, 0, self.modwidth, 24)
        #    gc.foreground = self.mod.get_colormap().alloc_color(
        #                int(0xCCCC*darkmulti),  int(0xCCCC*darkmulti),  int(0xCCCC*darkmulti))
        #    gc.function=gtk.gdk.AND
        #    self.pixmap2.draw_rectangle(gc, True, 0, 0, self.modwidth, 24)
        #    gc.function=gtk.gdk.COPY
        return b
Beispiel #59
0
def inv_grey(r, g, b):
	y, i, q = colorsys.rgb_to_yiq(r, g, b)
	return y, 0, 0
Beispiel #60
0
def inv_yiq(r, g, b):
	y, i, q = colorsys.rgb_to_yiq(r, g, b)
	return y, i/1.2 + 0.5, q + 0.5