
# https://www.globalsino.com/ICs/
# Euclidean distance and Euclidian Similarity for images

from PIL import Image
from collections import Counter
import numpy as np
import os
import cv2


filePath = r"C:\GlobalSino2\ICs\images"

# Resize the images so that ...
ref_img_1_0 = os.path.join(filePath,"4274Scratch.png")
ref_img_2_0 = os.path.join(filePath,"4274Random.png")
ref_img_3_0 = os.path.join(filePath,"4274Donut.png")
ref_img_4_0 = os.path.join(filePath,"4274EdgeLoc.png")

MyImg_1 = cv2.imread(ref_img_1_0)
MyImg_2 = cv2.imread(ref_img_2_0)
MyImg_3 = cv2.imread(ref_img_3_0)
MyImg_4 = cv2.imread(ref_img_4_0)

# Resized image cannot be larger than the original images
resizedImg_1 = cv2.resize(MyImg_1, (250,250))
resizedImg_2 = cv2.resize(MyImg_2, (250,250))
resizedImg_3 = cv2.resize(MyImg_3, (250,250))
resizedImg_4 = cv2.resize(MyImg_4, (250,250))

cv2.imwrite(os.path.join(filePath,"4274ScratchB.png"),resizedImg_1)
cv2.imwrite(os.path.join(filePath,"4274RandomB.png"),resizedImg_2)
cv2.imwrite(os.path.join(filePath,"4274DonutB.png"),resizedImg_3)
cv2.imwrite(os.path.join(filePath,"4274EdgeLocB.png"),resizedImg_4)

# image 1
ref_img_1 = Image.open(os.path.join(filePath,"4274ScratchB.png"))
ref_img_arr_1 = np.asarray(ref_img_1)
print(np.shape(ref_img_arr_1))
# Convert the 3-D array into a 1-D array
OneDarray_1 = ref_img_arr_1.flatten()
print(np.shape(OneDarray_1))

# image 2
ref_img_2 = Image.open(os.path.join(filePath,"4274RandomB.png"))
ref_img_arr_2 = np.asarray(ref_img_2)
print(np.shape(ref_img_arr_2))
# Convert the 3-D array into a 1-D array
OneDarray_2 = ref_img_arr_2.flatten()
print(np.shape(OneDarray_2))

# image 3
ref_img_3 = Image.open(os.path.join(filePath,"4274DonutB.png"))
ref_img_arr_3 = np.asarray(ref_img_3)
print(np.shape(ref_img_arr_3))
# Convert the 3-D array into a 1-D array
OneDarray_3 = ref_img_arr_3.flatten()
print(np.shape(OneDarray_3))


# image 4
ref_img_4 = Image.open(os.path.join(filePath,"4274EdgeLocB.png"))
ref_img_arr_4 = np.asarray(ref_img_4)
print(np.shape(ref_img_arr_4))
# Convert the 3-D array into a 1-D array
OneDarray_4 = ref_img_arr_4.flatten()
print(np.shape(OneDarray_4))

# Generating the Count-Histogram-Vectors
RHV_1 = Counter(OneDarray_1)
RHV_2 = Counter(OneDarray_2)
RHV_3 = Counter(OneDarray_3)
RHV_4 = Counter(OneDarray_4)
# print(RHV_1)
# print(RHV_2)
# print(RHV_3)
# print(RHV_4)

# Euclidean Distance Function
def L2Norm(H1,H2):
    distance =0
    for i in range(len(H1)):
        distance += np.square(H1[i]-H2[i])
    return np.sqrt(distance)

print("Ref_1/Ref_2: ", round((L2Norm(RHV_1,RHV_2))/1000))
print("Ref_1/Ref_3: ", round((L2Norm(RHV_1,RHV_3))/1000))
print("Ref_1/Ref_4: ", round((L2Norm(RHV_1,RHV_4))/1000))
print("Ref_2/Ref_3: ", round((L2Norm(RHV_2,RHV_3))/1000))
print("Ref_2/Ref_4: ", round((L2Norm(RHV_2,RHV_4))/1000))
print("Ref_3/Ref_4: ", round((L2Norm(RHV_3,RHV_4))/1000))




