wko_anime-face-similarity/main.py

61 lines
2.0 KiB
Python
Raw Normal View History

2023-01-15 12:40:35 +01:00
import sys
import cv2
import numpy as np
2023-01-29 22:43:45 +01:00
import matplotlib.pyplot as plt
2023-01-29 22:57:29 +01:00
from comparisons import histogram_comparison, structural_similarity_index, euclidean_distance
2023-01-15 12:40:35 +01:00
2023-01-29 21:23:11 +01:00
# Allows imports from the style transfer submodule
sys.path.append('DCT-Net')
2023-01-15 12:40:35 +01:00
from source.cartoonize import Cartoonizer
2023-01-29 21:14:30 +01:00
2023-01-15 12:40:35 +01:00
def load_source(filename: str) -> np.ndarray:
2023-01-29 21:23:11 +01:00
return cv2.imread(filename)[..., ::-1]
2023-01-15 12:40:35 +01:00
2023-01-29 22:43:45 +01:00
def find_and_crop_face(data: np.ndarray, classifier_file='haarcascades/haarcascade_frontalface_default.xml') -> np.ndarray:
2023-01-29 15:17:39 +01:00
data_gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
2023-01-29 22:43:45 +01:00
face_cascade = cv2.CascadeClassifier(classifier_file)
face = face_cascade.detectMultiScale(data_gray, 1.1, 3)
2023-01-29 15:17:39 +01:00
face = max(face, key=len)
2023-01-29 21:14:30 +01:00
x, y, w, h = face
2023-01-29 15:17:39 +01:00
face = data[y:y + h, x:x + w]
2023-01-29 18:58:45 +01:00
return face
2023-01-15 12:40:35 +01:00
2023-01-29 22:43:45 +01:00
def plot_two_images(a: np.ndarray, b: np.ndarray):
plt.figure(figsize=[10, 10])
plt.subplot(121)
plt.imshow(a)
plt.title("A")
plt.subplot(122)
plt.imshow(b)
plt.title("B")
plt.show()
2023-01-15 12:40:35 +01:00
def compare_with_anime_characters(data: np.ndarray) -> int:
2023-01-29 22:43:45 +01:00
# Example will be one face from anime dataset
example = load_source('data/images/Aisaka, Taiga.jpg')
# TODO: Use a different face detection method for anime images
example_face = find_and_crop_face(example, 'haarcascades/lbpcascade_animeface.xml')
data_rescaled = cv2.resize(data, example_face.shape[:2])
plot_two_images(example_face, data_rescaled)
print(histogram_comparison(data_rescaled, example_face))
print(f'structural-similarity: {structural_similarity_index(data_rescaled, example_face)}')
2023-01-29 22:57:29 +01:00
print(f'euclidean-distance: {euclidean_distance(data_rescaled, example_face)}')
2023-01-15 12:40:35 +01:00
2023-01-29 15:17:39 +01:00
def transfer_to_anime(img: np.ndarray):
2023-01-29 21:23:11 +01:00
algo = Cartoonizer(dataroot='DCT-Net/damo/cv_unet_person-image-cartoon_compound-models')
2023-01-29 22:43:45 +01:00
return algo.cartoonize(img).astype(np.uint8)
2023-01-15 12:40:35 +01:00
if __name__ == '__main__':
2023-01-29 22:43:45 +01:00
source = load_source('UAM-Andre.jpg')
source_anime = transfer_to_anime(source)
source_face_anime = find_and_crop_face(source_anime)
2023-01-15 12:40:35 +01:00
print(compare_with_anime_characters(source_face_anime))