-
Notifications
You must be signed in to change notification settings - Fork 0
/
distinguish.py
52 lines (42 loc) · 1.96 KB
/
distinguish.py
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
from PIL import Image, ImageTk
from numpy import average, dot, linalg
i = 1
List=[]
for i in range(9):
for j in range(9):
for k in range(1,37):
image1 = Image.open(r'D:\software_practice\get\question(29)' + str(i) + '.jpg')
image2 = Image.open(r'D:\software_practice\无框字符\\test(' + str(k) + ')' + str(j) + '.jpg')
# 对图片进行统一化处理
def get_thum(image, size=(64, 64), greyscale=False):
# 利用image对图像大小重新设置, Image.ANTIALIAS为高质量的
image = image.resize(size, Image.ANTIALIAS)
if greyscale:
# 将图片转换为L模式,其为灰度图,其每个像素用8个bit表示
image = image.convert('L')
return image
# 计算图片的余弦距离
def image_similarity_vectors_via_numpy(image1, image2):
image1 = get_thum(image1)
image2 = get_thum(image2)
images = [image1, image2]
vectors = []
norms = []
for image in images:
vector = []
for pixel_tuple in image.getdata():
vector.append(average(pixel_tuple))
vectors.append(vector)
# linalg=linear(线性)+algebra(代数),norm则表示范数
# 求图片的范数
norms.append(linalg.norm(vector, 2))
a, b = vectors
a_norm, b_norm = norms
# dot返回的是点积,对二维数组(矩阵)进行计算
res = dot(a / a_norm, b / b_norm)
return res
cosin = image_similarity_vectors_via_numpy(image1, image2)
if cosin > 0.98:
print(k, j, i, cosin)
List.append(j)
print(List)