Created
February 20, 2024 04:30
-
-
Save setuc/c6f0491163ee4622cc03f181fa67c854 to your computer and use it in GitHub Desktop.
A Python script that generates and displays color gradients using matplotlib. It includes functions to convert HEX color codes to RGB, interpolate between two colors, and generate a visual representation of the color gradient.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # coding: utf-8 | |
| # This script demonstrates generating gradients between two specified colors. | |
| # Users can define their start and end colors in HEX format, and the script will display the gradient transition. | |
| # Requirements: numpy, matplotlib | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| def hex_to_rgb(hex_color): | |
| """ | |
| Convert hex to RGB. | |
| Parameters: | |
| - hex_color: String representing the hexadecimal color code. | |
| Returns: | |
| - A tuple of integers representing the RGB values. | |
| """ | |
| return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) | |
| def interpolate_color(color_start_rgb, color_end_rgb, t): | |
| """ | |
| Interpolate between two RGB colors. | |
| Parameters: | |
| - color_start_rgb: Tuple of integers representing the starting RGB color. | |
| - color_end_rgb: Tuple of integers representing the ending RGB color. | |
| - t: Float representing the interpolation factor between 0 and 1. | |
| Returns: | |
| - A tuple representing the interpolated RGB color. | |
| """ | |
| return tuple(int(start_val + (end_val - start_val) * t) for start_val, end_val in zip(color_start_rgb, color_end_rgb)) | |
| # Example usage: | |
| # Define start and end colors | |
| examples = [ | |
| {"start": "E01A4F", "end": "53B3CB"}, | |
| {"start": "d00000", "end": "3f88c5"}, | |
| {"start": "ffafcc", "end": "a2d2ff"} | |
| ] | |
| for example in examples: | |
| color_start_hex = example["start"] | |
| color_end_hex = example["end"] | |
| color_start_rgb = hex_to_rgb(color_start_hex) | |
| color_end_rgb = hex_to_rgb(color_end_hex) | |
| # Generate gradient | |
| gradient = [interpolate_color(color_start_rgb, color_end_rgb, t) for t in np.linspace(0, 1, 256)] | |
| gradient = np.array([gradient] * 100) # Increase the height of the gradient image | |
| # Display the gradient | |
| plt.figure(figsize=(10, 2)) | |
| plt.imshow(gradient, aspect='auto') | |
| plt.axis('off') | |
| plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment