AshanGimhana commited on
Commit
dfcc787
1 Parent(s): b6dc33d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py CHANGED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.system("pip install gradio==3.50")
4
+
5
+
6
+ from argparse import Namespace
7
+ import pprint
8
+ import numpy as np
9
+ from PIL import Image
10
+ import torch
11
+ import torchvision.transforms as transforms
12
+ import cv2
13
+ import dlib
14
+ import matplotlib.pyplot as plt
15
+ import gradio as gr # Importing Gradio as gr
16
+ from tensorflow.keras.preprocessing.image import img_to_array
17
+ from huggingface_hub import hf_hub_download, login
18
+ from datasets.augmentations import AgeTransformer
19
+ from utils.common import tensor2im
20
+ from models.psp import pSp
21
+
22
+ # Huggingface login
23
+ login(token=TOKENKEY)
24
+
25
+ # Download models from Huggingface
26
+ age_prototxt = hf_hub_download(repo_id="AshanGimhana/Age_Detection_caffe", filename="age.prototxt")
27
+ caffe_model = hf_hub_download(repo_id="AshanGimhana/Age_Detection_caffe", filename="dex_imdb_wiki.caffemodel")
28
+ sam_ffhq_aging = hf_hub_download(repo_id="AshanGimhana/Face_Agin_model", filename="sam_ffhq_aging.pt")
29
+
30
+ # Age prediction model setup
31
+ age_net = cv2.dnn.readNetFromCaffe(age_prototxt, caffe_model)
32
+
33
+ # Face detection and landmarks predictor setup
34
+ detector = dlib.get_frontal_face_detector()
35
+ predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
36
+
37
+ # Load the pretrained aging model
38
+ EXPERIMENT_TYPE = 'ffhq_aging'
39
+ EXPERIMENT_DATA_ARGS = {
40
+ "ffhq_aging": {
41
+ "model_path": sam_ffhq_aging,
42
+ "transform": transforms.Compose([
43
+ transforms.Resize((256, 256)),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
46
+ ])
47
+ }
48
+ }
49
+ EXPERIMENT_ARGS = EXPERIMENT_DATA_ARGS[EXPERIMENT_TYPE]
50
+ model_path = EXPERIMENT_ARGS['model_path']
51
+ ckpt = torch.load(model_path, map_location='cpu')
52
+ opts = ckpt['opts']
53
+ pprint.pprint(opts)
54
+ opts['checkpoint_path'] = model_path
55
+ opts = Namespace(**opts)
56
+ net = pSp(opts)
57
+ net.eval()
58
+ net.cuda()
59
+
60
+ print('Model successfully loaded!')
61
+
62
+ def get_face_region(image):
63
+ gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
64
+ faces = detector(gray)
65
+ if len(faces) > 0:
66
+ return faces[0]
67
+ return None
68
+
69
+ def get_mouth_region(image):
70
+ gray = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2GRAY)
71
+ faces = detector(gray)
72
+ for face in faces:
73
+ landmarks = predictor(gray, face)
74
+ mouth_points = [(landmarks.part(i).x, landmarks.part(i).y) for i in range(48, 68)]
75
+ return np.array(mouth_points, np.int32)
76
+ return None
77
+
78
+ def predict_age(image):
79
+ image = np.array(image)
80
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
81
+ blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(224, 224), mean=(104.0, 177.0, 123.0), swapRB=False)
82
+ age_net.setInput(blob)
83
+ predictions = age_net.forward()
84
+ predicted_age = np.dot(predictions[0], np.arange(0, 101)).flatten()[0]
85
+ return int(predicted_age)
86
+
87
+ def color_correct(source, target):
88
+ mean_src = np.mean(source, axis=(0, 1))
89
+ std_src = np.std(source, axis=(0, 1))
90
+ mean_tgt = np.mean(target, axis=(0, 1))
91
+ std_tgt = np.std(target, axis=(0, 1))
92
+ src_normalized = (source - mean_src) / std_src
93
+ src_corrected = (src_normalized * std_tgt) + mean_tgt
94
+ return np.clip(src_corrected, 0, 255).astype(np.uint8)
95
+
96
+ def replace_teeth(temp_image, aged_image):
97
+ temp_image = np.array(temp_image)
98
+ aged_image = np.array(aged_image)
99
+ temp_mouth = get_mouth_region(temp_image)
100
+ aged_mouth = get_mouth_region(aged_image)
101
+ if temp_mouth is None or aged_mouth is None:
102
+ return aged_image
103
+
104
+ temp_mask = np.zeros_like(temp_image)
105
+ cv2.fillConvexPoly(temp_mask, temp_mouth, (255, 255, 255))
106
+ temp_mouth_region = cv2.bitwise_and(temp_image, temp_mask)
107
+ temp_mouth_bbox = cv2.boundingRect(temp_mouth)
108
+ aged_mouth_bbox = cv2.boundingRect(aged_mouth)
109
+ temp_mouth_crop = temp_mouth_region[temp_mouth_bbox[1]:temp_mouth_bbox[1] + temp_mouth_bbox[3], temp_mouth_bbox[0]:temp_mouth_bbox[0] + temp_mouth_bbox[2]]
110
+ temp_mask_crop = temp_mask[temp_mouth_bbox[1]:temp_mouth_bbox[1] + temp_mouth_bbox[3], temp_mouth_bbox[0]:temp_mouth_bbox[0] + temp_mouth_bbox[2]]
111
+ temp_mouth_crop_resized = cv2.resize(temp_mouth_crop, (aged_mouth_bbox[2], aged_mouth_bbox[3]))
112
+ temp_mask_crop_resized = cv2.resize(temp_mask_crop, (aged_mouth_bbox[2], aged_mouth_bbox[3]))
113
+ aged_mouth_crop = aged_image[aged_mouth_bbox[1]:aged_mouth_bbox[1] + aged_mouth_bbox[3], aged_mouth_bbox[0]:aged_mouth_bbox[0] + aged_mouth_bbox[2]]
114
+ temp_mouth_crop_resized = color_correct(temp_mouth_crop_resized, aged_mouth_crop)
115
+ center = (aged_mouth_bbox[0] + aged_mouth_bbox[2] // 2, aged_mouth_bbox[1] + aged_mouth_bbox[3] // 2)
116
+ seamless_teeth = cv2.seamlessClone(temp_mouth_crop_resized, aged_image, temp_mask_crop_resized, center, cv2.NORMAL_CLONE)
117
+ return seamless_teeth
118
+
119
+ def run_alignment(image):
120
+ from scripts.align_all_parallel import align_face
121
+ temp_image_path = "/tmp/temp_image.jpg"
122
+ image.save(temp_image_path)
123
+ aligned_image = align_face(filepath=temp_image_path, predictor=predictor)
124
+ return aligned_image
125
+
126
+ def apply_aging(image, target_age):
127
+ img_transforms = EXPERIMENT_DATA_ARGS[EXPERIMENT_TYPE]['transform']
128
+ input_image = img_transforms(image)
129
+ age_transformers = [AgeTransformer(target_age=target_age)]
130
+ results = []
131
+ for age_transformer in age_transformers:
132
+ with torch.no_grad():
133
+ input_image_age = [age_transformer(input_image.cpu()).to('cuda')]
134
+ input_image_age = torch.stack(input_image_age)
135
+ result_tensor = net(input_image_age.to("cuda").float(), randomize_noise=False, resize=False)[0]
136
+ result_image = tensor2im(result_tensor)
137
+ results.append(np.array(result_image))
138
+ final_result = results[0]
139
+ return final_result
140
+
141
+ def process_image(uploaded_image):
142
+ # Loading images for good and bad teeth
143
+ temp_images_good = [Image.open(f"good_teeth/G{i}.JPG") for i in range(1, 5)]
144
+ temp_images_bad = [Image.open(f"bad_teeth/B{i}.jpeg") for i in range(1, 5)]
145
+
146
+ # Predicting the age
147
+ predicted_age = predict_age(uploaded_image)
148
+ target_age = predicted_age + 5
149
+
150
+ # Aligning the face in the uploaded image
151
+ aligned_image = run_alignment(uploaded_image)
152
+
153
+ # Applying aging effect
154
+ aged_image = apply_aging(aligned_image, target_age=target_age)
155
+
156
+ # Randomly selecting teeth images using index instead of np.random.choice
157
+ good_teeth_image = temp_images_good[np.random.randint(0, len(temp_images_good))]
158
+ bad_teeth_image = temp_images_bad[np.random.randint(0, len(temp_images_bad))]
159
+
160
+ # Replacing teeth in aged image
161
+ aged_image_good_teeth = replace_teeth(good_teeth_image, aged_image)
162
+ aged_image_bad_teeth = replace_teeth(bad_teeth_image, aged_image)
163
+
164
+ return aged_image_good_teeth, aged_image_bad_teeth
165
+
166
+ iface = gr.Interface(
167
+ fn=process_image,
168
+ inputs=gr.Image(type="pil"),
169
+ outputs=[gr.Image(type="pil"), gr.Image(type="pil")],
170
+ title="Aging Effect with Teeth Replacement",
171
+ description="Upload an image to apply an aging effect. The application will generate two results: one with good teeth and one with bad teeth."
172
+ )
173
+
174
+ iface.launch(debug=True)