{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":16880,"databundleVersionId":858837,"sourceType":"competition"},{"sourceId":1003630,"sourceType":"datasetVersion","datasetId":442595},{"sourceId":7051864,"sourceType":"datasetVersion","datasetId":4058533},{"sourceId":7056181,"sourceType":"datasetVersion","datasetId":4061533},{"sourceId":7056802,"sourceType":"datasetVersion","datasetId":4061773}],"dockerImageVersionId":29845,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"%%capture\n!pip install /kaggle/input/facenet-pytorch-vggface2/facenet_pytorch-2.2.7-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:12.115863Z","iopub.execute_input":"2023-11-26T22:38:12.116241Z","iopub.status.idle":"2023-11-26T22:38:19.747968Z","shell.execute_reply.started":"2023-11-26T22:38:12.116167Z","shell.execute_reply":"2023-11-26T22:38:19.746900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from facenet_pytorch import MTCNN\nimport cv2\nfrom PIL import Image\nimport torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom tqdm.notebook import tqdm\nimport os","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:19.750439Z","iopub.execute_input":"2023-11-26T22:38:19.750762Z","iopub.status.idle":"2023-11-26T22:38:21.309965Z","shell.execute_reply.started":"2023-11-26T22:38:19.750704Z","shell.execute_reply":"2023-11-26T22:38:21.309289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(select_largest=False, device='cuda')\n\n# video path of the video\nvideo_path_here = '/kaggle/input/deepfake-detection-challenge/test_videos/acazlolrpz.mp4'\n\n# Load a single image and display\nv_cap = cv2.VideoCapture(video_path_here)\n\nsuccess, frame = v_cap.read()\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nframe = Image.fromarray(frame)\n\nplt.figure(figsize=(12, 8))\nplt.imshow(frame)\nplt.axis('off')\n\n# Detect face\nface = mtcnn(frame)\nface.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:21.311561Z","iopub.execute_input":"2023-11-26T22:38:21.311896Z","iopub.status.idle":"2023-11-26T22:38:26.683391Z","shell.execute_reply.started":"2023-11-26T22:38:21.311837Z","shell.execute_reply":"2023-11-26T22:38:26.682447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(select_largest=False, post_process=False, device='cuda:0')\n\n# Detect face\nface = mtcnn(frame)\n\n# Visualize\nplt.imshow(face.permute(1, 2, 0).int().numpy())\nplt.axis('off');","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:26.684872Z","iopub.execute_input":"2023-11-26T22:38:26.685265Z","iopub.status.idle":"2023-11-26T22:38:26.975873Z","shell.execute_reply.started":"2023-11-26T22:38:26.685188Z","shell.execute_reply":"2023-11-26T22:38:26.974737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(margin=40, select_largest=False, post_process=False, device='cuda:0')\n\n# Detect face\nface = mtcnn(frame)\n\n# Visualize\nplt.imshow(face.permute(1, 2, 0).int().numpy())\nplt.axis('off');","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:26.980739Z","iopub.execute_input":"2023-11-26T22:38:26.981226Z","iopub.status.idle":"2023-11-26T22:38:27.328210Z","shell.execute_reply.started":"2023-11-26T22:38:26.981133Z","shell.execute_reply":"2023-11-26T22:38:27.326874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0')\n\n# Load a single image and display\nv_cap = cv2.VideoCapture(video_path_here)\nsuccess, frame = v_cap.read()\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nframe = Image.fromarray(frame)\n\nplt.figure(figsize=(12, 8))\nplt.imshow(frame)\nplt.axis('off')\nplt.show()\n\n# Detect face\nfaces = mtcnn(frame)\n\n# Visualize\nfig, axes = plt.subplots(1, len(faces))\nfor face, ax in zip(faces, axes):\n    ax.imshow(face.permute(1, 2, 0).int().numpy())\n    ax.axis('off')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:27.330989Z","iopub.execute_input":"2023-11-26T22:38:27.331611Z","iopub.status.idle":"2023-11-26T22:38:28.199971Z","shell.execute_reply.started":"2023-11-26T22:38:27.331353Z","shell.execute_reply":"2023-11-26T22:38:28.198893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0')\n\n# Load a single image and display\nv_cap = cv2.VideoCapture(video_path_here)\nsuccess, frame = v_cap.read()\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nframe = Image.fromarray(frame)\n\nplt.figure(figsize=(12, 8))\nplt.imshow(frame)\nplt.axis('off')\nplt.show()\n\n# Detect face\nfaces = mtcnn(frame)\nfaces2 = faces\n# # print(faces)\n# # print(type(faces))\n# print(type(face[0]))\n# print(face[0])\n# -------------------------------------need to uncomment\n# if isinstance(faces2, torch.Tensor):\n#     faces2 = faces2.cpu().numpy()\n\n# # print(type(faces))\n# # print(faces)\n# # Reshape the tensor to extract individual face coordinates\n# num_faces = faces2.shape[0]\n# for i in range(num_faces):\n#     # Extract coordinates from the tensor\n#     x, y, width, height = faces[i][0], faces[i][1], faces[i][2], faces[i][3]\n\n#     # Draw a rectangle around the face\n#     cv2.rectangle(frame, (x, y), (x + width, y + height), (0, 255, 0), 2)  # (0, 255, 0) is the color in BGR format, 2 is the thickness\n\n# # Display the frame with rectangles around faces\n# cv2.imshow('Detected Faces', frame)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n# ----------------------------------------upto here\n# Visualize\nfig, axes = plt.subplots(1, len(faces))\nfor face, ax in zip(faces, axes):\n    ax.imshow(face.permute(1, 2, 0).int().numpy())\n    ax.axis('off')\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:28.202074Z","iopub.execute_input":"2023-11-26T22:38:28.202797Z","iopub.status.idle":"2023-11-26T22:38:29.051967Z","shell.execute_reply.started":"2023-11-26T22:38:28.202714Z","shell.execute_reply":"2023-11-26T22:38:29.050900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Create face detector\n# mtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0')\n\n# # Load a video\n# v_cap = cv2.VideoCapture(video_path_here)\n# v_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n# # Loop through video, taking a handful of frames to form a batch\n# frames = []\n# for i in tqdm(range(v_len)):\n    \n#     # Load frame\n#     success = v_cap.grab()\n#     if i % 50 == 0:\n#         success, frame = v_cap.retrieve()\n#     else:\n#         continue\n#     if not success:\n#         continue\n        \n#     # Add to batch\n#     frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n#     frames.append(Image.fromarray(frame))\n\n# # Detect faces in batch\n# faces = mtcnn(frames)\n\n# fig, axes = plt.subplots(len(faces), 2, figsize=(6, 15))\n# for i, frame_faces in enumerate(faces):\n#     for j, face in enumerate(frame_faces):\n#         axes[i, j].imshow(face.permute(1, 2, 0).int().numpy())\n#         axes[i, j].axis('off')\n# fig.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:29.053950Z","iopub.execute_input":"2023-11-26T22:38:29.054651Z","iopub.status.idle":"2023-11-26T22:38:32.928608Z","shell.execute_reply.started":"2023-11-26T22:38:29.054581Z","shell.execute_reply":"2023-11-26T22:38:32.927453Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0')\n\n# Load a video\nv_cap = cv2.VideoCapture(video_path_here)\nv_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n# Loop through video, taking a handful of frames to form a batch\nframes = []\nframes_id = np.array([])\nfor i in tqdm(range(v_len)):\n    \n    # Load frame\n    success = v_cap.grab()\n    \n    # taking only 50 multiple frames     \n    if i % 50 == 0:\n        success, frame = v_cap.retrieve()\n    else:\n        continue\n    if not success:\n        continue\n        \n    # Add to batch\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    frames.append(Image.fromarray(frame))\n    frames_id.append(i)\n\n# Detect faces in batch\nfaces = mtcnn(frames)\n\nfig, axes = plt.subplots(len(faces), 2, figsize=(6, 15))\n\nfor i, frame_faces in enumerate(faces):\n    # If there are no faces detected in the frame, skip to the next iteration\n    if frame_faces is None:\n        continue\n    \n    # Determine the number of faces detected in the current frame\n    num_faces = len(frame_faces)\n    \n    for j in range(min(2, num_faces)):  # Plot up to 2 faces per row\n        axes[i, j].imshow(frame_faces[j].permute(1, 2, 0).int().numpy())\n        axes[i, j].axis('off')\n    \n    # If there's only one face detected, leave the second subplot empty\n    if num_faces == 1:\n        axes[i, 1].axis('off')\n\n# Hide any remaining empty subplots\nfor i in range(len(faces)):\n    for j in range(2):\n        if not axes[i, j].imshow:\n            axes[i, j].axis('off')\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:44.731902Z","iopub.execute_input":"2023-11-26T22:38:44.732245Z","iopub.status.idle":"2023-11-26T22:38:48.203920Z","shell.execute_reply.started":"2023-11-26T22:38:44.732184Z","shell.execute_reply":"2023-11-26T22:38:48.203179Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(margin=20, keep_all=True, post_process=False, device='cuda:0')\n\n# Load a video\nv_cap = cv2.VideoCapture(video_path_here)\nv_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n# Loop through video, taking a handful of frames to form a batch\nframes = []\nframes_ids = np.array([])\nfor i in tqdm(range(v_len)):\n    \n    # Load frame\n    success = v_cap.grab()\n    \n    # taking only 50 multiple frames     \n    if i % 50 == 0:\n        success, frame = v_cap.retrieve()\n    else:\n        continue\n    if not success:\n        continue\n        \n    # Add to batch\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    frames.append(Image.fromarray(frame))\n    frames_id.append(i)\n\nfor frame, frame_id in frames, frame_ids:\n    faces = mtcnn(frame)\n    \n    # for saving the faces in each frame     \n    for i, (frame, frame_id) in enumerate(zip(frames, frame_ids)):\n    # Detect faces in the frame\n    faces = mtcnn(frame)\n    \n    # Create a directory to save faces if it doesn't exist\n    faces_dir = f\"faces_{frame_id}\"\n    os.makedirs(faces_dir, exist_ok=True)\n    \n    # Save each detected face as an image\n    for j, face in enumerate(faces):\n        # Convert the PyTorch tensor to a PIL Image\n        face_image = Image.fromarray(face.permute(1, 2, 0).int().numpy())\n        \n        # Save the face image with a filename based on frame_id and face index\n        face_filename = f\"frame_{frame_id}_face_{j}.png\"\n        face_path = os.path.join(faces_dir, face_filename)\n        face_image.save(face_path)\n    \n    fig, axes = plt.subplots(len(faces), 2, figsize=(6, 15))\n\n    for i, frame_faces in enumerate(faces):\n        # If there are no faces detected in the frame, skip to the next iteration\n        if frame_faces is None:\n            continue\n    \n        # Determine the number of faces detected in the current frame\n        num_faces = len(frame_faces)\n    \n        for j in range(min(2, num_faces)):  # Plot up to 2 faces per row\n            axes[i, j].imshow(frame_faces[j].permute(1, 2, 0).int().numpy())\n            axes[i, j].axis('off')\n    \n        # If there's only one face detected, leave the second subplot empty\n        if num_faces == 1:\n            axes[i, 1].axis('off')\n\n    # Hide any remaining empty subplots\n    for i in range(len(faces)):\n        for j in range(2):\n            if not axes[i, j].imshow:\n                axes[i, j].axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load a video\nv_cap = cv2.VideoCapture(video_path_here)\nv_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n# Loop through video\nbatch_size = 16\nframes = []\nfaces = []\nfor _ in tqdm(range(v_len)):\n    \n    # Load frame\n    success, frame = v_cap.read()\n    if not success:\n        continue\n        \n    # Add to batch\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    frames.append(Image.fromarray(frame))\n    \n    # When batch is full, detect faces and reset batch list\n    if len(frames) >= batch_size:\n        faces.extend(mtcnn(frames))\n        frames = []\n\nplt.figure(figsize=(12, 4))\nplt.plot([len(f) for f in faces])\nplt.title('Detected faces per frame');","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:58.247830Z","iopub.execute_input":"2023-11-26T22:38:58.248134Z","iopub.status.idle":"2023-11-26T22:39:39.215467Z","shell.execute_reply.started":"2023-11-26T22:38:58.248087Z","shell.execute_reply":"2023-11-26T22:39:39.214662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(keep_all=True, device='cuda:0')\n\n# Load a single image and display\nv_cap = cv2.VideoCapture(video_path_here)\nsuccess, frame = v_cap.read()\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nframe = Image.fromarray(frame)\n\n# Detect face\nboxes, probs, landmarks = mtcnn.detect(frame, landmarks=True)\n\n# Visualize\nfig, ax = plt.subplots(figsize=(16, 12))\nax.imshow(frame)\nax.axis('off')\n\nfor box, landmark in zip(boxes, landmarks):\n    ax.scatter(*np.meshgrid(box[[0, 2]], box[[1, 3]]))\n    ax.scatter(landmark[:, 0], landmark[:, 1], s=8)\nfig.show()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:39:47.541268Z","iopub.execute_input":"2023-11-26T22:39:47.541653Z","iopub.status.idle":"2023-11-26T22:39:48.293094Z","shell.execute_reply.started":"2023-11-26T22:39:47.541593Z","shell.execute_reply":"2023-11-26T22:39:48.292264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create face detector\nmtcnn = MTCNN(keep_all=True, device='cuda:0')\n\n# Load a single image and display\nv_cap = cv2.VideoCapture(video_path_here)\nsuccess, frame = v_cap.read()\nframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\nframe = Image.fromarray(frame)\n\n# Detect face\nboxes, probs, landmarks = mtcnn.detect(frame, landmarks=True)\n\nif boxes is not None:\n    for box in boxes:\n        # Extract coordinates of the bounding box\n        x, y, w, h = box.astype(int)\n\n        # Draw a rectangle around the face\n        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) \n# Display the frame with rectangles around the faces\ncv2.imshow('Detected Faces', frame)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n# Visualize\nfig, ax = plt.subplots(figsize=(16, 12))\nax.imshow(frame)\nax.axis('off')\n\nfor box, landmark in zip(boxes, landmarks):\n    ax.scatter(*np.meshgrid(box[[0, 2]], box[[1, 3]]))\n    ax.scatter(landmark[:, 0], landmark[:, 1], s=8)\nfig.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load a video\nv_cap = cv2.VideoCapture(video_path_here)\n\n# Loop through video\nbatch_size = 32\nframes = []\nboxes = []\nlandmarks = []\nview_frames = []\nview_boxes = []\nview_landmarks = []\nfor _ in tqdm(range(v_len)):\n    \n    # Load frame\n    success, frame = v_cap.read()\n    if not success:\n        continue\n        \n    # Add to batch, resizing for speed\n    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    frame = Image.fromarray(frame)\n    frame = frame.resize([int(f * 0.25) for f in frame.size])\n    frames.append(frame)\n    \n    # When batch is full, detect faces and reset batch list\n    if len(frames) >= batch_size:\n        batch_boxes, _, batch_landmarks = mtcnn.detect(frames, landmarks=True)\n        boxes.extend(batch_boxes)\n        landmarks.extend(batch_landmarks)\n        \n        view_frames.append(frames[-1])\n        view_boxes.append(boxes[-1])\n        view_landmarks.append(landmarks[-1])\n        \n        frames = []\n\n# Visualize\nfig, ax = plt.subplots(3, 3, figsize=(18, 12))\nfor i in range(9):\n    ax[int(i / 3), i % 3].imshow(view_frames[i])\n    ax[int(i / 3), i % 3].axis('off')\n    for box, landmark in zip(view_boxes[i], view_landmarks[i]):\n        ax[int(i / 3), i % 3].scatter(*np.meshgrid(box[[0, 2]], box[[1, 3]]), s=8)\n        ax[int(i / 3), i % 3].scatter(landmark[:, 0], landmark[:, 1], s=6)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:40:00.305466Z","iopub.execute_input":"2023-11-26T22:40:00.305909Z","iopub.status.idle":"2023-11-26T22:40:11.289382Z","shell.execute_reply.started":"2023-11-26T22:40:00.305844Z","shell.execute_reply":"2023-11-26T22:40:11.288671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Single image\nmtcnn(frame, save_path='single_image.jpg');\n\n# Batch\nsave_paths = [f'image_{i}.jpg' for i in range(len(frames))]\nmtcnn(frames, save_path=save_paths);","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:40:29.619496Z","iopub.execute_input":"2023-11-26T22:40:29.619845Z","iopub.status.idle":"2023-11-26T22:40:30.088260Z","shell.execute_reply.started":"2023-11-26T22:40:29.619769Z","shell.execute_reply":"2023-11-26T22:40:30.087387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install keras_vggface","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:32.937129Z","iopub.status.idle":"2023-11-26T22:38:32.937531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install scipy","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:32.938444Z","iopub.status.idle":"2023-11-26T22:38:32.938872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from keras.preprocessing import image\n# from keras_vggface.vggface import VGGFace\n# from keras_vggface.utils import preprocess_input\n# import numpy as np\n# from scipy.spatial.distance import cosine\n\n# # Load VGGFace model with pretrained weights\n# vggface_model = VGGFace(model='vgg16', include_top=False, input_shape=(224, 224, 3), pooling='avg')\n\n# # Load images\n# img_path_1 = '/kaggle/input/true-data/11.png'\n# img_path_2 = '/kaggle/input/true-data/23.png'\n\n# # Load and preprocess images\n# def load_and_preprocess_image(img_path):\n#     img = image.load_img(img_path, target_size=(224, 224))\n#     img_array = image.img_to_array(img)\n#     img_array = np.expand_dims(img_array, axis=0)\n#     return preprocess_input(img_array.copy())\n\n# preprocessed_image_1 = load_and_preprocess_image(img_path_1)\n# preprocessed_image_2 = load_and_preprocess_image(img_path_2)\n\n# # Extract features from the images using VGGFace model\n# features_1 = vggface_model.predict(preprocessed_image_1)\n# features_2 = vggface_model.predict(preprocessed_image_2)\n\n# # Calculate cosine similarity between two face embeddings\n# similarity_scor = 1 - cosine(features_1, features_2)\n\n# # Define a threshold for face similarity\n# threshold = 0.7  # Example threshold value\n\n# # Determine if faces are a match based on the similarity score\n# if similarity_scor > threshold:\n#     print(similarity_scor)\n#     print(\"Faces are a match!\")\n# else:\n#     print(similarity_scor)\n#     print(\"Faces are not a match.\")","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:32.939740Z","iopub.status.idle":"2023-11-26T22:38:32.940244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.preprocessing import image\nfrom keras_vggface.vggface import VGGFace\nfrom keras_vggface.utils import preprocess_input\nimport numpy as np\nfrom scipy.spatial.distance import cosine\nfrom scipy.spatial.distance import euclidean\n\n# Loading VGGFace model with pretrained weights\nvggface_model = VGGFace(model='vgg16', include_top=False, input_shape=(224, 224, 3), pooling='avg')\n\n# Loading and preprocessing images\ndef load_and_preprocess_image(img_path):\n    img = image.load_img(img_path, target_size=(224, 224))\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    return preprocess_input(img_array.copy())\n\n# comparing two faces with cosine\ndef comparing_images_cosine(img_face_1, img_face_2):\n    preprocessed_image_1 = load_and_preprocess_image(img_face_1)\n    preprocessed_image_2 = load_and_preprocess_image(img_face_2)\n    \n    # Extract features from the images using VGGFace model\n    features_face_1 = vggface_model.predict(preprocessed_image_1)\n    features_face_2 = vggface_model.predict(preprocessed_image_2)\n    \n    # Calculate cosine similarity between two face embeddings\n    similarity_score = 1 - cosine(features_face_1, features_face_2)\n\n    # Define a threshold for face similarity\n    threshold = 0.7  # Example threshold value\n    \n    # saving the result as numpy array\n    result_array = np.array([similarity_score > threshold, img_face_1])\n    \n    #returning all the best match faces\n    return result_array\n\n# comparing similar faces on euclidean_distance\ndef comparing_images_euclidean(similar_faces, img_face_2):\n    \n# creating a numpy array  \n    euclidean_distances = np.array([])\n    \n# generating preprocessed image from image 2\n    preprocessed_image_1 = load_and_preprocess_image(img_path_2)\n    \n# extracting features from preprocessed_image 1\n    features_face_1 = vggface_model.predict(preprocessed_image_1)\n    \n# finding euclidean distances for all images from the suspect image \n    for face in similar_faces:\n        preprocessed_image_2 = load_and_preprocess_image(face)\n        features_face_2 = vggface_model.predict(preprocessed_image_2)\n        euclidean_distance = euclidean(features_face_2, features_face_1)\n        euclidean_distances.append(euclidean_distance)\n    \n    min_distance= euclidean_distances[0]\n    detected_face= similar_faces[0]\n    \n# finding the best match\n    for i,j in simiiar_faces,euclidean_distances: \n        if min_distance>j: \n            min_distance=j\n            detected_face=i\n    \n# output the best match\n    return detected_face\n","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:32.941311Z","iopub.status.idle":"2023-11-26T22:38:32.941806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"extracted_faces = '/kaggle/working/extracted_faces'\ndatabase_faces = '/kaggle/working/database_faces'\n\n# Iterate through the database_faces\nfor database_face in os.listdir(database_faces):\n    database_face_path = os.path.join(database_faces, database_face)\n    \n    # Initialize an empty list to store similar faces\n    similar_faces = np.array([])\n    \n    # Iterate through the extracted_faces\n    for extracted_face in os.listdir(extracted_faces):\n        extracted_face_path = os.path.join(extracted_faces, extracted_face)\n        \n        # Compare faces using cosine similarity (this part is just a placeholder)\n        compared_face = comparing_images_cosine(extracted_face_path, database_face_path)\n        if compared_face[0] == True:\n            similar_faces.append(extracted_face_path)\n    \n    # If similar faces were found\n    if len(similar_faces) > 0:\n        matched_face = comparing_images_euclidean(similar_faces, img_face_2)\n        \n        # Assuming matched_face is the path of the matched face\n        if matched_face is not None:\n            matched_basename = os.path.basename(matched_face)\n            database_basename = os.path.basename(database_face_path)\n            print(\"Matched face:\", matched_basename)\n            matched_face_pic = cv2.imread(matched_face)\n            cv2.imshow('Matched face', matched_face_pic)\n            print(\"Database_face:\", database_basename)\n            database_face_pic = cv2.imread(database_face_path)\n            cv2.imshow('Database_face', database_face_pic)\n            cv2.waitKey(0)\n            cv2.destroyAllWindows()","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:38:32.942775Z","iopub.status.idle":"2023-11-26T22:38:32.943357Z"},"trusted":true},"execution_count":null,"outputs":[]}]}