Exemple #1
0
    def test_lightness(self):
        a = Color("#abc")
        l = a.hls.l

        b = a.lighter()
        assert a.hls.l < b.hls.l
        assert a.hls.l == l

        b = a.darker()
        assert a.hls.l > b.hls.l
        assert a.hls.l == l
Exemple #2
0
    def test_hsl(self):
        c = Color("#abc")
        self.assertAlmostEqual(c.hsl, (0.5833333333333334,
                                       0.25,
                                       0.7333333333333334))
        assert c.hex == "#aabbcc"

        # Test HSL is relative to RGB working space
        a = Color("#abc", workspace="srgb")
        b = Color("#abc", workspace="linear_rgb")
        self.assertAlmostEqual(a.hsl, b.hsl)
Exemple #3
0
    def test_alpha(self):
        a = Color("#abc", a=0.5)
        assert a.hex == "#aabbcc"
        assert a.css == "rgba(170, 187, 204, 0.50)"
        a.rgb.r = 0.3
        assert a.css == "rgba(77, 187, 204, 0.50)"

        a.a = 1
        assert a.css == "rgb(77, 187, 204)"

        a = Color("#abc", a=0.5, workspace="linear_rgb")
        assert a.hex == "#aabbcc"
        assert a.css == 'rgba(213, 222, 231, 0.50)'
Exemple #4
0
    def test_rgb(self):
        c = Color("#abc")

        # Test value iteration
        assert tuple(c.rgb8) == (170, 187, 204)

        # Test key iteration / access by key
        self.assertAlmostEqual(
            dict(c.rgb8),
            {'r': 170.0, 'b': 204.0, 'g': 187.0})

        # Test access by attribute
        assert c.rgb8.r == 170
        assert c.rgb8.g == 187
        assert c.rgb8.b == 204

        # Check floating RGB
        self.assertAlmostEqual(
            c.rgb,
            (0.6666666666666666, 0.7333333333333333, 0.8))
        self.assertAlmostEqual(
            dict(c.rgb),
            {'r': 0.6666666666666666, 'g': 0.7333333333333333, 'b': 0.8})

        assert c.hex == "#aabbcc"
Exemple #5
0
    def test_contrast(self):
        # Test WCAG luminance ratio contrast test
        a = Color("#000")
        b = Color("#111")
        c = Color("#aaa")

        assert not a.w3_contrast_test(b)
        assert not a.w3_contrast_test(c)
        assert c.w3_contrast_test(a)
Exemple #6
0
 def openToHsv(file):
     img = Image.open(file)
     arr = numpy.zeros(img.size+(3,), dtype=float)
     for v in each_pixel(img):
         try:
             color = Color(rgb8=img.getpixel(v))
             arr[v] = tuple(color.hls)
         except ValueError as e:
             print v,":",img.getpixel(v)
             raise e
     return arr
Exemple #7
0
    def get_colors(self,
                   image_path,
                   num,
                   return_color_counts=False,
                   return_image=False,
                   use_logs=False):
        if num < 2:
            print("The image must have at least 2 colors.")
            return
        image = cv2.imread(image_path, cv2.IMREAD_COLOR)
        (h, w) = image.shape[:2]
        # Convert color spaces
        image = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
        image = image.reshape((image.shape[0] * image.shape[1], 3))
        clusters = MiniBatchKMeans(n_clusters=num)
        labels = clusters.fit_predict(image)
        res = clusters.cluster_centers_.astype("uint8")[labels]
        # To get the colors back to RGB, we must convert to an image and extract the colors
        res = res.reshape((h, w, 3))
        res = cv2.cvtColor(res, cv2.COLOR_LAB2BGR)
        if return_image:
            res_image = res

        res = res.reshape((h * w, 3))

        res_colors = []
        color_counts = []

        for color in res:
            string_color = generate_hex(color, bgr=True)
            if string_color not in res_colors:
                res_colors.append(string_color)
                color_counts.append(0)
            else:
                color_counts[res_colors.index(string_color)] += 1

        palette = Palette()
        for i, color in enumerate(res_colors):
            palette.add(Color(color, color_counts[i]))

        self.scheme_cache = palette

        # Oh no
        if return_image:
            if return_color_counts:
                return palette, color_counts, res_image
            return palette, res_image
        if return_color_counts:
            return palette, color_counts
        return palette
Exemple #8
0
    def test_srgb(self):
        # Default workspace is sRGB
        c = Color("#abc")
        self.assertAlmostEqual(c.rgb, c.srgb)
        self.assertAlmostEqual(c.srgb,
                               (0.6666666666666667,
                                0.7333333333333333,
                                0.8))
        self.assertAlmostEqual(c.linear_rgb,
                               (0.4019777798321958,
                                0.4969329950608704,
                                0.6038273388553378))

        # Compare to linear RGB
        c = Color("#abc", workspace="linear_rgb")
        self.assertAlmostEqual(c.rgb, c.linear_rgb)
        self.assertAlmostEqual(c.linear_rgb,
                               (0.6666666666666667,
                                0.7333333333333333,
                                0.8))
        self.assertAlmostEqual(c.srgb,
                               (0.8360069706715786,
                                0.8721031439596221,
                                0.9063317533440594))
