Skip to content

Commit

Permalink
[Feat] Add image URL support (#16)
Browse files Browse the repository at this point in the history
* Add image URL functionality

* Update README.md

* Bump version to 2.0 due to breaking changes
  • Loading branch information
qTipTip authored Feb 9, 2024
1 parent c36f401 commit 5379253
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 20 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Added

- Added an `image_url` argument to the `extract_color` function, allowing the user to specify an image URL to extract colors from.
- Added the `--image-url` argument to the CLI, allowing the user to specify an image URL to extract colors from.

### Changed

- Changed the positional argument `filename` to an optional argument in the CLI.
## [1.0.0] 09/02/2024

### Added
Expand Down
12 changes: 10 additions & 2 deletions Pylette/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument("filename", help="path to image file", type=str)
group = parser.add_mutually_exclusive_group(required=True)

group.add_argument("--filename", help="path to image file", type=str, default=None)
group.add_argument(
"--image-url", help="url to the image file", type=str, default=None
)

parser.add_argument(
"--mode",
help="extraction_mode (KMeans/MedianCut",
Expand Down Expand Up @@ -48,7 +54,9 @@ def main():
type=bool,
)
args = parser.parse_args()
palette = extract_colors(args.filename, palette_size=args.n, sort_mode=args.sort_by)
palette = extract_colors(
args.filename, args.image_url, palette_size=args.n, sort_mode=args.sort_by
)

palette.to_csv(filename=args.out_filename, frequency="True", stdout=args.stdout)
if args.display_colors:
Expand Down
29 changes: 27 additions & 2 deletions Pylette/src/color_extraction.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from io import BytesIO

import numpy as np
import requests
from PIL import Image
from sklearn.cluster import KMeans

Expand Down Expand Up @@ -32,19 +35,41 @@ def median_cut_extraction(arr, height, width, palette_size):
return colors


def extract_colors(image, palette_size=5, resize=True, mode="KM", sort_mode=None):
def extract_colors(
image=None,
image_url: str = None,
palette_size=5,
resize=True,
mode="KM",
sort_mode=None,
):
"""
Extracts a set of 'palette_size' colors from the given image.
:param image: path to Image file
:param image_url: url to the image-file
:param palette_size: number of colors to extract
:param resize: whether to resize the image before processing, yielding faster results with lower quality
:param mode: the color quantization algorithm to use. Currently supports K-Means (KM) and Median Cut (MC)
:param sort_mode: sort colors by luminance, or by frequency
:return: a list of the extracted colors
"""

if image is None and image_url is None:
raise ValueError("No image provided")

if image is None and image_url is not None:
response = requests.get(image_url)
# Check if the request was successful and content type is an image
if response.status_code == 200 and "image" in response.headers.get(
"Content-Type", ""
):
img = Image.open(BytesIO(response.content)).convert("RGB")
else:
raise ValueError("The URL did not point to a valid image.")
else:
img = Image.open(image).convert("RGB")

# open the image
img = Image.open(image).convert("RGB")
if resize:
img = img.resize((256, 256))
width, height = img.size
Expand Down
26 changes: 11 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ pip install Pylette

## Basic usage

A `Palette` object is created by calling the `extract_colors` function.
A `Palette` object is created by calling the `extract_colors` function, either using a path to an image, or an image url:

```python
from Pylette import extract_colors

palette = extract_colors('image.jpg', palette_size=10, resize=True)
palette = extract_colors('image.jpg', palette_size=10, resize=True, mode='MC', sort_mode='luminance')
palette = extract_colors(image='image.jpg', palette_size=10, resize=True)
palette = extract_colors(image_url='https://path.to.image', palette_size=10, resize=True, mode='MC', sort_mode='luminance')
```

This yields a palette of ten colors, and the `resize` flag tells Pylette to resize the image to a more manageable size before
Expand Down Expand Up @@ -94,29 +94,25 @@ Original Image | Extracted Palette
The new version of Pylette also comes bundled with a command line tool, which can be used to extract color palettes from the command line.

```shell script
usage: pylette [-h] [--mode {KM,MC}] [--n N] [--sort_by {luminance,frequency}]
[--stdout STDOUT] [--colorspace {rgb,hsv,hls}]
[--out_filename OUT_FILENAME] [--display-colors DISPLAY_COLORS]
filename
usage: pylette [-h] (--filename FILENAME | --image-url IMAGE_URL) [--mode {KM,MC}] [--n N] [--sort_by {luminance,frequency}] [--stdout STDOUT] [--colorspace {rgb,hsv,hls}] [--out_filename OUT_FILENAME]
[--display-colors DISPLAY_COLORS]

positional arguments:
filename path to image file

optional arguments:
options:
-h, --help show this help message and exit
--filename FILENAME path to image file (default: None)
--image-url IMAGE_URL
url to the image file (default: None)
--mode {KM,MC} extraction_mode (KMeans/MedianCut (default: KM)
--n N the number of colors to extract (default: 5)
--sort_by {luminance,frequency}
sort by luminance or frequency (default: luminance)
--stdout STDOUT whether to display the extracted color values in the
stdout (default: True)
--stdout STDOUT whether to display the extracted color values in the stdout (default: True)
--colorspace {rgb,hsv,hls}
color space to represent colors in (default: RGB)
--out_filename OUT_FILENAME
where to save the csv file (default: None)
--display-colors DISPLAY_COLORS
Open a window displaying the extracted palette
(default: False)
Open a window displaying the extracted palette (default: False)
```
## Under the hood
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "pylette"
version = "1.0.0"
version = "2.0.0"
description = "A Python library for extracting color palettes from images."
authors = ["Ivar Stangeby"]
license = "MIT"
Expand Down

0 comments on commit 5379253

Please sign in to comment.