Skip to content

Commit

Permalink
Merge pull request #26 from arvkevi/update_deps
Browse files Browse the repository at this point in the history
Update dependencies and output more hex codes after optimization
  • Loading branch information
arvkevi authored Dec 28, 2023
2 parents fc80332 + 04a7caf commit 8281174
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 27 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ repos:
- id: end-of-file-fixer
- id: debug-statements
- repo: https://github.com/timothycrosley/isort
rev: 5.10.1
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 22.3.0
rev: 23.12.1
hooks:
- id: black
2 changes: 1 addition & 1 deletion CONTRIBUTING.rst
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ To set up `img2cmap` for local development:

pip install img2cmap[dev]

5. When you're done making changes run all the checks and docs builder with `tox <https://tox.readthedocs.io/en/latest/install.html>`_ one command::
5. When you're done making changes run all the checks and docs builder with `tox <https://tox.wiki/en/latest/installation.html>`_ one command::

tox

Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ authors = [
{ name="Marshall Krassenstein", email="[email protected]"},
]
description = "Create colormaps from images"
readme = "README.md"
readme = "README.rst"
requires-python = ">=3.7"
classifiers = [
"License :: OSI Approved :: MIT License",
Expand Down Expand Up @@ -42,7 +42,7 @@ dependencies = [

[project.optional-dependencies]
dev = ["black", "requests", "tox"]
streamlit= ["streamlit", "st-annotated-text"]
streamlit= ["streamlit>=1.29.0", "st-annotated-text"]
all = ["black", "requests", "tox", "streamlit", "st-annotated-text"]

[project.license]
Expand Down
2 changes: 1 addition & 1 deletion src/img2cmap/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def generate_cmap(self, n_colors=4, palette_name=None, random_state=None):
matplotlib.colors.ListedColormap: A matplotlib ListedColormap object.
"""
# create a kmeans model
self.kmeans = MiniBatchKMeans(n_clusters=n_colors, random_state=random_state)
self.kmeans = MiniBatchKMeans(n_clusters=n_colors, random_state=random_state, n_init=3)
# fit the model to the pixels
self.kmeans.fit(self.pixels)
# get the cluster centers
Expand Down
28 changes: 10 additions & 18 deletions streamlit/app.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import warnings
from io import BytesIO
from pprint import pformat

import matplotlib as mpl
import matplotlib.patches as patches
Expand Down Expand Up @@ -35,7 +36,7 @@ def colorpicker(color):
# @profile
def main():
warnings.filterwarnings("ignore")
st.set_option("deprecation.showfileUploaderEncoding", False)
# st.set_option("deprecation.showfileUploaderEncoding", False)

st.set_page_config(
page_title="img2cmap web",
Expand All @@ -59,9 +60,7 @@ def main():
if user_image is not None:
user_image = BytesIO(user_image.getvalue())
elif file_or_url == "url":
user_image = st.sidebar.text_input(
"Paste an image URL", "https://static1.bigstockphoto.com/3/2/3/large1500/323952496.jpg"
)
user_image = st.sidebar.text_input("Paste an image URL", "https://static1.bigstockphoto.com/3/2/3/large1500/323952496.jpg")
else:
st.warning("Please select an option")

Expand All @@ -81,7 +80,7 @@ def main():
random_state = st.sidebar.number_input("Random state", value=42, help="Random state for reproducibility")
random_state = int(random_state)

@st.cache(allow_output_mutation=True)
@st.cache_data
def get_image_converter(user_image, remove_transparent):
converter = ImageConverter(user_image)
if remove_transparent:
Expand Down Expand Up @@ -117,17 +116,13 @@ def get_image_converter(user_image, remove_transparent):
annotated_text(*[(hexcode, "", hexcode, text_color) for hexcode, text_color in zip(colors1, bw_mask)])
st.code(colors1)
st.caption("Click copy button on far right to copy hex codes to clipboard.")

st.header("Detect optimal number of colors")
max_colors = st.number_input(
"Max number of colors in cmap (more colors = longer runtime)", min_value=2, max_value=20, value=10
)
col1, _, _, _, _ = st.columns(5)
max_colors = col1.number_input("Max number of colors in cmap (more colors = longer runtime)", min_value=2, max_value=20, value=10)
optimize = st.button("Optimize")
if optimize:
with st.spinner("Optimizing... (this can take up to a minute)"):
cmaps, best_n_colors, ssd = converter.generate_optimal_cmap(
max_colors=max_colors, palette_name="", random_state=random_state
)
cmaps, best_n_colors, ssd = converter.generate_optimal_cmap(max_colors=max_colors, palette_name="", random_state=random_state)

figopt, ax = plt.subplots(figsize=(7, 5))

Expand All @@ -152,9 +147,7 @@ def get_image_converter(user_image, remove_transparent):
ax.set_xticks([])

# best
rect = patches.Rectangle(
(0, best_n_colors), ymax, 1, linewidth=1, facecolor="none", edgecolor="black", linestyle="--"
)
rect = patches.Rectangle((0, best_n_colors), ymax, 1, linewidth=1, facecolor="none", edgecolor="black", linestyle="--")
ax.add_patch(rect)

# minus 2, one for starting at 2 and one for 0-indexing
Expand All @@ -163,9 +156,8 @@ def get_image_converter(user_image, remove_transparent):
st.metric("Optimal number of colors", best_n_colors)
st.text("Hex Codes of optimal colormap (click to copy on far right)")
st.code(sorted([mpl.colors.rgb2hex(c) for c in cmaps[best_n_colors].colors]))

st.text("Sum of squared distances by number of colors:")
st.write(ssd)
st.text("Hex Codes of all colormaps {k: [hex codes]}")
st.code(pformat({k: sorted([mpl.colors.rgb2hex(c) for c in v.colors]) for k, v in cmaps.items()}))


if __name__ == "__main__":
Expand Down
5 changes: 2 additions & 3 deletions tests/test_img2cmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ def test_cmap_optimal_plot(test_image_input):
imageconverter = ImageConverter(test_image_input)
cmaps, _, _ = imageconverter.generate_optimal_cmap(random_state=42)
for _, cmap_ in cmaps.items():

assert not np.any(np.all(np.isclose(cmap_.colors, 1, atol=1e-9)))
assert not np.any(np.all(np.isclose(cmap_.colors, 0, atol=1e-9)))

Expand Down Expand Up @@ -135,6 +134,6 @@ def test_compute_optimal_hexcodes():


def test_break_kneed():
with pytest.raises(UserWarning):
with pytest.raises(ValueError):
imageconverter = ImageConverter(image_urls[0])
imageconverter.generate_optimal_cmap(max_colors=5, random_state=42)
imageconverter.generate_optimal_cmap(max_colors=1, random_state=42)

0 comments on commit 8281174

Please sign in to comment.