Exemple #9
0
 def convert(self):
     c = canvas = Drawing()
     img = self._image
     mean, std = img[:,:,1].mean(), img[:,:,1].std()
     for x,y in product(xrange(self.width), xrange(self.height)):
         hue, lum, sat = self._pixelval(x,y)
         perimeter = self.peri(lum, mean, std)
         color = Color.from_hls(hue, lum, sat)
         if perimeter > self._size_threshold:
             shape = c.circle(
                     center = (
                         (self._size_of_pixel + self._d_pixel) * x,
                         (self._size_of_pixel + self._d_pixel) * y),
                     r      = self._size_of_pixel * perimeter / 2,
                     fill = rgb(*color.rgb8))
             canvas.add(shape)
     return canvas
Exemple #10
0
sorted_dg = sorted(degrees.items(), key=operator.itemgetter(1))

delta4 = 0.99/float(counts[0])
delta3 = 0.95/float(counts[1])
delta2 = 0.96/float(counts[2])
delta1 = 0.97/float(counts[3])
delta0 = 1/float(counts[4])

offset0 = 0
offset1 = 0
offset2 = 0
offset3 = 0
offset4 = 0


a0_color = Color('#ffee00')
a2_color = Color('#5a004c')
a3_color = Color('#336699')
# place nodes on axes
print("place nodes on axes")
for n,d in sorted_dg:
    nd = Node(n)

    if d >= bins[0] and d < bins[1]:
        offset4 += delta4
        axis4.add_node(nd, offset4)


    if d >= bins[1] and d < bins[2]:
        offset3 += delta3
        axis3.add_node(nd, offset3)
Exemple #11
0
def export_excel(story_map, file_name, title=None):
    colors = Story.objects.filter(
        theme__story_map=story_map
    ).order_by('color').values("color")
    # we could use distinct here but as we want to support
    # sqlite, we use list(set(x)) instead.
    color_list = [c['color'] for c in colors]
    color_list = list(set(color_list))
    file_name = u"{0}.xls".format(slugify(file_name))
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = \
        'attachment; filename="{0}"'.format(file_name)
    book = Workbook()

    i = 0
    ix = 0x21
    for c in color_list:
        add_palette_colour("board_color_{0}".format(i), ix)
        color = Color(c)
        book.set_colour_RGB(ix,
                            int(color.r * 255),
                            int(color.g * 255),
                            int(color.b * 255))
        ix += 1
        i += 1

    header_style = easyxf(
        'font: name Arial, bold True, height 250;'
        'borders: bottom thin;'
        'alignment: horizontal center;'
        'pattern: pattern solid, fore_colour gray25;',
    )

    sheet1 = book.add_sheet('Board')

    row = 0
    row_head = sheet1.row(row)

    themes = story_map.themes.all()
    index = 1
    for theme in themes:
        row_head.write(index, theme.name, header_style)
        sheet1.col(index).width = 5000
        index += 1

    phase_style = easyxf(
        'alignment: horizontal center, vertical center;'
        'font:  bold True;'
        'border: right thin, top thin;'
        'pattern: pattern solid, fore_colour gray25;'
    )

    row += 1
    for phase in story_map.phases.all():
        max_stories = 1
        index = 1
        for theme in themes:
            stories = phase.stories.filter(theme=theme).all()
            row_index = row
            for story in stories:
                color = "board_color_{0}".format(color_list.index(story.color))
                style = easyxf(
                    'alignment: wrap True, horizontal center, vertical top;'
                    'border: left thin, top thin, right thin, bottom thin;'
                    'pattern: pattern solid, fore_colour {0};'.format(color)
                )
                sheet1.write(row_index, index, story.title, style)
                row_index += 1
            index += 1
            max_stories = max(max_stories, len(stories))
        index = 0
        # write theme name
        sheet1.write_merge(row, (row + max_stories - 1), index, index,
                           phase.name, phase_style)
        row += max_stories
    book.save(response)
    return response
Exemple #12
0
sorted_dg = sorted(degrees.items(), key=operator.itemgetter(1))

delta4 = 0.99/float(counts[0])
delta3 = 0.95/float(counts[1])
delta2 = 0.96/float(counts[2])
delta1 = 0.97/float(counts[3])
delta0 = 1/float(counts[4])

offset0 = 0
offset1 = 0
offset2 = 0
offset3 = 0
offset4 = 0


a0_color = Color('#ffee00')
a2_color = Color('#5a004c')
a3_color = Color('#336699')
# place nodes on axes
print "place nodes on axes"
for n,d in sorted_dg:
    nd = Node(n)

    if d >= bins[0] and d < bins[1]:
        offset4 += delta4
        axis4.add_node(nd, offset4)


    if d >= bins[1] and d < bins[2]:
        offset3 += delta3
        axis3.add_node(nd, offset3)
                return res_colors, color_counts, res_image
            return res_colors, res_image
        if return_color_counts:
            return res_colors, color_counts
        return res_colors

    def get_image_data_from_url(self, url):
        req = urllib.urlopen(url)
        return np.asarray(bytearray(req.read()), dtype=np.uint8)


if __name__ == "__main__":
    print("Running...")
    extractor = Extractor()
    colors, counts, image = extractor.get_colors(
        extractor.get_image_data_from_url(image_url),
        colors,
        return_color_counts=True,
        return_image=True,
        use_logs=True)
    (h, w) = image.shape[:2]
    if colors is not None:
        print("Resulting colors:")
        palette = Palette([])
        for i, color in enumerate(colors):
            palette.add(Color(color, counts[i]))
        palette.sort(sort_palette_by)
        display(palette.get_palette_html())

        cv2_imshow(image)