def find_a_dominant_color(image):
# K-mean clustering to find the k most dominant color, from:
# http://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image
n_clusters = 5
# Get image into a workable form
im = image.copy()
im = im.resize((150, 150)) # optional, to reduce time
ar = scipy.misc.fromimage(im)
im_shape = ar.shape
ar = ar.reshape(scipy.product(im_shape[:2]), im_shape[2])
ar = np.float_(ar)
# Compute clusters
codes, dist = scipy.cluster.vq.kmeans(ar, n_clusters)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
# Get the indexes of the most frequent, 2nd most frequent, 3rd, ...
sorted_idxs = np.argsort(counts)
# Get the color
peak = codes[sorted_idxs[1]] # get second most frequent color
return [int(i) for i in peak.tolist()] # list comprehension to quickly cast everything to int
python类histogram()的实例源码
def kde(data, N=None, MIN=None, MAX=None):
# Parameters to set up the mesh on which to calculate
N = 2**14 if N is None else int(2**sci.ceil(sci.log2(N)))
if MIN is None or MAX is None:
minimum = min(data)
maximum = max(data)
Range = maximum - minimum
MIN = minimum - Range/10 if MIN is None else MIN
MAX = maximum + Range/10 if MAX is None else MAX
# Range of the data
R = MAX-MIN
# Histogram the data to get a crude first approximation of the density
M = len(data)
DataHist, bins = sci.histogram(data, bins=N, range=(MIN,MAX))
DataHist = DataHist/M
DCTData = scipy.fftpack.dct(DataHist, norm=None)
I = [iN*iN for iN in xrange(1, N)]
SqDCTData = (DCTData[1:]/2)**2
# The fixed point calculation finds the bandwidth = t_star
guess = 0.1
try:
t_star = scipy.optimize.brentq(fixed_point, 0, guess,
args=(M, I, SqDCTData))
except ValueError:
print 'Oops!'
return None
# Smooth the DCTransformed data using t_star
SmDCTData = DCTData*sci.exp(-sci.arange(N)**2*sci.pi**2*t_star/2)
# Inverse DCT to get density
density = scipy.fftpack.idct(SmDCTData, norm=None)*N/R
mesh = [(bins[i]+bins[i+1])/2 for i in xrange(N)]
bandwidth = sci.sqrt(t_star)*R
density = density/sci.trapz(density, mesh)
return bandwidth, mesh, density
def _auto_color(self, url:str, ranks):
phrases = ["Calculating colors..."] # in case I want more
#try:
await self.bot.say("**{}**".format(random.choice(phrases)))
clusters = 10
async with self.session.get(url) as r:
image = await r.content.read()
with open('data/leveler/temp_auto.png','wb') as f:
f.write(image)
im = Image.open('data/leveler/temp_auto.png').convert('RGBA')
im = im.resize((290, 290)) # resized to reduce time
ar = scipy.misc.fromimage(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2])
codes, dist = scipy.cluster.vq.kmeans(ar.astype(float), clusters)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
# sort counts
freq_index = []
index = 0
for count in counts:
freq_index.append((index, count))
index += 1
sorted_list = sorted(freq_index, key=operator.itemgetter(1), reverse=True)
colors = []
for rank in ranks:
color_index = min(rank, len(codes))
peak = codes[sorted_list[color_index][0]] # gets the original index
peak = peak.astype(int)
colors.append(''.join(format(c, '02x') for c in peak))
return colors # returns array
#except:
#await self.bot.say("```Error or no scipy. Install scipy doing 'pip3 install numpy' and 'pip3 install scipy' or read here: https://github.com/AznStevy/Maybe-Useful-Cogs/blob/master/README.md```")
# converts hex to rgb
def pdf(self):
if self._pdf is None:
from scipy import histogram
self._pdf = histogram(self.speed, range(0, 50, self.bin_width), density=True)
return self._pdf
def pdf(self):
if self._pdf is None:
from scipy import histogram
self._pdf = histogram(self.speed, range(0, 50, self.bin_width), density=True)
return self._pdf
def find_dominant_colors(image):
"""Cluster the colors of the image in CLUSTER_NUMBER of clusters. Returns
an array of dominant colors reverse sorted by cluster size.
"""
array = img_as_float(fromimage(image))
# Reshape from MxNx4 to Mx4 array
array = array.reshape(scipy.product(array.shape[:2]), array.shape[2])
# Remove transparent pixels if any (channel 4 is alpha)
if array.shape[-1] > 3:
array = array[array[:, 3] == 1]
# Finding centroids (centroids are colors)
centroids, _ = kmeans(array, CLUSTER_NUMBER)
# Allocate pixel to a centroid cluster
observations, _ = vq(array, centroids)
# Calculate the number of pixels in a cluster
histogram, _ = scipy.histogram(observations, len(centroids))
# Sort centroids by number of pixels in their cluster
sorted_centroids = sorted(zip(centroids, histogram),
key=lambda x: x[1],
reverse=True)
sorted_colors = tuple((couple[0] for couple in sorted_centroids))
return sorted_colors