Skip to content

Commit 50b7fbb

Browse files
committed
fixed RGB to HEX conversion
1 parent 8244665 commit 50b7fbb

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

Diff for: image_decoder.py

+14-5
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,21 @@ def reject_outliers(data, m = 6.):
66
if not isinstance(data, np.ndarray):
77
data = np.array(data)
88
d = np.abs(data - np.median(data))
9-
#print(d)
109
mdev = np.median(d)
1110
s = d / (mdev if mdev else 1.)
12-
13-
#print(s)
1411
output = data[s<m].tolist()
12+
13+
# sometimes numpy tolist() returns a nested list
1514
if type(output[0]) == list:
1615
return output[0]
16+
1717
return output
1818

19+
def clamp(x):
20+
return max(0, min(x, 255))
21+
1922
def rgb_to_hex(r, g, b):
20-
return ('#{:X}{:X}{:X}').format(r, g, b)
23+
return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
2124

2225
def average_pixels(img, pixels_coords, quiet):
2326
r, g, b = img.convert('RGB').split()
@@ -34,6 +37,7 @@ def average_pixels(img, pixels_coords, quiet):
3437
r_list.append(r.getpixel((x, y)))
3538
g_list.append(g.getpixel((x, y)))
3639
b_list.append(b.getpixel((x, y)))
40+
3741
if not quiet:
3842
img_size = img.width * img.height
3943
print(img.width, img.height)
@@ -90,6 +94,7 @@ def downscale_image(image_path, quiet):
9094
img = Image.open(image_path) # open source image as PIL/Pillow object
9195
except IOError:
9296
print('%s could not be opened' % image_path)
97+
return None
9398
width, height = img.size
9499

95100
aspect_ratio = height / width
@@ -118,7 +123,11 @@ def decode(image_path, show_preview = False, quiet = True):
118123
if show_preview:
119124
img_size = img.size
120125
preview_size = (round(img.width * 1.5), round(img.height * 1.5))
121-
preview_img = Image.new("RGB", preview_size, average_color)
126+
127+
# for some reason PIL doesn't play nicely with hex inputs here
128+
# manually convert back to RGB here since occasionally it won't accept certain values
129+
preview_img = Image.new("RGB", preview_size, tuple(int(average_color.lstrip('#')[i:i+2], 16) for i in (0, 2, 4)))
130+
122131
preview_img.paste(img, ((preview_size[0]-img_size[0])//2,
123132
(preview_size[1]-img_size[1])//2))
124133
preview_img.show()

0 commit comments

Comments
 (0)