Skip to content

Commit

Permalink
add Colors.create_from_image
Browse files Browse the repository at this point in the history
  • Loading branch information
MAfarrag committed Jul 27, 2024
1 parent 469b17b commit 393a5df
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 0 deletions.
43 changes: 43 additions & 0 deletions cleopatra/colors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from typing import List, Union, Tuple, Any
from matplotlib import colors as mcolors
from pathlib import Path
from PIL import Image


class Colors:
Expand Down Expand Up @@ -52,6 +54,47 @@ def __init__(

self._color_value = color_value

@classmethod
def create_from_image(cls, path: str) -> "Colors":
"""Create a color object from an image.
if you have an image of a color ramp, and you want to extract the colors from it, you can use this method.
.. image:: /_images/colors/color-ramp.png
:alt: Example Image
:align: center
Parameters
----------
path : str
The path to the image file.
Returns
-------
Colors
A color object.
Raises
------
FileNotFoundError
If the file does not exist.
Examples
--------
>>> path = "examples/data/colors/color-ramp.png"
>>> colors = Colors.create_from_image(path)
>>> print(colors.color_value) # doctest: +SKIP
[(9, 63, 8), (8, 68, 9), (5, 78, 7), (1, 82, 3), (0, 84, 0), (0, 85, 0), (1, 83, 0), (1, 81, 0), (1, 80, 1)
"""
if not Path(path).exists():
raise FileNotFoundError(f"The file {path} does not exist.")

image = Image.open(path).convert("RGB")
width, height = image.size
color_values = [image.getpixel((x, int(height / 2))) for x in range(width)]

return cls(color_values)

def get_type(self) -> List[str]:
"""get_type.
Expand Down
Binary file added docs/source/_images/colors/color-ramp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/data/colors/color-ramp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added tests/data/colors/color-ramp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ def test_create_from_rgb(self):
color = Colors(rgb_color)
assert color._color_value == [rgb_color]

def test_create_from_image(self):
path = "tests\data\colors\color-ramp.png"
colors = Colors.create_from_image(path)
assert isinstance(colors.color_value, list)
assert len(colors.color_value) == 2713


def test_get_type():
"""test_create_colors_object."""
Expand Down

0 comments on commit 393a5df

Please sign in to comment.