-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_operations.py
More file actions
57 lines (51 loc) · 1.86 KB
/
image_operations.py
File metadata and controls
57 lines (51 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import urllib.parse
from urllib.error import URLError
from flask import abort
import scipy
import scipy.misc
import scipy.cluster
import binascii
from PIL import Image, UnidentifiedImageError
from urllib.request import urlopen
import numpy as np
# get PIL.Image.Image from url
def img_from_url(url):
url_1 = url[:6]
url = url[6:]
url = urllib.parse.quote(url)
try:
img = Image.open(urlopen(url_1 + url))
except URLError:
abort(404, "Invalid URL")
except UnidentifiedImageError:
abort(404, "Image not found")
return img
# get dominant color in the RGB/RGBA array of pixels
def get_dominant_color(arr):
arr = arr.astype(float)
codes, distort = scipy.cluster.vq.kmeans(arr, 5) # finding clusters
code_indices, distort = scipy.cluster.vq.vq(arr, codes) # assign codes
counts, bins = np.histogram(code_indices, len(codes)) # count occurrences
index_max = np.argmax(counts) # find most frequent
peak = codes[index_max]
color = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')
return color
# get border color and logo primary color from PIL.Image.Image
def get_colors(img):
arr = np.asarray(img)
shape = arr.shape
# separate border pixels from others
row_offset = shape[0] // 15
col_offset = shape[1] // 15
border_arr = []
logo_arr = []
for row in range(shape[0]):
for col in range(shape[1]):
if row < row_offset or row >= (shape[0] - row_offset) or col < col_offset or col >= (shape[1] - col_offset):
border_arr.append((arr[row][col]))
else:
logo_arr.append(arr[row][col])
# get dominant colors in both set of pixels
border = get_dominant_color(np.array(border_arr))
primary = get_dominant_color(np.array(logo_arr))
return ("#" + border[:6]).upper(), ("#" + primary[:6]).upper()