from PIL import Image
import numpy as np
import math
import os
import matplotlib.pyplot as plt
import colorsys
# Compute low order moments(1,2,3)
def color_moments(filename):
img = Image.open(filename)
if img is None:
return
#9 vectors
color_feature = []
#get r,g,b
r,g,b = img.split()
# The first central moment - average
r_mean = np.mean(r) # np.sum(h)/float(N)
g_mean = np.mean(g) # np.sum(s)/float(N)
b_mean = np.mean(b) # np.sum(v)/float(N)
color_feature.extend([r_mean, g_mean, b_mean])
# The second central moment - standard deviation
r_std = np.std(r) # np.sqrt(np.mean(abs(h - h.mean())**2))
g_std = np.std(g) # np.sqrt(np.mean(abs(s - s.mean())**2))
b_std = np.std(b) # np.sqrt(np.mean(abs(v - v.mean())**2))
color_feature.extend([r_std, g_std, b_std])
# The third central moment - the third root of the skewness
r_skewness = np.mean(abs(r - r_mean)**3)
g_skewness = np.mean(abs(g - g_mean)**3)
b_skewness = np.mean(abs(b - b_mean)**3)
r_thirdMoment = r_skewness**(1./3)
g_thirdMoment = g_skewness**(1./3)
b_thirdMoment = b_skewness**(1./3)
color_feature.extend([r_thirdMoment, g_thirdMoment, b_thirdMoment])
return color_feature
def calculate_distance(feature_1, feature_2):
distance = 0
for i in range(0,9):
distance += (abs(feature_1[i]-feature_2[i]))**2
distance = math.sqrt(distance)
return distance
def similarity(doc,rootdir):
feature_1 = color_moments(doc)
print(doc)
min = 10000
location = -1
list = os.listdir(rootdir)
distance = [0]*len(list)
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isfile(path):
if os.path.samefile(path, doc):
continue
else:
feature_2 = color_moments(path)
distance[i] = calculate_distance(feature_1, feature_2)
if min>distance[i]:
min = distance[i]
location = i
print(os.path.join(rootdir,list[location]))
print(min)
plt.figure("result")
plt.subplot(2,2,1),plt.title("Input")
img = Image.open(doc)
plt.imshow(img)
plt.axis('off')
plt.subplot(2,2,2),plt.title("most similarity\ndistance:"+str(round(distance[location],2)))
img = Image.open(os.path.join(rootdir,list[location]))
plt.axis('off')
plt.imshow(img)
count = 0
for i in range (0,len(list)):
if os.path.samefile(os.path.join(rootdir,list[i]), doc):
continue
if i==location:
continue
count+=1
if count==9:
break
plt.subplot(4,4,count+8),plt.title("distance:"+str(round(distance[i],2)))
img = Image.open(os.path.join(rootdir,list[i]))
plt.imshow(img)
plt.axis('off')
plt.show()
def picture_similarity(rootdir):
mainlist = os.listdir(rootdir)
for i in range(0,len(mainlist)):
path = os.path.join(rootdir,mainlist[i])
if os.path.isfile(path):
similarity(path,rootdir)
rootdir = ".\img"
picture_similarity(rootdir)