Skip to content

Instantly share code, notes, and snippets.

@eliemichel
Created August 6, 2014 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliemichel/40d3c1e54dc248b690c1 to your computer and use it in GitHub Desktop.
Save eliemichel/40d3c1e54dc248b690c1 to your computer and use it in GitHub Desktop.
Convert image to Gimp gradient
import sys
import cv2
import numpy as np
"""
Convert image to Gimp gradient.
Usage: python image2gradient.py input_image
Output gradient in stdout. Place it in something like
~/.config/GIMP/2.x/gradients or
~/.gimp-2.x/gradients
(usually in a .ggr file but any extention will do the job)
Requires opencv2. But it is easy to adapt to some other image loading library.
"""
def convert(p):
"""Convert BGR byte-encoded color to gimp gradient color"""
return '%f %f %f %f' % (p[2] / 255.0, p[1] / 255.0, p[0] / 255.0, 1.0)
# Check arguments
if len(sys.argv) < 2:
print("Usage: %s input_image" % (sys.argv,))
exit(0)
# Load Image
im = cv2.imread(sys.argv[1])
# Get keys
old_p = None
count = 0
keys = []
for l in im:
p = list(l[0])
# Add a key at each color change
if (old_p != p):
if count > 0:
keys.append((convert(old_p), count))
count = 0
count += 1
old_p = p
keys.append((convert(old_p), count))
total = sum([k[1] for k in keys[1:]])
# Write file
print('GIMP Gradient')
print('Name: ' + sys.argv[1].split('/')[-1].split('.')[0]) # Name of input file
print(len(keys) - 1)
old_k = None
offset = 0.0
for k, c in keys:
if old_k:
begin = offset / total
end = (offset + c) / total
print('%f %f %f %s %s 0 0 0 0' % (begin, (begin + end) / 2.0, end, old_k, k))
offset += c
old_k = k
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment