Delete Wav2Lip-master
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Wav2Lip-master/.gitignoreDeleted-16
- Wav2Lip-master/README.mdDeleted-168
- Wav2Lip-master/__pycache__/audio.cpython-310.pycDeleted
- Wav2Lip-master/__pycache__/audio.cpython-311.pycDeleted
- Wav2Lip-master/__pycache__/audio.cpython-38.pycDeleted
- Wav2Lip-master/__pycache__/hparams.cpython-311.pycDeleted
- Wav2Lip-master/__pycache__/hparams.cpython-38.pycDeleted
- Wav2Lip-master/audio.pyDeleted-136
- Wav2Lip-master/checkpoints/README.mdDeleted-1
- Wav2Lip-master/color_syncnet_train.pyDeleted-279
- Wav2Lip-master/evaluation/README.mdDeleted-63
- Wav2Lip-master/evaluation/gen_videos_from_filelist.pyDeleted-238
- Wav2Lip-master/evaluation/real_videos_inference.pyDeleted-305
- Wav2Lip-master/evaluation/scores_LSE/SyncNetInstance_calc_scores.pyDeleted-210
- Wav2Lip-master/evaluation/scores_LSE/calculate_scores_LRS.pyDeleted-53
- Wav2Lip-master/evaluation/scores_LSE/calculate_scores_real_videos.pyDeleted-45
- Wav2Lip-master/evaluation/scores_LSE/calculate_scores_real_videos.shDeleted-8
- Wav2Lip-master/evaluation/test_filelists/README.mdDeleted-13
- Wav2Lip-master/evaluation/test_filelists/ReSyncED/random_pairs.txtDeleted-160
- Wav2Lip-master/evaluation/test_filelists/ReSyncED/tts_pairs.txtDeleted-18
- Wav2Lip-master/evaluation/test_filelists/lrs2.txtDeleted
- Wav2Lip-master/evaluation/test_filelists/lrs3.txtDeleted
- Wav2Lip-master/evaluation/test_filelists/lrw.txtDeleted
- Wav2Lip-master/face_detection/README.mdDeleted-1
- Wav2Lip-master/face_detection/__init__.pyDeleted-7
- Wav2Lip-master/face_detection/__pycache__/__init__.cpython-311.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/__init__.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/api.cpython-311.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/api.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/models.cpython-311.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/models.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/utils.cpython-311.pycDeleted
- Wav2Lip-master/face_detection/__pycache__/utils.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/api.pyDeleted-79
- Wav2Lip-master/face_detection/detection/__init__.pyDeleted-1
- Wav2Lip-master/face_detection/detection/__pycache__/__init__.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/__pycache__/core.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/core.pyDeleted-130
- Wav2Lip-master/face_detection/detection/sfd/__init__.pyDeleted-1
- Wav2Lip-master/face_detection/detection/sfd/__pycache__/__init__.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/sfd/__pycache__/bbox.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/sfd/__pycache__/detect.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/sfd/__pycache__/net_s3fd.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/sfd/__pycache__/sfd_detector.cpython-38.pycDeleted
- Wav2Lip-master/face_detection/detection/sfd/bbox.pyDeleted-129
- Wav2Lip-master/face_detection/detection/sfd/detect.pyDeleted-112
- Wav2Lip-master/face_detection/detection/sfd/net_s3fd.pyDeleted-129
- Wav2Lip-master/face_detection/detection/sfd/s3fd.pthDeleted-3
- Wav2Lip-master/face_detection/detection/sfd/sfd_detector.pyDeleted-59
- Wav2Lip-master/face_detection/models.pyDeleted-261
12345678910111213141516*.pkl*.jpg*.mp4*.pth*.pyc__pycache__*.h5*.avi*.wavfilelists/*.txtevaluation/test_filelists/lr*.txt*.pyc*.mkv*.gif*.webm*.mp3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168python .\inference.py --checkpoint_path .\wav2lip_gan.pth --face ..\face_input\input_video.mp3 --audio ..\wav_output\response.wav
# **Wav2Lip**: *Accurately Lip-syncing Videos In The Wild*
### Wav2Lip is hosted for free at [Sync Labs](https://synclabs.so/)
Are you looking to integrate this into a product? We have a turn-key hosted API with new and improved lip-syncing models here: https://synclabs.so/
For any other commercial / enterprise requests, please contact us at pavan@synclabs.so and prady@synclabs.so
To reach out to the authors directly you can reach us at prajwal@synclabs.so, rudrabha@synclabs.so.
This code is part of the paper: _A Lip Sync Expert Is All You Need for Speech to Lip Generation In the Wild_ published at ACM Multimedia 2020.
[](https://paperswithcode.com/sota/lip-sync-on-lrs2?p=a-lip-sync-expert-is-all-you-need-for-speech)[](https://paperswithcode.com/sota/lip-sync-on-lrs3?p=a-lip-sync-expert-is-all-you-need-for-speech)[](https://paperswithcode.com/sota/lip-sync-on-lrw?p=a-lip-sync-expert-is-all-you-need-for-speech)
|📑 Original Paper|📰 Project Page|🌀 Demo|⚡ Live Testing|📔 Colab Notebook|:-:|:-:|:-:|:-:|:-:|[Paper](http://arxiv.org/abs/2008.10010) | [Project Page](http://cvit.iiit.ac.in/research/projects/cvit-projects/a-lip-sync-expert-is-all-you-need-for-speech-to-lip-generation-in-the-wild/) | [Demo Video](https://youtu.be/0fXaDCZNOJc) | [Interactive Demo](https://synclabs.so/) | [Colab Notebook](https://colab.research.google.com/drive/1tZpDWXz49W6wDcTprANRGLo2D_EbD5J8?usp=sharing) /[Updated Collab Notebook](https://colab.research.google.com/drive/1IjFW1cLevs6Ouyu4Yht4mnR4yeuMqO7Y#scrollTo=MH1m608OymLH) 
----------**Highlights**---------- - Weights of the visual quality disc has been updated in readme! - Lip-sync videos to any target speech with high accuracy :100:. Try our [interactive demo](https://synclabs.so/). - :sparkles: Works for any identity, voice, and language. Also works for CGI faces and synthetic voices. - Complete training code, inference code, and pretrained models are available :boom: - Or, quick-start with the Google Colab Notebook: [Link](https://colab.research.google.com/drive/1tZpDWXz49W6wDcTprANRGLo2D_EbD5J8?usp=sharing). Checkpoints and samples are available in a Google Drive [folder](https://drive.google.com/drive/folders/1I-0dNLfFOSFwrfqjNa-SXuwaURHE5K4k?usp=sharing) as well. There is also a [tutorial video](https://www.youtube.com/watch?v=Ic0TBhfuOrA) on this, courtesy of [What Make Art](https://www.youtube.com/channel/UCmGXH-jy0o2CuhqtpxbaQgA). Also, thanks to [Eyal Gruss](https://eyalgruss.com), there is a more accessible [Google Colab notebook](https://j.mp/wav2lip) with more useful features. A tutorial collab notebook is present at this [link](https://colab.research.google.com/drive/1IjFW1cLevs6Ouyu4Yht4mnR4yeuMqO7Y#scrollTo=MH1m608OymLH). - :fire: :fire: Several new, reliable evaluation benchmarks and metrics [[`evaluation/` folder of this repo]](https://github.com/Rudrabha/Wav2Lip/tree/master/evaluation) released. Instructions to calculate the metrics reported in the paper are also present.
--------**Disclaimer**--------All results from this open-source code or our [demo website](https://bhaasha.iiit.ac.in/lipsync) should only be used for research/academic/personal purposes only. As the models are trained on the <a href="http://www.robots.ox.ac.uk/~vgg/data/lip_reading/lrs2.html">LRS2 dataset</a>, any form of commercial use is strictly prohibited. For commercial requests please contact us directly!
Prerequisites-------------- `Python 3.6` - ffmpeg: `sudo apt-get install ffmpeg`- Install necessary packages using `pip install -r requirements.txt`. Alternatively, instructions for using a docker image is provided [here](https://gist.github.com/xenogenesi/e62d3d13dadbc164124c830e9c453668). Have a look at [this comment](https://github.com/Rudrabha/Wav2Lip/issues/131#issuecomment-725478562) and comment on [the gist](https://gist.github.com/xenogenesi/e62d3d13dadbc164124c830e9c453668) if you encounter any issues. - Face detection [pre-trained model](https://www.adrianbulat.com/downloads/python-fan/s3fd-619a316812.pth) should be downloaded to `face_detection/detection/sfd/s3fd.pth`. Alternative [link](https://iiitaphyd-my.sharepoint.com/:u:/g/personal/prajwal_k_research_iiit_ac_in/EZsy6qWuivtDnANIG73iHjIBjMSoojcIV0NULXV-yiuiIg?e=qTasa8) if the above does not work.
Getting the weights----------| Model | Description | Link to the model | | :-------------: | :---------------: | :---------------: || Wav2Lip | Highly accurate lip-sync | [Link](https://iiitaphyd-my.sharepoint.com/:u:/g/personal/radrabha_m_research_iiit_ac_in/Eb3LEzbfuKlJiR600lQWRxgBIY27JZg80f7V9jtMfbNDaQ?e=TBFBVW) || Wav2Lip + GAN | Slightly inferior lip-sync, but better visual quality | [Link](https://iiitaphyd-my.sharepoint.com/:u:/g/personal/radrabha_m_research_iiit_ac_in/EdjI7bZlgApMqsVoEUUXpLsBxqXbn5z8VTmoxp55YNDcIA?e=n9ljGW) || Expert Discriminator | Weights of the expert discriminator | [Link](https://iiitaphyd-my.sharepoint.com/:u:/g/personal/radrabha_m_research_iiit_ac_in/EQRvmiZg-HRAjvI6zqN9eTEBP74KefynCwPWVmF57l-AYA?e=ZRPHKP) || Visual Quality Discriminator | Weights of the visual disc trained in a GAN setup | [Link](https://iiitaphyd-my.sharepoint.com/:u:/g/personal/radrabha_m_research_iiit_ac_in/EQVqH88dTm1HjlK11eNba5gBbn15WMS0B0EZbDBttqrqkg?e=ic0ljo) |
Lip-syncing videos using the pre-trained models (Inference)-------You can lip-sync any video to any audio:```bashpython inference.py --checkpoint_path <ckpt> --face <video.mp4> --audio <an-audio-source> ```The result is saved (by default) in `results/result_voice.mp4`. You can specify it as an argument, similar to several other available options. The audio source can be any file supported by `FFMPEG` containing audio data: `*.wav`, `*.mp3` or even a video file, from which the code will automatically extract the audio.
##### Tips for better results:- Experiment with the `--pads` argument to adjust the detected face bounding box. Often leads to improved results. You might need to increase the bottom padding to include the chin region. E.g. `--pads 0 20 0 0`.- If you see the mouth position dislocated or some weird artifacts such as two mouths, then it can be because of over-smoothing the face detections. Use the `--nosmooth` argument and give it another try. - Experiment with the `--resize_factor` argument, to get a lower-resolution video. Why? The models are trained on faces that were at a lower resolution. You might get better, visually pleasing results for 720p videos than for 1080p videos (in many cases, the latter works well too). - The Wav2Lip model without GAN usually needs more experimenting with the above two to get the most ideal results, and sometimes, can give you a better result as well.
Preparing LRS2 for training----------Our models are trained on LRS2. See [here](#training-on-datasets-other-than-lrs2) for a few suggestions regarding training on other datasets.##### LRS2 dataset folder structure
```data_root (mvlrs_v1)├── main, pretrain (we use only main folder in this work)| ├── list of folders| │ ├── five-digit numbered video IDs ending with (.mp4)```
Place the LRS2 filelists (train, val, test) `.txt` files in the `filelists/` folder.
##### Preprocess the dataset for fast training
```bashpython preprocess.py --data_root data_root/main --preprocessed_root lrs2_preprocessed/```Additional options like `batch_size` and the number of GPUs to use in parallel to use can also be set.
##### Preprocessed LRS2 folder structure```preprocessed_root (lrs2_preprocessed)├── list of folders| ├── Folders with five-digit numbered video IDs| │ ├── *.jpg| │ ├── audio.wav```
Train!----------There are two major steps: (i) Train the expert lip-sync discriminator, (ii) Train the Wav2Lip model(s).
##### Training the expert discriminatorYou can download [the pre-trained weights](#getting-the-weights) if you want to skip this step. To train it:```bashpython color_syncnet_train.py --data_root lrs2_preprocessed/ --checkpoint_dir <folder_to_save_checkpoints>```##### Training the Wav2Lip modelsYou can either train the model without the additional visual quality discriminator (< 1 day of training) or use the discriminator (~2 days). For the former, run: ```bashpython wav2lip_train.py --data_root lrs2_preprocessed/ --checkpoint_dir <folder_to_save_checkpoints> --syncnet_checkpoint_path <path_to_expert_disc_checkpoint>```
To train with the visual quality discriminator, you should run `hq_wav2lip_train.py` instead. The arguments for both files are similar. In both cases, you can resume training as well. Look at `python wav2lip_train.py --help` for more details. You can also set additional less commonly-used hyper-parameters at the bottom of the `hparams.py` file.
Training on datasets other than LRS2------------------------------------Training on other datasets might require modifications to the code. Please read the following before you raise an issue:
- You might not get good results by training/fine-tuning on a few minutes of a single speaker. This is a separate research problem, to which we do not have a solution yet. Thus, we would most likely not be able to resolve your issue. - You must train the expert discriminator for your own dataset before training Wav2Lip.- If it is your own dataset downloaded from the web, in most cases, needs to be sync-corrected.- Be mindful of the FPS of the videos of your dataset. Changes to FPS would need significant code changes. - The expert discriminator's eval loss should go down to ~0.25 and the Wav2Lip eval sync loss should go down to ~0.2 to get good results.
When raising an issue on this topic, please let us know that you are aware of all these points.
We have an HD model trained on a dataset allowing commercial usage. The size of the generated face will be 192 x 288 in our new model.
Evaluation----------Please check the `evaluation/` folder for the instructions.
License and Citation----------This repository can only be used for personal/research/non-commercial purposes. However, for commercial requests, please contact us directly at rudrabha@synclabs.so or prajwal@synclabs.so. We have a turn-key hosted API with new and improved lip-syncing models here: https://synclabs.so/The size of the generated face will be 192 x 288 in our new models. Please cite the following paper if you use this repository:```@inproceedings{10.1145/3394171.3413532,author = {Prajwal, K R and Mukhopadhyay, Rudrabha and Namboodiri, Vinay P. and Jawahar, C.V.},title = {A Lip Sync Expert Is All You Need for Speech to Lip Generation In the Wild},year = {2020},isbn = {9781450379885},publisher = {Association for Computing Machinery},address = {New York, NY, USA},url = {https://doi.org/10.1145/3394171.3413532},doi = {10.1145/3394171.3413532},booktitle = {Proceedings of the 28th ACM International Conference on Multimedia},pages = {484–492},numpages = {9},keywords = {lip sync, talking face generation, video generation},location = {Seattle, WA, USA},series = {MM '20}}```
Acknowledgments----------Parts of the code structure are inspired by this [TTS repository](https://github.com/r9y9/deepvoice3_pytorch). We thank the author for this wonderful code. The code for Face Detection has been taken from the [face_alignment](https://github.com/1adrianb/face-alignment) repository. We thank the authors for releasing their code and models. We thank [zabique](https://github.com/zabique) for the tutorial collab notebook.
## Acknowledgements
- [Awesome Readme Templates](https://awesomeopensource.com/project/elangosundar/awesome-README-templates) - [Awesome README](https://github.com/matiassingers/awesome-readme) - [How to write a Good readme](https://bulldogjob.com/news/449-how-to-write-a-good-readme-for-your-github-project)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import librosaimport librosa.filtersimport numpy as np# import tensorflow as tffrom scipy import signalfrom scipy.io import wavfilefrom hparams import hparams as hp
def load_wav(path, sr): return librosa.core.load(path, sr=sr)[0]
def save_wav(wav, path, sr): wav *= 32767 / max(0.01, np.max(np.abs(wav))) #proposed by @dsmiller wavfile.write(path, sr, wav.astype(np.int16))
def save_wavenet_wav(wav, path, sr): librosa.output.write_wav(path, wav, sr=sr)
def preemphasis(wav, k, preemphasize=True): if preemphasize: return signal.lfilter([1, -k], [1], wav) return wav
def inv_preemphasis(wav, k, inv_preemphasize=True): if inv_preemphasize: return signal.lfilter([1], [1, -k], wav) return wav
def get_hop_size(): hop_size = hp.hop_size if hop_size is None: assert hp.frame_shift_ms is not None hop_size = int(hp.frame_shift_ms / 1000 * hp.sample_rate) return hop_size
def linearspectrogram(wav): D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) S = _amp_to_db(np.abs(D)) - hp.ref_level_db if hp.signal_normalization: return _normalize(S) return S
def melspectrogram(wav): D = _stft(preemphasis(wav, hp.preemphasis, hp.preemphasize)) S = _amp_to_db(_linear_to_mel(np.abs(D))) - hp.ref_level_db if hp.signal_normalization: return _normalize(S) return S
def _lws_processor(): import lws return lws.lws(hp.n_fft, get_hop_size(), fftsize=hp.win_size, mode="speech")
def _stft(y): if hp.use_lws: return _lws_processor(hp).stft(y).T else: return librosa.stft(y=y, n_fft=hp.n_fft, hop_length=get_hop_size(), win_length=hp.win_size)
###########################################################Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!)def num_frames(length, fsize, fshift): """Compute number of time frames of spectrogram """ pad = (fsize - fshift) if length % fshift == 0: M = (length + pad * 2 - fsize) // fshift + 1 else: M = (length + pad * 2 - fsize) // fshift + 2 return M
def pad_lr(x, fsize, fshift): """Compute left and right padding """ M = num_frames(len(x), fsize, fshift) pad = (fsize - fshift) T = len(x) + 2 * pad r = (M - 1) * fshift + fsize - T return pad, pad + r###########################################################Librosa correct paddingdef librosa_pad_lr(x, fsize, fshift): return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]
# Conversions_mel_basis = None
def _linear_to_mel(spectogram): global _mel_basis if _mel_basis is None: _mel_basis = _build_mel_basis() return np.dot(_mel_basis, spectogram)
def _build_mel_basis(): assert hp.fmax <= hp.sample_rate // 2 return librosa.filters.mel(sr=hp.sample_rate, n_fft= hp.n_fft, n_mels=hp.num_mels, fmin=hp.fmin, fmax=hp.fmax)
def _amp_to_db(x): min_level = np.exp(hp.min_level_db / 20 * np.log(10)) return 20 * np.log10(np.maximum(min_level, x))
def _db_to_amp(x): return np.power(10.0, (x) * 0.05)
def _normalize(S): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return np.clip((2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value, -hp.max_abs_value, hp.max_abs_value) else: return np.clip(hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db)), 0, hp.max_abs_value) assert S.max() <= 0 and S.min() - hp.min_level_db >= 0 if hp.symmetric_mels: return (2 * hp.max_abs_value) * ((S - hp.min_level_db) / (-hp.min_level_db)) - hp.max_abs_value else: return hp.max_abs_value * ((S - hp.min_level_db) / (-hp.min_level_db))
def _denormalize(D): if hp.allow_clipping_in_normalization: if hp.symmetric_mels: return (((np.clip(D, -hp.max_abs_value, hp.max_abs_value) + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((np.clip(D, 0, hp.max_abs_value) * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db) if hp.symmetric_mels: return (((D + hp.max_abs_value) * -hp.min_level_db / (2 * hp.max_abs_value)) + hp.min_level_db) else: return ((D * -hp.min_level_db / hp.max_abs_value) + hp.min_level_db)1Place all your checkpoints (.pth files) here. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279from os.path import dirname, join, basename, isfilefrom tqdm import tqdm
from models import SyncNet_color as SyncNetimport audio
import torchfrom torch import nnfrom torch import optimimport torch.backends.cudnn as cudnnfrom torch.utils import data as data_utilsimport numpy as np
from glob import glob
import os, random, cv2, argparsefrom hparams import hparams, get_image_list
parser = argparse.ArgumentParser(description='Code to train the expert lip-sync discriminator')
parser.add_argument("--data_root", help="Root folder of the preprocessed LRS2 dataset", required=True)
parser.add_argument('--checkpoint_dir', help='Save checkpoints to this directory', required=True, type=str)parser.add_argument('--checkpoint_path', help='Resumed from this checkpoint', default=None, type=str)
args = parser.parse_args()
global_step = 0global_epoch = 0use_cuda = torch.cuda.is_available()print('use_cuda: {}'.format(use_cuda))
syncnet_T = 5syncnet_mel_step_size = 16
class Dataset(object): def __init__(self, split): self.all_videos = get_image_list(args.data_root, split)
def get_frame_id(self, frame): return int(basename(frame).split('.')[0])
def get_window(self, start_frame): start_id = self.get_frame_id(start_frame) vidname = dirname(start_frame)
window_fnames = [] for frame_id in range(start_id, start_id + syncnet_T): frame = join(vidname, '{}.jpg'.format(frame_id)) if not isfile(frame): return None window_fnames.append(frame) return window_fnames
def crop_audio_window(self, spec, start_frame): # num_frames = (T x hop_size * fps) / sample_rate start_frame_num = self.get_frame_id(start_frame) start_idx = int(80. * (start_frame_num / float(hparams.fps)))
end_idx = start_idx + syncnet_mel_step_size
return spec[start_idx : end_idx, :]
def __len__(self): return len(self.all_videos)
def __getitem__(self, idx): while 1: idx = random.randint(0, len(self.all_videos) - 1) vidname = self.all_videos[idx]
img_names = list(glob(join(vidname, '*.jpg'))) if len(img_names) <= 3 * syncnet_T: continue img_name = random.choice(img_names) wrong_img_name = random.choice(img_names) while wrong_img_name == img_name: wrong_img_name = random.choice(img_names)
if random.choice([True, False]): y = torch.ones(1).float() chosen = img_name else: y = torch.zeros(1).float() chosen = wrong_img_name
window_fnames = self.get_window(chosen) if window_fnames is None: continue
window = [] all_read = True for fname in window_fnames: img = cv2.imread(fname) if img is None: all_read = False break try: img = cv2.resize(img, (hparams.img_size, hparams.img_size)) except Exception as e: all_read = False break
window.append(img)
if not all_read: continue
try: wavpath = join(vidname, "audio.wav") wav = audio.load_wav(wavpath, hparams.sample_rate)
orig_mel = audio.melspectrogram(wav).T except Exception as e: continue
mel = self.crop_audio_window(orig_mel.copy(), img_name)
if (mel.shape[0] != syncnet_mel_step_size): continue
# H x W x 3 * T x = np.concatenate(window, axis=2) / 255. x = x.transpose(2, 0, 1) x = x[:, x.shape[1]//2:]
x = torch.FloatTensor(x) mel = torch.FloatTensor(mel.T).unsqueeze(0)
return x, mel, y
logloss = nn.BCELoss()def cosine_loss(a, v, y): d = nn.functional.cosine_similarity(a, v) loss = logloss(d.unsqueeze(1), y)
return loss
def train(device, model, train_data_loader, test_data_loader, optimizer, checkpoint_dir=None, checkpoint_interval=None, nepochs=None):
global global_step, global_epoch resumed_step = global_step while global_epoch < nepochs: running_loss = 0. prog_bar = tqdm(enumerate(train_data_loader)) for step, (x, mel, y) in prog_bar: model.train() optimizer.zero_grad()
# Transform data to CUDA device x = x.to(device)
mel = mel.to(device)
a, v = model(mel, x) y = y.to(device)
loss = cosine_loss(a, v, y) loss.backward() optimizer.step()
global_step += 1 cur_session_steps = global_step - resumed_step running_loss += loss.item()
if global_step == 1 or global_step % checkpoint_interval == 0: save_checkpoint( model, optimizer, global_step, checkpoint_dir, global_epoch)
if global_step % hparams.syncnet_eval_interval == 0: with torch.no_grad(): eval_model(test_data_loader, global_step, device, model, checkpoint_dir)
prog_bar.set_description('Loss: {}'.format(running_loss / (step + 1)))
global_epoch += 1
def eval_model(test_data_loader, global_step, device, model, checkpoint_dir): eval_steps = 1400 print('Evaluating for {} steps'.format(eval_steps)) losses = [] while 1: for step, (x, mel, y) in enumerate(test_data_loader):
model.eval()
# Transform data to CUDA device x = x.to(device)
mel = mel.to(device)
a, v = model(mel, x) y = y.to(device)
loss = cosine_loss(a, v, y) losses.append(loss.item())
if step > eval_steps: break
averaged_loss = sum(losses) / len(losses) print(averaged_loss)
return
def save_checkpoint(model, optimizer, step, checkpoint_dir, epoch):
checkpoint_path = join( checkpoint_dir, "checkpoint_step{:09d}.pth".format(global_step)) optimizer_state = optimizer.state_dict() if hparams.save_optimizer_state else None torch.save({ "state_dict": model.state_dict(), "optimizer": optimizer_state, "global_step": step, "global_epoch": epoch, }, checkpoint_path) print("Saved checkpoint:", checkpoint_path)
def _load(checkpoint_path): if use_cuda: checkpoint = torch.load(checkpoint_path) else: checkpoint = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) return checkpoint
def load_checkpoint(path, model, optimizer, reset_optimizer=False): global global_step global global_epoch
print("Load checkpoint from: {}".format(path)) checkpoint = _load(path) model.load_state_dict(checkpoint["state_dict"]) if not reset_optimizer: optimizer_state = checkpoint["optimizer"] if optimizer_state is not None: print("Load optimizer state from {}".format(path)) optimizer.load_state_dict(checkpoint["optimizer"]) global_step = checkpoint["global_step"] global_epoch = checkpoint["global_epoch"]
return model
if __name__ == "__main__": checkpoint_dir = args.checkpoint_dir checkpoint_path = args.checkpoint_path
if not os.path.exists(checkpoint_dir): os.mkdir(checkpoint_dir)
# Dataset and Dataloader setup train_dataset = Dataset('train') test_dataset = Dataset('val')
train_data_loader = data_utils.DataLoader( train_dataset, batch_size=hparams.syncnet_batch_size, shuffle=True, num_workers=hparams.num_workers)
test_data_loader = data_utils.DataLoader( test_dataset, batch_size=hparams.syncnet_batch_size, num_workers=8)
device = torch.device("cuda" if use_cuda else "cpu")
# Model model = SyncNet().to(device) print('total trainable params {}'.format(sum(p.numel() for p in model.parameters() if p.requires_grad)))
optimizer = optim.Adam([p for p in model.parameters() if p.requires_grad], lr=hparams.syncnet_lr)
if checkpoint_path is not None: load_checkpoint(checkpoint_path, model, optimizer, reset_optimizer=False)
train(device, model, train_data_loader, test_data_loader, optimizer, checkpoint_dir=checkpoint_dir, checkpoint_interval=hparams.syncnet_checkpoint_interval, nepochs=hparams.nepochs)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# Novel Evaluation Framework, new filelists, and using the LSE-D and LSE-C metric.
Our paper also proposes a novel evaluation framework (Section 4). To evaluate on LRS2, LRS3, and LRW, the filelists are present in the `test_filelists` folder. Please use `gen_videos_from_filelist.py` script to generate the videos. After that, you can calculate the LSE-D and LSE-C scores using the instructions below. Please see [this thread](https://github.com/Rudrabha/Wav2Lip/issues/22#issuecomment-712825380) on how to calculate the FID scores.
The videos of the ReSyncED benchmark for real-world evaluation will be released soon.
### Steps to set-up the evaluation repository for LSE-D and LSE-C metric:We use the pre-trained syncnet model available in this [repository](https://github.com/joonson/syncnet_python).
* Clone the SyncNet repository.``` git clone https://github.com/joonson/syncnet_python.git ```* Follow the procedure given in the above linked [repository](https://github.com/joonson/syncnet_python) to download the pretrained models and set up the dependencies. * **Note: Please install a separate virtual environment for the evaluation scripts. The versions used by Wav2Lip and the publicly released code of SyncNet is different and can cause version mis-match issues. To avoid this, we suggest the users to install a separate virtual environment for the evaluation scripts**```cd syncnet_pythonpip install -r requirements.txtsh download_model.sh```* The above step should ensure that all the dependencies required by the repository is installed and the pre-trained models are downloaded.
### Running the evaluation scripts:* Copy our evaluation scripts given in this folder to the cloned repository.``` cd Wav2Lip/evaluation/scores_LSE/ cp *.py syncnet_python/ cp *.sh syncnet_python/ ```**Note: We will release the test filelists for LRW, LRS2 and LRS3 shortly once we receive permission from the dataset creators. We will also release the Real World Dataset we have collected shortly.**
* Our evaluation technique does not require ground-truth of any sorts. Given lip-synced videos we can directly calculate the scores from only the generated videos. Please store the generated videos (from our test sets or your own generated videos) in the following folder structure.```video data root (Folder containing all videos)├── All .mp4 files```* Change the folder back to the cloned repository. ```cd syncnet_python```* To run evaluation on the LRW, LRS2 and LRS3 test files, please run the following command:```python calculate_scores_LRS.py --data_root /path/to/video/data/root --tmp_dir tmp_dir/```
* To run evaluation on the ReSynced dataset or your own generated videos, please run the following command:```sh calculate_scores_real_videos.sh /path/to/video/data/root```* The generated scores will be present in the all_scores.txt generated in the ```syncnet_python/``` folder
# Evaluation of image quality using FID metric.We use the [pytorch-fid](https://github.com/mseitzer/pytorch-fid) repository for calculating the FID metrics. We dump all the frames in both ground-truth and generated videos and calculate the FID score.
# Opening issues related to evaluation scripts* Please open the issues with the "Evaluation" label if you face any issues in the evaluation scripts.
# AcknowledgementsOur evaluation pipeline in based on two existing repositories. LSE metrics are based on the [syncnet_python](https://github.com/joonson/syncnet_python) repository and the FID score is based on [pytorch-fid](https://github.com/mseitzer/pytorch-fid) repository. We thank the authors of both the repositories for releasing their wonderful code.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238from os import listdir, pathimport numpy as npimport scipy, cv2, os, sys, argparseimport dlib, json, subprocessfrom tqdm import tqdmfrom glob import globimport torch
sys.path.append('../')import audioimport face_detectionfrom models import Wav2Lip
parser = argparse.ArgumentParser(description='Code to generate results for test filelists')
parser.add_argument('--filelist', type=str, help='Filepath of filelist file to read', required=True)parser.add_argument('--results_dir', type=str, help='Folder to save all results into', required=True)parser.add_argument('--data_root', type=str, required=True)parser.add_argument('--checkpoint_path', type=str, help='Name of saved checkpoint to load weights from', required=True)
parser.add_argument('--pads', nargs='+', type=int, default=[0, 0, 0, 0], help='Padding (top, bottom, left, right)')parser.add_argument('--face_det_batch_size', type=int, help='Single GPU batch size for face detection', default=64)parser.add_argument('--wav2lip_batch_size', type=int, help='Batch size for Wav2Lip', default=128)
# parser.add_argument('--resize_factor', default=1, type=int)
args = parser.parse_args()args.img_size = 96
def get_smoothened_boxes(boxes, T): for i in range(len(boxes)): if i + T > len(boxes): window = boxes[len(boxes) - T:] else: window = boxes[i : i + T] boxes[i] = np.mean(window, axis=0) return boxes
def face_detect(images): batch_size = args.face_det_batch_size while 1: predictions = [] try: for i in range(0, len(images), batch_size): predictions.extend(detector.get_detections_for_batch(np.array(images[i:i + batch_size]))) except RuntimeError: if batch_size == 1: raise RuntimeError('Image too big to run face detection on GPU') batch_size //= 2 args.face_det_batch_size = batch_size print('Recovering from OOM error; New batch size: {}'.format(batch_size)) continue break
results = [] pady1, pady2, padx1, padx2 = args.pads for rect, image in zip(predictions, images): if rect is None: raise ValueError('Face not detected!')
y1 = max(0, rect[1] - pady1) y2 = min(image.shape[0], rect[3] + pady2) x1 = max(0, rect[0] - padx1) x2 = min(image.shape[1], rect[2] + padx2) results.append([x1, y1, x2, y2])
boxes = get_smoothened_boxes(np.array(results), T=5) results = [[image[y1: y2, x1:x2], (y1, y2, x1, x2), True] for image, (x1, y1, x2, y2) in zip(images, boxes)]
return results
def datagen(frames, face_det_results, mels): img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
for i, m in enumerate(mels): if i >= len(frames): raise ValueError('Equal or less lengths only')
frame_to_save = frames[i].copy() face, coords, valid_frame = face_det_results[i].copy() if not valid_frame: continue
face = cv2.resize(face, (args.img_size, args.img_size)) img_batch.append(face) mel_batch.append(m) frame_batch.append(frame_to_save) coords_batch.append(coords)
if len(img_batch) >= args.wav2lip_batch_size: img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy() img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255. mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
if len(img_batch) > 0: img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy() img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255. mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch
fps = 25mel_step_size = 16mel_idx_multiplier = 80./fpsdevice = 'cuda' if torch.cuda.is_available() else 'cpu'print('Using {} for inference.'.format(device))
detector = face_detection.FaceAlignment(face_detection.LandmarksType._2D, flip_input=False, device=device)
def _load(checkpoint_path): if device == 'cuda': checkpoint = torch.load(checkpoint_path) else: checkpoint = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) return checkpoint
def load_model(path): model = Wav2Lip() print("Load checkpoint from: {}".format(path)) checkpoint = _load(path) s = checkpoint["state_dict"] new_s = {} for k, v in s.items(): new_s[k.replace('module.', '')] = v model.load_state_dict(new_s)
model = model.to(device) return model.eval()
model = load_model(args.checkpoint_path)
def main(): assert args.data_root is not None data_root = args.data_root
if not os.path.isdir(args.results_dir): os.makedirs(args.results_dir)
with open(args.filelist, 'r') as filelist: lines = filelist.readlines()
for idx, line in enumerate(tqdm(lines)): audio_src, video = line.strip().split()
audio_src = os.path.join(data_root, audio_src) + '.mp4' video = os.path.join(data_root, video) + '.mp4'
command = 'ffmpeg -loglevel panic -y -i {} -strict -2 {}'.format(audio_src, '../temp/temp.wav') subprocess.call(command, shell=True) temp_audio = '../temp/temp.wav'
wav = audio.load_wav(temp_audio, 16000) mel = audio.melspectrogram(wav) if np.isnan(mel.reshape(-1)).sum() > 0: continue
mel_chunks = [] i = 0 while 1: start_idx = int(i * mel_idx_multiplier) if start_idx + mel_step_size > len(mel[0]): break mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size]) i += 1
video_stream = cv2.VideoCapture(video) full_frames = [] while 1: still_reading, frame = video_stream.read() if not still_reading or len(full_frames) > len(mel_chunks): video_stream.release() break full_frames.append(frame)
if len(full_frames) < len(mel_chunks): continue
full_frames = full_frames[:len(mel_chunks)]
try: face_det_results = face_detect(full_frames.copy()) except ValueError as e: continue
batch_size = args.wav2lip_batch_size gen = datagen(full_frames.copy(), face_det_results, mel_chunks)
for i, (img_batch, mel_batch, frames, coords) in enumerate(gen): if i == 0: frame_h, frame_w = full_frames[0].shape[:-1] out = cv2.VideoWriter('../temp/result.avi', cv2.VideoWriter_fourcc(*'DIVX'), fps, (frame_w, frame_h))
img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device) mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
with torch.no_grad(): pred = model(mel_batch, img_batch)
pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255. for pl, f, c in zip(pred, frames, coords): y1, y2, x1, x2 = c pl = cv2.resize(pl.astype(np.uint8), (x2 - x1, y2 - y1)) f[y1:y2, x1:x2] = pl out.write(f)
out.release()
vid = os.path.join(args.results_dir, '{}.mp4'.format(idx))
command = 'ffmpeg -loglevel panic -y -i {} -i {} -strict -2 -q:v 1 {}'.format(temp_audio, '../temp/result.avi', vid) subprocess.call(command, shell=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305from os import listdir, pathimport numpy as npimport scipy, cv2, os, sys, argparseimport dlib, json, subprocessfrom tqdm import tqdmfrom glob import globimport torch
sys.path.append('../')import audioimport face_detectionfrom models import Wav2Lip
parser = argparse.ArgumentParser(description='Code to generate results on ReSyncED evaluation set')
parser.add_argument('--mode', type=str, help='random | dubbed | tts', required=True)
parser.add_argument('--filelist', type=str, help='Filepath of filelist file to read', default=None)
parser.add_argument('--results_dir', type=str, help='Folder to save all results into', required=True)parser.add_argument('--data_root', type=str, required=True)parser.add_argument('--checkpoint_path', type=str, help='Name of saved checkpoint to load weights from', required=True)parser.add_argument('--pads', nargs='+', type=int, default=[0, 10, 0, 0], help='Padding (top, bottom, left, right)')
parser.add_argument('--face_det_batch_size', type=int, help='Single GPU batch size for face detection', default=16)
parser.add_argument('--wav2lip_batch_size', type=int, help='Batch size for Wav2Lip', default=128)parser.add_argument('--face_res', help='Approximate resolution of the face at which to test', default=180)parser.add_argument('--min_frame_res', help='Do not downsample further below this frame resolution', default=480)parser.add_argument('--max_frame_res', help='Downsample to at least this frame resolution', default=720)# parser.add_argument('--resize_factor', default=1, type=int)
args = parser.parse_args()args.img_size = 96
def get_smoothened_boxes(boxes, T): for i in range(len(boxes)): if i + T > len(boxes): window = boxes[len(boxes) - T:] else: window = boxes[i : i + T] boxes[i] = np.mean(window, axis=0) return boxes
def rescale_frames(images): rect = detector.get_detections_for_batch(np.array([images[0]]))[0] if rect is None: raise ValueError('Face not detected!') h, w = images[0].shape[:-1]
x1, y1, x2, y2 = rect
face_size = max(np.abs(y1 - y2), np.abs(x1 - x2))
diff = np.abs(face_size - args.face_res) for factor in range(2, 16): downsampled_res = face_size // factor if min(h//factor, w//factor) < args.min_frame_res: break if np.abs(downsampled_res - args.face_res) >= diff: break
factor -= 1 if factor == 1: return images
return [cv2.resize(im, (im.shape[1]//(factor), im.shape[0]//(factor))) for im in images]
def face_detect(images): batch_size = args.face_det_batch_size images = rescale_frames(images)
while 1: predictions = [] try: for i in range(0, len(images), batch_size): predictions.extend(detector.get_detections_for_batch(np.array(images[i:i + batch_size]))) except RuntimeError: if batch_size == 1: raise RuntimeError('Image too big to run face detection on GPU') batch_size //= 2 print('Recovering from OOM error; New batch size: {}'.format(batch_size)) continue break
results = [] pady1, pady2, padx1, padx2 = args.pads for rect, image in zip(predictions, images): if rect is None: raise ValueError('Face not detected!')
y1 = max(0, rect[1] - pady1) y2 = min(image.shape[0], rect[3] + pady2) x1 = max(0, rect[0] - padx1) x2 = min(image.shape[1], rect[2] + padx2) results.append([x1, y1, x2, y2])
boxes = get_smoothened_boxes(np.array(results), T=5) results = [[image[y1: y2, x1:x2], (y1, y2, x1, x2), True] for image, (x1, y1, x2, y2) in zip(images, boxes)]
return results, images
def datagen(frames, face_det_results, mels): img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
for i, m in enumerate(mels): if i >= len(frames): raise ValueError('Equal or less lengths only')
frame_to_save = frames[i].copy() face, coords, valid_frame = face_det_results[i].copy() if not valid_frame: continue
face = cv2.resize(face, (args.img_size, args.img_size)) img_batch.append(face) mel_batch.append(m) frame_batch.append(frame_to_save) coords_batch.append(coords)
if len(img_batch) >= args.wav2lip_batch_size: img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy() img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255. mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch img_batch, mel_batch, frame_batch, coords_batch = [], [], [], []
if len(img_batch) > 0: img_batch, mel_batch = np.asarray(img_batch), np.asarray(mel_batch)
img_masked = img_batch.copy() img_masked[:, args.img_size//2:] = 0
img_batch = np.concatenate((img_masked, img_batch), axis=3) / 255. mel_batch = np.reshape(mel_batch, [len(mel_batch), mel_batch.shape[1], mel_batch.shape[2], 1])
yield img_batch, mel_batch, frame_batch, coords_batch
def increase_frames(frames, l): ## evenly duplicating frames to increase length of video while len(frames) < l: dup_every = float(l) / len(frames)
final_frames = [] next_duplicate = 0.
for i, f in enumerate(frames): final_frames.append(f)
if int(np.ceil(next_duplicate)) == i: final_frames.append(f)
next_duplicate += dup_every
frames = final_frames
return frames[:l]
mel_step_size = 16device = 'cuda' if torch.cuda.is_available() else 'cpu'print('Using {} for inference.'.format(device))
detector = face_detection.FaceAlignment(face_detection.LandmarksType._2D, flip_input=False, device=device)
def _load(checkpoint_path): if device == 'cuda': checkpoint = torch.load(checkpoint_path) else: checkpoint = torch.load(checkpoint_path, map_location=lambda storage, loc: storage) return checkpoint
def load_model(path): model = Wav2Lip() print("Load checkpoint from: {}".format(path)) checkpoint = _load(path) s = checkpoint["state_dict"] new_s = {} for k, v in s.items(): new_s[k.replace('module.', '')] = v model.load_state_dict(new_s)
model = model.to(device) return model.eval()
model = load_model(args.checkpoint_path)
def main(): if not os.path.isdir(args.results_dir): os.makedirs(args.results_dir)
if args.mode == 'dubbed': files = listdir(args.data_root) lines = ['{} {}'.format(f, f) for f in files]
else: assert args.filelist is not None with open(args.filelist, 'r') as filelist: lines = filelist.readlines()
for idx, line in enumerate(tqdm(lines)): video, audio_src = line.strip().split()
audio_src = os.path.join(args.data_root, audio_src) video = os.path.join(args.data_root, video)
command = 'ffmpeg -loglevel panic -y -i {} -strict -2 {}'.format(audio_src, '../temp/temp.wav') subprocess.call(command, shell=True) temp_audio = '../temp/temp.wav'
wav = audio.load_wav(temp_audio, 16000) mel = audio.melspectrogram(wav)
if np.isnan(mel.reshape(-1)).sum() > 0: raise ValueError('Mel contains nan!')
video_stream = cv2.VideoCapture(video)
fps = video_stream.get(cv2.CAP_PROP_FPS) mel_idx_multiplier = 80./fps
full_frames = [] while 1: still_reading, frame = video_stream.read() if not still_reading: video_stream.release() break
if min(frame.shape[:-1]) > args.max_frame_res: h, w = frame.shape[:-1] scale_factor = min(h, w) / float(args.max_frame_res) h = int(h/scale_factor) w = int(w/scale_factor)
frame = cv2.resize(frame, (w, h)) full_frames.append(frame)
mel_chunks = [] i = 0 while 1: start_idx = int(i * mel_idx_multiplier) if start_idx + mel_step_size > len(mel[0]): break mel_chunks.append(mel[:, start_idx : start_idx + mel_step_size]) i += 1
if len(full_frames) < len(mel_chunks): if args.mode == 'tts': full_frames = increase_frames(full_frames, len(mel_chunks)) else: raise ValueError('#Frames, audio length mismatch')
else: full_frames = full_frames[:len(mel_chunks)]
try: face_det_results, full_frames = face_detect(full_frames.copy()) except ValueError as e: continue
batch_size = args.wav2lip_batch_size gen = datagen(full_frames.copy(), face_det_results, mel_chunks)
for i, (img_batch, mel_batch, frames, coords) in enumerate(gen): if i == 0: frame_h, frame_w = full_frames[0].shape[:-1]
out = cv2.VideoWriter('../temp/result.avi', cv2.VideoWriter_fourcc(*'DIVX'), fps, (frame_w, frame_h))
img_batch = torch.FloatTensor(np.transpose(img_batch, (0, 3, 1, 2))).to(device) mel_batch = torch.FloatTensor(np.transpose(mel_batch, (0, 3, 1, 2))).to(device)
with torch.no_grad(): pred = model(mel_batch, img_batch)
pred = pred.cpu().numpy().transpose(0, 2, 3, 1) * 255. for pl, f, c in zip(pred, frames, coords): y1, y2, x1, x2 = c pl = cv2.resize(pl.astype(np.uint8), (x2 - x1, y2 - y1)) f[y1:y2, x1:x2] = pl out.write(f)
out.release()
vid = os.path.join(args.results_dir, '{}.mp4'.format(idx)) command = 'ffmpeg -loglevel panic -y -i {} -i {} -strict -2 -q:v 1 {}'.format('../temp/temp.wav', '../temp/result.avi', vid) subprocess.call(command, shell=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210#!/usr/bin/python#-*- coding: utf-8 -*-# Video 25 FPS, Audio 16000HZ
import torchimport numpyimport time, pdb, argparse, subprocess, os, math, globimport cv2import python_speech_features
from scipy import signalfrom scipy.io import wavfilefrom SyncNetModel import *from shutil import rmtree
# ==================== Get OFFSET ====================
def calc_pdist(feat1, feat2, vshift=10): win_size = vshift*2+1
feat2p = torch.nn.functional.pad(feat2,(0,0,vshift,vshift))
dists = []
for i in range(0,len(feat1)):
dists.append(torch.nn.functional.pairwise_distance(feat1[[i],:].repeat(win_size, 1), feat2p[i:i+win_size,:]))
return dists
# ==================== MAIN DEF ====================
class SyncNetInstance(torch.nn.Module):
def __init__(self, dropout = 0, num_layers_in_fc_layers = 1024): super(SyncNetInstance, self).__init__();
self.__S__ = S(num_layers_in_fc_layers = num_layers_in_fc_layers).cuda();
def evaluate(self, opt, videofile):
self.__S__.eval();
# ========== ========== # Convert files # ========== ==========
if os.path.exists(os.path.join(opt.tmp_dir,opt.reference)): rmtree(os.path.join(opt.tmp_dir,opt.reference))
os.makedirs(os.path.join(opt.tmp_dir,opt.reference))
command = ("ffmpeg -loglevel error -y -i %s -threads 1 -f image2 %s" % (videofile,os.path.join(opt.tmp_dir,opt.reference,'%06d.jpg'))) output = subprocess.call(command, shell=True, stdout=None)
command = ("ffmpeg -loglevel error -y -i %s -async 1 -ac 1 -vn -acodec pcm_s16le -ar 16000 %s" % (videofile,os.path.join(opt.tmp_dir,opt.reference,'audio.wav'))) output = subprocess.call(command, shell=True, stdout=None) # ========== ========== # Load video # ========== ==========
images = [] flist = glob.glob(os.path.join(opt.tmp_dir,opt.reference,'*.jpg')) flist.sort()
for fname in flist: img_input = cv2.imread(fname) img_input = cv2.resize(img_input, (224,224)) #HARD CODED, CHANGE BEFORE RELEASE images.append(img_input)
im = numpy.stack(images,axis=3) im = numpy.expand_dims(im,axis=0) im = numpy.transpose(im,(0,3,4,1,2))
imtv = torch.autograd.Variable(torch.from_numpy(im.astype(float)).float())
# ========== ========== # Load audio # ========== ==========
sample_rate, audio = wavfile.read(os.path.join(opt.tmp_dir,opt.reference,'audio.wav')) mfcc = zip(*python_speech_features.mfcc(audio,sample_rate)) mfcc = numpy.stack([numpy.array(i) for i in mfcc])
cc = numpy.expand_dims(numpy.expand_dims(mfcc,axis=0),axis=0) cct = torch.autograd.Variable(torch.from_numpy(cc.astype(float)).float())
# ========== ========== # Check audio and video input length # ========== ==========
#if (float(len(audio))/16000) != (float(len(images))/25) : # print("WARNING: Audio (%.4fs) and video (%.4fs) lengths are different."%(float(len(audio))/16000,float(len(images))/25))
min_length = min(len(images),math.floor(len(audio)/640)) # ========== ========== # Generate video and audio feats # ========== ==========
lastframe = min_length-5 im_feat = [] cc_feat = []
tS = time.time() for i in range(0,lastframe,opt.batch_size): im_batch = [ imtv[:,:,vframe:vframe+5,:,:] for vframe in range(i,min(lastframe,i+opt.batch_size)) ] im_in = torch.cat(im_batch,0) im_out = self.__S__.forward_lip(im_in.cuda()); im_feat.append(im_out.data.cpu())
cc_batch = [ cct[:,:,:,vframe*4:vframe*4+20] for vframe in range(i,min(lastframe,i+opt.batch_size)) ] cc_in = torch.cat(cc_batch,0) cc_out = self.__S__.forward_aud(cc_in.cuda()) cc_feat.append(cc_out.data.cpu())
im_feat = torch.cat(im_feat,0) cc_feat = torch.cat(cc_feat,0)
# ========== ========== # Compute offset # ========== ========== #print('Compute time %.3f sec.' % (time.time()-tS))
dists = calc_pdist(im_feat,cc_feat,vshift=opt.vshift) mdist = torch.mean(torch.stack(dists,1),1)
minval, minidx = torch.min(mdist,0)
offset = opt.vshift-minidx conf = torch.median(mdist) - minval
fdist = numpy.stack([dist[minidx].numpy() for dist in dists]) # fdist = numpy.pad(fdist, (3,3), 'constant', constant_values=15) fconf = torch.median(mdist).numpy() - fdist fconfm = signal.medfilt(fconf,kernel_size=9) numpy.set_printoptions(formatter={'float': '{: 0.3f}'.format}) #print('Framewise conf: ') #print(fconfm) #print('AV offset: \t%d \nMin dist: \t%.3f\nConfidence: \t%.3f' % (offset,minval,conf))
dists_npy = numpy.array([ dist.numpy() for dist in dists ]) return offset.numpy(), conf.numpy(), minval.numpy()
def extract_feature(self, opt, videofile):
self.__S__.eval(); # ========== ========== # Load video # ========== ========== cap = cv2.VideoCapture(videofile)
frame_num = 1; images = [] while frame_num: frame_num += 1 ret, image = cap.read() if ret == 0: break
images.append(image)
im = numpy.stack(images,axis=3) im = numpy.expand_dims(im,axis=0) im = numpy.transpose(im,(0,3,4,1,2))
imtv = torch.autograd.Variable(torch.from_numpy(im.astype(float)).float()) # ========== ========== # Generate video feats # ========== ==========
lastframe = len(images)-4 im_feat = []
tS = time.time() for i in range(0,lastframe,opt.batch_size): im_batch = [ imtv[:,:,vframe:vframe+5,:,:] for vframe in range(i,min(lastframe,i+opt.batch_size)) ] im_in = torch.cat(im_batch,0) im_out = self.__S__.forward_lipfeat(im_in.cuda()); im_feat.append(im_out.data.cpu())
im_feat = torch.cat(im_feat,0)
# ========== ========== # Compute offset # ========== ========== print('Compute time %.3f sec.' % (time.time()-tS))
return im_feat
def loadParameters(self, path): loaded_state = torch.load(path, map_location=lambda storage, loc: storage);
self_state = self.__S__.state_dict();
for name, param in loaded_state.items():
self_state[name].copy_(param);1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/usr/bin/python#-*- coding: utf-8 -*-
import time, pdb, argparse, subprocessimport globimport osfrom tqdm import tqdm
from SyncNetInstance_calc_scores import *
# ==================== LOAD PARAMS ====================
parser = argparse.ArgumentParser(description = "SyncNet");
parser.add_argument('--initial_model', type=str, default="data/syncnet_v2.model", help='');parser.add_argument('--batch_size', type=int, default='20', help='');parser.add_argument('--vshift', type=int, default='15', help='');parser.add_argument('--data_root', type=str, required=True, help='');parser.add_argument('--tmp_dir', type=str, default="data/work/pytmp", help='');parser.add_argument('--reference', type=str, default="demo", help='');
opt = parser.parse_args();
# ==================== RUN EVALUATION ====================
s = SyncNetInstance();
s.loadParameters(opt.initial_model);#print("Model %s loaded."%opt.initial_model);path = os.path.join(opt.data_root, "*.mp4")
all_videos = glob.glob(path)
prog_bar = tqdm(range(len(all_videos)))avg_confidence = 0.avg_min_distance = 0.
for videofile_idx in prog_bar: videofile = all_videos[videofile_idx] offset, confidence, min_distance = s.evaluate(opt, videofile=videofile) avg_confidence += confidence avg_min_distance += min_distance prog_bar.set_description('Avg Confidence: {}, Avg Minimum Dist: {}'.format(round(avg_confidence / (videofile_idx + 1), 3), round(avg_min_distance / (videofile_idx + 1), 3))) prog_bar.refresh()
print ('Average Confidence: {}'.format(avg_confidence/len(all_videos)))print ('Average Minimum Distance: {}'.format(avg_min_distance/len(all_videos)))
123456789101112131415161718192021222324252627282930313233343536373839404142434445#!/usr/bin/python#-*- coding: utf-8 -*-
import time, pdb, argparse, subprocess, pickle, os, gzip, glob
from SyncNetInstance_calc_scores import *
# ==================== PARSE ARGUMENT ====================
parser = argparse.ArgumentParser(description = "SyncNet");parser.add_argument('--initial_model', type=str, default="data/syncnet_v2.model", help='');parser.add_argument('--batch_size', type=int, default='20', help='');parser.add_argument('--vshift', type=int, default='15', help='');parser.add_argument('--data_dir', type=str, default='data/work', help='');parser.add_argument('--videofile', type=str, default='', help='');parser.add_argument('--reference', type=str, default='', help='');opt = parser.parse_args();
setattr(opt,'avi_dir',os.path.join(opt.data_dir,'pyavi'))setattr(opt,'tmp_dir',os.path.join(opt.data_dir,'pytmp'))setattr(opt,'work_dir',os.path.join(opt.data_dir,'pywork'))setattr(opt,'crop_dir',os.path.join(opt.data_dir,'pycrop'))
# ==================== LOAD MODEL AND FILE LIST ====================
s = SyncNetInstance();
s.loadParameters(opt.initial_model);#print("Model %s loaded."%opt.initial_model);
flist = glob.glob(os.path.join(opt.crop_dir,opt.reference,'0*.avi'))flist.sort()
# ==================== GET OFFSETS ====================
dists = []for idx, fname in enumerate(flist): offset, conf, dist = s.evaluate(opt,videofile=fname) print (str(dist)+" "+str(conf)) # ==================== PRINT RESULTS TO FILE ====================
#with open(os.path.join(opt.work_dir,opt.reference,'activesd.pckl'), 'wb') as fil:# pickle.dump(dists, fil)12345678rm all_scores.txtyourfilenames=`ls $1`
for eachfile in $yourfilenamesdo python run_pipeline.py --videofile $1/$eachfile --reference wav2lip --data_dir tmp_dir python calculate_scores_real_videos.py --videofile $1/$eachfile --reference wav2lip --data_dir tmp_dir >> all_scores.txtdone12345678910111213This folder contains the filelists for the new evaluation framework proposed in the paper.
## Test filelists for LRS2, LRS3, and LRW.
This folder contains three filelists, each containing a list of names of audio-video pairs from the test sets of LRS2, LRS3, and LRW. The LRS2 and LRW filelists are strictly "Copyright BBC" and can only be used for “non-commercial research by applicants who have an agreement with the BBC to access the Lip Reading in the Wild and/or Lip Reading Sentences in the Wild datasets”. Please follow this link for more details: [https://www.bbc.co.uk/rd/projects/lip-reading-datasets](https://www.bbc.co.uk/rd/projects/lip-reading-datasets).
## ReSynCED benchmark
The sub-folder `ReSynCED` contains filelists for our own Real-world lip-Sync Evaluation Dataset (ReSyncED).
#### Instructions on how to use the above two filelists are available in the README of the parent folder. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160sachin.mp4 emma_cropped.mp4sachin.mp4 mourinho.mp4sachin.mp4 elon.mp4sachin.mp4 messi2.mp4sachin.mp4 cr1.mp4sachin.mp4 sachin.mp4sachin.mp4 sg.mp4sachin.mp4 fergi.mp4sachin.mp4 spanish_lec1.mp4sachin.mp4 bush_small.mp4sachin.mp4 macca_cut.mp4sachin.mp4 ca_cropped.mp4sachin.mp4 lecun.mp4sachin.mp4 spanish_lec0.mp4srk.mp4 emma_cropped.mp4srk.mp4 mourinho.mp4srk.mp4 elon.mp4srk.mp4 messi2.mp4srk.mp4 cr1.mp4srk.mp4 srk.mp4srk.mp4 sachin.mp4srk.mp4 sg.mp4srk.mp4 fergi.mp4srk.mp4 spanish_lec1.mp4srk.mp4 bush_small.mp4srk.mp4 macca_cut.mp4srk.mp4 ca_cropped.mp4srk.mp4 guardiola.mp4srk.mp4 lecun.mp4srk.mp4 spanish_lec0.mp4cr1.mp4 emma_cropped.mp4cr1.mp4 elon.mp4cr1.mp4 messi2.mp4cr1.mp4 cr1.mp4cr1.mp4 spanish_lec1.mp4cr1.mp4 bush_small.mp4cr1.mp4 macca_cut.mp4cr1.mp4 ca_cropped.mp4cr1.mp4 lecun.mp4cr1.mp4 spanish_lec0.mp4macca_cut.mp4 emma_cropped.mp4macca_cut.mp4 elon.mp4macca_cut.mp4 messi2.mp4macca_cut.mp4 spanish_lec1.mp4macca_cut.mp4 macca_cut.mp4macca_cut.mp4 ca_cropped.mp4macca_cut.mp4 spanish_lec0.mp4lecun.mp4 emma_cropped.mp4lecun.mp4 elon.mp4lecun.mp4 messi2.mp4lecun.mp4 spanish_lec1.mp4lecun.mp4 macca_cut.mp4lecun.mp4 ca_cropped.mp4lecun.mp4 lecun.mp4lecun.mp4 spanish_lec0.mp4messi2.mp4 emma_cropped.mp4messi2.mp4 elon.mp4messi2.mp4 messi2.mp4messi2.mp4 spanish_lec1.mp4messi2.mp4 macca_cut.mp4messi2.mp4 ca_cropped.mp4messi2.mp4 spanish_lec0.mp4ca_cropped.mp4 emma_cropped.mp4ca_cropped.mp4 elon.mp4ca_cropped.mp4 spanish_lec1.mp4ca_cropped.mp4 ca_cropped.mp4ca_cropped.mp4 spanish_lec0.mp4spanish_lec1.mp4 spanish_lec1.mp4spanish_lec1.mp4 spanish_lec0.mp4elon.mp4 elon.mp4elon.mp4 spanish_lec1.mp4elon.mp4 spanish_lec0.mp4guardiola.mp4 emma_cropped.mp4guardiola.mp4 mourinho.mp4guardiola.mp4 elon.mp4guardiola.mp4 messi2.mp4guardiola.mp4 cr1.mp4guardiola.mp4 sachin.mp4guardiola.mp4 sg.mp4guardiola.mp4 fergi.mp4guardiola.mp4 spanish_lec1.mp4guardiola.mp4 bush_small.mp4guardiola.mp4 macca_cut.mp4guardiola.mp4 ca_cropped.mp4guardiola.mp4 guardiola.mp4guardiola.mp4 lecun.mp4guardiola.mp4 spanish_lec0.mp4fergi.mp4 emma_cropped.mp4fergi.mp4 mourinho.mp4fergi.mp4 elon.mp4fergi.mp4 messi2.mp4fergi.mp4 cr1.mp4fergi.mp4 sachin.mp4fergi.mp4 sg.mp4fergi.mp4 fergi.mp4fergi.mp4 spanish_lec1.mp4fergi.mp4 bush_small.mp4fergi.mp4 macca_cut.mp4fergi.mp4 ca_cropped.mp4fergi.mp4 lecun.mp4fergi.mp4 spanish_lec0.mp4spanish.mp4 emma_cropped.mp4spanish.mp4 spanish.mp4spanish.mp4 mourinho.mp4spanish.mp4 elon.mp4spanish.mp4 messi2.mp4spanish.mp4 cr1.mp4spanish.mp4 srk.mp4spanish.mp4 sachin.mp4spanish.mp4 sg.mp4spanish.mp4 fergi.mp4spanish.mp4 spanish_lec1.mp4spanish.mp4 bush_small.mp4spanish.mp4 macca_cut.mp4spanish.mp4 ca_cropped.mp4spanish.mp4 guardiola.mp4spanish.mp4 lecun.mp4spanish.mp4 spanish_lec0.mp4bush_small.mp4 emma_cropped.mp4bush_small.mp4 elon.mp4bush_small.mp4 messi2.mp4bush_small.mp4 spanish_lec1.mp4bush_small.mp4 bush_small.mp4bush_small.mp4 macca_cut.mp4bush_small.mp4 ca_cropped.mp4bush_small.mp4 lecun.mp4bush_small.mp4 spanish_lec0.mp4emma_cropped.mp4 emma_cropped.mp4emma_cropped.mp4 elon.mp4emma_cropped.mp4 spanish_lec1.mp4emma_cropped.mp4 spanish_lec0.mp4sg.mp4 emma_cropped.mp4sg.mp4 mourinho.mp4sg.mp4 elon.mp4sg.mp4 messi2.mp4sg.mp4 cr1.mp4sg.mp4 sachin.mp4sg.mp4 sg.mp4sg.mp4 fergi.mp4sg.mp4 spanish_lec1.mp4sg.mp4 bush_small.mp4sg.mp4 macca_cut.mp4sg.mp4 ca_cropped.mp4sg.mp4 lecun.mp4sg.mp4 spanish_lec0.mp4spanish_lec0.mp4 spanish_lec0.mp4mourinho.mp4 emma_cropped.mp4mourinho.mp4 mourinho.mp4mourinho.mp4 elon.mp4mourinho.mp4 messi2.mp4mourinho.mp4 cr1.mp4mourinho.mp4 sachin.mp4mourinho.mp4 sg.mp4mourinho.mp4 fergi.mp4mourinho.mp4 spanish_lec1.mp4mourinho.mp4 bush_small.mp4mourinho.mp4 macca_cut.mp4mourinho.mp4 ca_cropped.mp4mourinho.mp4 lecun.mp4mourinho.mp4 spanish_lec0.mp4123456789101112131415161718adam_1.mp4 andreng_optimization.wavagad_2.mp4 agad_2.wavagad_1.mp4 agad_1.wavagad_3.mp4 agad_3.wavrms_prop_1.mp4 rms_prop_tts.wavtf_1.mp4 tf_1.wavtf_2.mp4 tf_2.wavandrew_ng_ai_business.mp4 andrewng_business_tts.wavcovid_autopsy_1.mp4 autopsy_tts.wavnews_1.mp4 news_tts.wavandrew_ng_fund_1.mp4 andrewng_ai_fund.wavcovid_treatments_1.mp4 covid_tts.wavpytorch_v_tf.mp4 pytorch_vs_tf_eng.wavpytorch_1.mp4 pytorch.wavpkb_1.mp4 pkb_1.wavss_1.mp4 ss_1.wavcarlsen_1.mp4 carlsen_eng.wavfrench.mp4 french.wav1The code for Face Detection in this folder has been taken from the wonderful [face_alignment](https://github.com/1adrianb/face-alignment) repository. This has been modified to take batches of faces at a time. 1234567# -*- coding: utf-8 -*-
__author__ = """Adrian Bulat"""__email__ = 'adrian.bulat@nottingham.ac.uk'__version__ = '1.0.1'
from .api import FaceAlignment, LandmarksType, NetworkSize12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879from __future__ import print_functionimport osimport torchfrom torch.utils.model_zoo import load_urlfrom enum import Enumimport numpy as npimport cv2try: import urllib.request as request_fileexcept BaseException: import urllib as request_file
from .models import FAN, ResNetDepthfrom .utils import *
class LandmarksType(Enum): """Enum class defining the type of landmarks to detect.
``_2D`` - the detected points ``(x,y)`` are detected in a 2D space and follow the visible contour of the face ``_2halfD`` - this points represent the projection of the 3D points into 3D ``_3D`` - detect the points ``(x,y,z)``` in a 3D space
""" _2D = 1 _2halfD = 2 _3D = 3
class NetworkSize(Enum): # TINY = 1 # SMALL = 2 # MEDIUM = 3 LARGE = 4
def __new__(cls, value): member = object.__new__(cls) member._value_ = value return member
def __int__(self): return self.value
ROOT = os.path.dirname(os.path.abspath(__file__))
class FaceAlignment: def __init__(self, landmarks_type, network_size=NetworkSize.LARGE, device='cuda', flip_input=False, face_detector='sfd', verbose=False): self.device = device self.flip_input = flip_input self.landmarks_type = landmarks_type self.verbose = verbose
network_size = int(network_size)
if 'cuda' in device: torch.backends.cudnn.benchmark = True
# Get the face detector face_detector_module = __import__('face_detection.detection.' + face_detector, globals(), locals(), [face_detector], 0) self.face_detector = face_detector_module.FaceDetector(device=device, verbose=verbose)
def get_detections_for_batch(self, images): images = images[..., ::-1] detected_faces = self.face_detector.detect_from_batch(images.copy()) results = []
for i, d in enumerate(detected_faces): if len(d) == 0: results.append(None) continue d = d[0] d = np.clip(d, 0, None) x1, y1, x2, y2 = map(int, d[:-1]) results.append((x1, y1, x2, y2))
return results1from .core import FaceDetector123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import loggingimport globfrom tqdm import tqdmimport numpy as npimport torchimport cv2
class FaceDetector(object): """An abstract class representing a face detector.
Any other face detection implementation must subclass it. All subclasses must implement ``detect_from_image``, that return a list of detected bounding boxes. Optionally, for speed considerations detect from path is recommended. """
def __init__(self, device, verbose): self.device = device self.verbose = verbose
if verbose: if 'cpu' in device: logger = logging.getLogger(__name__) logger.warning("Detection running on CPU, this may be potentially slow.")
if 'cpu' not in device and 'cuda' not in device: if verbose: logger.error("Expected values for device are: {cpu, cuda} but got: %s", device) raise ValueError
def detect_from_image(self, tensor_or_path): """Detects faces in a given image.
This function detects the faces present in a provided BGR(usually) image. The input can be either the image itself or the path to it.
Arguments: tensor_or_path {numpy.ndarray, torch.tensor or string} -- the path to an image or the image itself.
Example::
>>> path_to_image = 'data/image_01.jpg' ... detected_faces = detect_from_image(path_to_image) [A list of bounding boxes (x1, y1, x2, y2)] >>> image = cv2.imread(path_to_image) ... detected_faces = detect_from_image(image) [A list of bounding boxes (x1, y1, x2, y2)]
""" raise NotImplementedError
def detect_from_directory(self, path, extensions=['.jpg', '.png'], recursive=False, show_progress_bar=True): """Detects faces from all the images present in a given directory.
Arguments: path {string} -- a string containing a path that points to the folder containing the images
Keyword Arguments: extensions {list} -- list of string containing the extensions to be consider in the following format: ``.extension_name`` (default: {['.jpg', '.png']}) recursive {bool} -- option wherever to scan the folder recursively (default: {False}) show_progress_bar {bool} -- display a progressbar (default: {True})
Example: >>> directory = 'data' ... detected_faces = detect_from_directory(directory) {A dictionary of [lists containing bounding boxes(x1, y1, x2, y2)]}
""" if self.verbose: logger = logging.getLogger(__name__)
if len(extensions) == 0: if self.verbose: logger.error("Expected at list one extension, but none was received.") raise ValueError
if self.verbose: logger.info("Constructing the list of images.") additional_pattern = '/**/*' if recursive else '/*' files = [] for extension in extensions: files.extend(glob.glob(path + additional_pattern + extension, recursive=recursive))
if self.verbose: logger.info("Finished searching for images. %s images found", len(files)) logger.info("Preparing to run the detection.")
predictions = {} for image_path in tqdm(files, disable=not show_progress_bar): if self.verbose: logger.info("Running the face detector on image: %s", image_path) predictions[image_path] = self.detect_from_image(image_path)
if self.verbose: logger.info("The detector was successfully run on all %s images", len(files))
return predictions
@property def reference_scale(self): raise NotImplementedError
@property def reference_x_shift(self): raise NotImplementedError
@property def reference_y_shift(self): raise NotImplementedError
@staticmethod def tensor_or_path_to_ndarray(tensor_or_path, rgb=True): """Convert path (represented as a string) or torch.tensor to a numpy.ndarray
Arguments: tensor_or_path {numpy.ndarray, torch.tensor or string} -- path to the image, or the image itself """ if isinstance(tensor_or_path, str): return cv2.imread(tensor_or_path) if not rgb else cv2.imread(tensor_or_path)[..., ::-1] elif torch.is_tensor(tensor_or_path): # Call cpu in case its coming from cuda return tensor_or_path.cpu().numpy()[..., ::-1].copy() if not rgb else tensor_or_path.cpu().numpy() elif isinstance(tensor_or_path, np.ndarray): return tensor_or_path[..., ::-1].copy() if not rgb else tensor_or_path else: raise TypeError1from .sfd_detector import SFDDetector as FaceDetector123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from __future__ import print_functionimport osimport sysimport cv2import randomimport datetimeimport timeimport mathimport argparseimport numpy as npimport torch
try: from iou import IOUexcept BaseException: # IOU cython speedup 10x def IOU(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2): sa = abs((ax2 - ax1) * (ay2 - ay1)) sb = abs((bx2 - bx1) * (by2 - by1)) x1, y1 = max(ax1, bx1), max(ay1, by1) x2, y2 = min(ax2, bx2), min(ay2, by2) w = x2 - x1 h = y2 - y1 if w < 0 or h < 0: return 0.0 else: return 1.0 * w * h / (sa + sb - w * h)
def bboxlog(x1, y1, x2, y2, axc, ayc, aww, ahh): xc, yc, ww, hh = (x2 + x1) / 2, (y2 + y1) / 2, x2 - x1, y2 - y1 dx, dy = (xc - axc) / aww, (yc - ayc) / ahh dw, dh = math.log(ww / aww), math.log(hh / ahh) return dx, dy, dw, dh
def bboxloginv(dx, dy, dw, dh, axc, ayc, aww, ahh): xc, yc = dx * aww + axc, dy * ahh + ayc ww, hh = math.exp(dw) * aww, math.exp(dh) * ahh x1, x2, y1, y2 = xc - ww / 2, xc + ww / 2, yc - hh / 2, yc + hh / 2 return x1, y1, x2, y2
def nms(dets, thresh): if 0 == len(dets): return [] x1, y1, x2, y2, scores = dets[:, 0], dets[:, 1], dets[:, 2], dets[:, 3], dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1]
keep = [] while order.size > 0: i = order[0] keep.append(i) xx1, yy1 = np.maximum(x1[i], x1[order[1:]]), np.maximum(y1[i], y1[order[1:]]) xx2, yy2 = np.minimum(x2[i], x2[order[1:]]), np.minimum(y2[i], y2[order[1:]])
w, h = np.maximum(0.0, xx2 - xx1 + 1), np.maximum(0.0, yy2 - yy1 + 1) ovr = w * h / (areas[i] + areas[order[1:]] - w * h)
inds = np.where(ovr <= thresh)[0] order = order[inds + 1]
return keep
def encode(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_priors, 4]. priors: (tensor) Prior boxes in center-offset form Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: encoded boxes (tensor), Shape: [num_priors, 4] """
# dist b/t match center and prior's center g_cxcy = (matched[:, :2] + matched[:, 2:]) / 2 - priors[:, :2] # encode variance g_cxcy /= (variances[0] * priors[:, 2:]) # match wh / prior wh g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:] g_wh = torch.log(g_wh) / variances[1] # return target for smooth_l1_loss return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]
def decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """
boxes = torch.cat(( priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:], priors[:, 2:] * torch.exp(loc[:, 2:] * variances[1])), 1) boxes[:, :2] -= boxes[:, 2:] / 2 boxes[:, 2:] += boxes[:, :2] return boxes
def batch_decode(loc, priors, variances): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes Return: decoded bounding box predictions """
boxes = torch.cat(( priors[:, :, :2] + loc[:, :, :2] * variances[0] * priors[:, :, 2:], priors[:, :, 2:] * torch.exp(loc[:, :, 2:] * variances[1])), 2) boxes[:, :, :2] -= boxes[:, :, 2:] / 2 boxes[:, :, 2:] += boxes[:, :, :2] return boxes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import torchimport torch.nn.functional as F
import osimport sysimport cv2import randomimport datetimeimport mathimport argparseimport numpy as np
import scipy.io as sioimport zipfilefrom .net_s3fd import s3fdfrom .bbox import *
def detect(net, img, device): img = img - np.array([104, 117, 123]) img = img.transpose(2, 0, 1) img = img.reshape((1,) + img.shape)
if 'cuda' in device: torch.backends.cudnn.benchmark = True
img = torch.from_numpy(img).float().to(device) BB, CC, HH, WW = img.size() with torch.no_grad(): olist = net(img)
bboxlist = [] for i in range(len(olist) // 2): olist[i * 2] = F.softmax(olist[i * 2], dim=1) olist = [oelem.data.cpu() for oelem in olist] for i in range(len(olist) // 2): ocls, oreg = olist[i * 2], olist[i * 2 + 1] FB, FC, FH, FW = ocls.size() # feature map size stride = 2**(i + 2) # 4,8,16,32,64,128 anchor = stride * 4 poss = zip(*np.where(ocls[:, 1, :, :] > 0.05)) for Iindex, hindex, windex in poss: axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride score = ocls[0, 1, hindex, windex] loc = oreg[0, :, hindex, windex].contiguous().view(1, 4) priors = torch.Tensor([[axc / 1.0, ayc / 1.0, stride * 4 / 1.0, stride * 4 / 1.0]]) variances = [0.1, 0.2] box = decode(loc, priors, variances) x1, y1, x2, y2 = box[0] * 1.0 # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1) bboxlist.append([x1, y1, x2, y2, score]) bboxlist = np.array(bboxlist) if 0 == len(bboxlist): bboxlist = np.zeros((1, 5))
return bboxlist
def batch_detect(net, imgs, device): imgs = imgs - np.array([104, 117, 123]) imgs = imgs.transpose(0, 3, 1, 2)
if 'cuda' in device: torch.backends.cudnn.benchmark = True
imgs = torch.from_numpy(imgs).float().to(device) BB, CC, HH, WW = imgs.size() with torch.no_grad(): olist = net(imgs)
bboxlist = [] for i in range(len(olist) // 2): olist[i * 2] = F.softmax(olist[i * 2], dim=1) olist = [oelem.data.cpu() for oelem in olist] for i in range(len(olist) // 2): ocls, oreg = olist[i * 2], olist[i * 2 + 1] FB, FC, FH, FW = ocls.size() # feature map size stride = 2**(i + 2) # 4,8,16,32,64,128 anchor = stride * 4 poss = zip(*np.where(ocls[:, 1, :, :] > 0.05)) for Iindex, hindex, windex in poss: axc, ayc = stride / 2 + windex * stride, stride / 2 + hindex * stride score = ocls[:, 1, hindex, windex] loc = oreg[:, :, hindex, windex].contiguous().view(BB, 1, 4) priors = torch.Tensor([[axc / 1.0, ayc / 1.0, stride * 4 / 1.0, stride * 4 / 1.0]]).view(1, 1, 4) variances = [0.1, 0.2] box = batch_decode(loc, priors, variances) box = box[:, 0] * 1.0 # cv2.rectangle(imgshow,(int(x1),int(y1)),(int(x2),int(y2)),(0,0,255),1) bboxlist.append(torch.cat([box, score.unsqueeze(1)], 1).cpu().numpy()) bboxlist = np.array(bboxlist) if 0 == len(bboxlist): bboxlist = np.zeros((1, BB, 5))
return bboxlist
def flip_detect(net, img, device): img = cv2.flip(img, 1) b = detect(net, img, device)
bboxlist = np.zeros(b.shape) bboxlist[:, 0] = img.shape[1] - b[:, 2] bboxlist[:, 1] = b[:, 1] bboxlist[:, 2] = img.shape[1] - b[:, 0] bboxlist[:, 3] = b[:, 3] bboxlist[:, 4] = b[:, 4] return bboxlist
def pts_to_bb(pts): min_x, min_y = np.min(pts, axis=0) max_x, max_y = np.max(pts, axis=0) return np.array([min_x, min_y, max_x, max_y])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129import torchimport torch.nn as nnimport torch.nn.functional as F
class L2Norm(nn.Module): def __init__(self, n_channels, scale=1.0): super(L2Norm, self).__init__() self.n_channels = n_channels self.scale = scale self.eps = 1e-10 self.weight = nn.Parameter(torch.Tensor(self.n_channels)) self.weight.data *= 0.0 self.weight.data += self.scale
def forward(self, x): norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() + self.eps x = x / norm * self.weight.view(1, -1, 1, 1) return x
class s3fd(nn.Module): def __init__(self): super(s3fd, self).__init__() self.conv1_1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1) self.conv1_2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.conv2_1 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1) self.conv2_2 = nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1)
self.conv3_1 = nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1) self.conv3_2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.conv3_3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1)
self.conv4_1 = nn.Conv2d(256, 512, kernel_size=3, stride=1, padding=1) self.conv4_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1) self.conv4_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.conv5_1 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1) self.conv5_2 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1) self.conv5_3 = nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1)
self.fc6 = nn.Conv2d(512, 1024, kernel_size=3, stride=1, padding=3) self.fc7 = nn.Conv2d(1024, 1024, kernel_size=1, stride=1, padding=0)
self.conv6_1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0) self.conv6_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)
self.conv7_1 = nn.Conv2d(512, 128, kernel_size=1, stride=1, padding=0) self.conv7_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)
self.conv3_3_norm = L2Norm(256, scale=10) self.conv4_3_norm = L2Norm(512, scale=8) self.conv5_3_norm = L2Norm(512, scale=5)
self.conv3_3_norm_mbox_conf = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1) self.conv3_3_norm_mbox_loc = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1) self.conv4_3_norm_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1) self.conv4_3_norm_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1) self.conv5_3_norm_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1) self.conv5_3_norm_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1)
self.fc7_mbox_conf = nn.Conv2d(1024, 2, kernel_size=3, stride=1, padding=1) self.fc7_mbox_loc = nn.Conv2d(1024, 4, kernel_size=3, stride=1, padding=1) self.conv6_2_mbox_conf = nn.Conv2d(512, 2, kernel_size=3, stride=1, padding=1) self.conv6_2_mbox_loc = nn.Conv2d(512, 4, kernel_size=3, stride=1, padding=1) self.conv7_2_mbox_conf = nn.Conv2d(256, 2, kernel_size=3, stride=1, padding=1) self.conv7_2_mbox_loc = nn.Conv2d(256, 4, kernel_size=3, stride=1, padding=1)
def forward(self, x): h = F.relu(self.conv1_1(x)) h = F.relu(self.conv1_2(h)) h = F.max_pool2d(h, 2, 2)
h = F.relu(self.conv2_1(h)) h = F.relu(self.conv2_2(h)) h = F.max_pool2d(h, 2, 2)
h = F.relu(self.conv3_1(h)) h = F.relu(self.conv3_2(h)) h = F.relu(self.conv3_3(h)) f3_3 = h h = F.max_pool2d(h, 2, 2)
h = F.relu(self.conv4_1(h)) h = F.relu(self.conv4_2(h)) h = F.relu(self.conv4_3(h)) f4_3 = h h = F.max_pool2d(h, 2, 2)
h = F.relu(self.conv5_1(h)) h = F.relu(self.conv5_2(h)) h = F.relu(self.conv5_3(h)) f5_3 = h h = F.max_pool2d(h, 2, 2)
h = F.relu(self.fc6(h)) h = F.relu(self.fc7(h)) ffc7 = h h = F.relu(self.conv6_1(h)) h = F.relu(self.conv6_2(h)) f6_2 = h h = F.relu(self.conv7_1(h)) h = F.relu(self.conv7_2(h)) f7_2 = h
f3_3 = self.conv3_3_norm(f3_3) f4_3 = self.conv4_3_norm(f4_3) f5_3 = self.conv5_3_norm(f5_3)
cls1 = self.conv3_3_norm_mbox_conf(f3_3) reg1 = self.conv3_3_norm_mbox_loc(f3_3) cls2 = self.conv4_3_norm_mbox_conf(f4_3) reg2 = self.conv4_3_norm_mbox_loc(f4_3) cls3 = self.conv5_3_norm_mbox_conf(f5_3) reg3 = self.conv5_3_norm_mbox_loc(f5_3) cls4 = self.fc7_mbox_conf(ffc7) reg4 = self.fc7_mbox_loc(ffc7) cls5 = self.conv6_2_mbox_conf(f6_2) reg5 = self.conv6_2_mbox_loc(f6_2) cls6 = self.conv7_2_mbox_conf(f7_2) reg6 = self.conv7_2_mbox_loc(f7_2)
# max-out background label chunk = torch.chunk(cls1, 4, 1) bmax = torch.max(torch.max(chunk[0], chunk[1]), chunk[2]) cls1 = torch.cat([bmax, chunk[3]], dim=1)
return [cls1, reg1, cls2, reg2, cls3, reg3, cls4, reg4, cls5, reg5, cls6, reg6]123version https://git-lfs.github.com/spec/v1oid sha256:619a31681264d3f7f7fc7a16a42cbbe8b23f31a256f75a366e5a1bcd59b33543size 898432251234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import osimport cv2from torch.utils.model_zoo import load_url
from ..core import FaceDetector
from .net_s3fd import s3fdfrom .bbox import *from .detect import *
models_urls = { 's3fd': 'https://www.adrianbulat.com/downloads/python-fan/s3fd-619a316812.pth',}
class SFDDetector(FaceDetector): def __init__(self, device, path_to_detector=os.path.join(os.path.dirname(os.path.abspath(__file__)), 's3fd.pth'), verbose=False): super(SFDDetector, self).__init__(device, verbose)
# Initialise the face detector if not os.path.isfile(path_to_detector): model_weights = load_url(models_urls['s3fd']) else: model_weights = torch.load(path_to_detector)
self.face_detector = s3fd() self.face_detector.load_state_dict(model_weights) self.face_detector.to(device) self.face_detector.eval()
def detect_from_image(self, tensor_or_path): image = self.tensor_or_path_to_ndarray(tensor_or_path)
bboxlist = detect(self.face_detector, image, device=self.device) keep = nms(bboxlist, 0.3) bboxlist = bboxlist[keep, :] bboxlist = [x for x in bboxlist if x[-1] > 0.5]
return bboxlist
def detect_from_batch(self, images): bboxlists = batch_detect(self.face_detector, images, device=self.device) keeps = [nms(bboxlists[:, i, :], 0.3) for i in range(bboxlists.shape[1])] bboxlists = [bboxlists[keep, i, :] for i, keep in enumerate(keeps)] bboxlists = [[x for x in bboxlist if x[-1] > 0.5] for bboxlist in bboxlists]
return bboxlists
@property def reference_scale(self): return 195
@property def reference_x_shift(self): return 0
@property def reference_y_shift(self): return 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261import torchimport torch.nn as nnimport torch.nn.functional as Fimport math
def conv3x3(in_planes, out_planes, strd=1, padding=1, bias=False): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=strd, padding=padding, bias=bias)
class ConvBlock(nn.Module): def __init__(self, in_planes, out_planes): super(ConvBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = conv3x3(in_planes, int(out_planes / 2)) self.bn2 = nn.BatchNorm2d(int(out_planes / 2)) self.conv2 = conv3x3(int(out_planes / 2), int(out_planes / 4)) self.bn3 = nn.BatchNorm2d(int(out_planes / 4)) self.conv3 = conv3x3(int(out_planes / 4), int(out_planes / 4))
if in_planes != out_planes: self.downsample = nn.Sequential( nn.BatchNorm2d(in_planes), nn.ReLU(True), nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=1, bias=False), ) else: self.downsample = None
def forward(self, x): residual = x
out1 = self.bn1(x) out1 = F.relu(out1, True) out1 = self.conv1(out1)
out2 = self.bn2(out1) out2 = F.relu(out2, True) out2 = self.conv2(out2)
out3 = self.bn3(out2) out3 = F.relu(out3, True) out3 = self.conv3(out3)
out3 = torch.cat((out1, out2, out3), 1)
if self.downsample is not None: residual = self.downsample(residual)
out3 += residual
return out3
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(planes * 4) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride
def forward(self, x): residual = x
out = self.conv1(x) out = self.bn1(out) out = self.relu(out)
out = self.conv2(out) out = self.bn2(out) out = self.relu(out)
out = self.conv3(out) out = self.bn3(out)
if self.downsample is not None: residual = self.downsample(x)
out += residual out = self.relu(out)
return out
class HourGlass(nn.Module): def __init__(self, num_modules, depth, num_features): super(HourGlass, self).__init__() self.num_modules = num_modules self.depth = depth self.features = num_features
self._generate_network(self.depth)
def _generate_network(self, level): self.add_module('b1_' + str(level), ConvBlock(self.features, self.features))
self.add_module('b2_' + str(level), ConvBlock(self.features, self.features))
if level > 1: self._generate_network(level - 1) else: self.add_module('b2_plus_' + str(level), ConvBlock(self.features, self.features))
self.add_module('b3_' + str(level), ConvBlock(self.features, self.features))
def _forward(self, level, inp): # Upper branch up1 = inp up1 = self._modules['b1_' + str(level)](up1)
# Lower branch low1 = F.avg_pool2d(inp, 2, stride=2) low1 = self._modules['b2_' + str(level)](low1)
if level > 1: low2 = self._forward(level - 1, low1) else: low2 = low1 low2 = self._modules['b2_plus_' + str(level)](low2)
low3 = low2 low3 = self._modules['b3_' + str(level)](low3)
up2 = F.interpolate(low3, scale_factor=2, mode='nearest')
return up1 + up2
def forward(self, x): return self._forward(self.depth, x)
class FAN(nn.Module):
def __init__(self, num_modules=1): super(FAN, self).__init__() self.num_modules = num_modules
# Base part self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) self.bn1 = nn.BatchNorm2d(64) self.conv2 = ConvBlock(64, 128) self.conv3 = ConvBlock(128, 128) self.conv4 = ConvBlock(128, 256)
# Stacking part for hg_module in range(self.num_modules): self.add_module('m' + str(hg_module), HourGlass(1, 4, 256)) self.add_module('top_m_' + str(hg_module), ConvBlock(256, 256)) self.add_module('conv_last' + str(hg_module), nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0)) self.add_module('bn_end' + str(hg_module), nn.BatchNorm2d(256)) self.add_module('l' + str(hg_module), nn.Conv2d(256, 68, kernel_size=1, stride=1, padding=0))
if hg_module < self.num_modules - 1: self.add_module( 'bl' + str(hg_module), nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0)) self.add_module('al' + str(hg_module), nn.Conv2d(68, 256, kernel_size=1, stride=1, padding=0))
def forward(self, x): x = F.relu(self.bn1(self.conv1(x)), True) x = F.avg_pool2d(self.conv2(x), 2, stride=2) x = self.conv3(x) x = self.conv4(x)
previous = x
outputs = [] for i in range(self.num_modules): hg = self._modules['m' + str(i)](previous)
ll = hg ll = self._modules['top_m_' + str(i)](ll)
ll = F.relu(self._modules['bn_end' + str(i)] (self._modules['conv_last' + str(i)](ll)), True)
# Predict heatmaps tmp_out = self._modules['l' + str(i)](ll) outputs.append(tmp_out)
if i < self.num_modules - 1: ll = self._modules['bl' + str(i)](ll) tmp_out_ = self._modules['al' + str(i)](tmp_out) previous = previous + ll + tmp_out_
return outputs
class ResNetDepth(nn.Module):
def __init__(self, block=Bottleneck, layers=[3, 8, 36, 3], num_classes=68): self.inplanes = 64 super(ResNetDepth, self).__init__() self.conv1 = nn.Conv2d(3 + 68, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AvgPool2d(7) self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), )
layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x)
x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x)
x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x)
return xWav2Lip-master/.gitignoreDeleted-16
Wav2Lip-master/README.mdDeleted-168
Wav2Lip-master/__pycache__/audio.cpython-310.pycDeleted
Wav2Lip-master/__pycache__/audio.cpython-311.pycDeleted
Wav2Lip-master/__pycache__/audio.cpython-38.pycDeleted
Wav2Lip-master/__pycache__/hparams.cpython-311.pycDeleted
Wav2Lip-master/__pycache__/hparams.cpython-38.pycDeleted
Wav2Lip-master/audio.pyDeleted-136
Wav2Lip-master/checkpoints/README.mdDeleted-1
Wav2Lip-master/color_syncnet_train.pyDeleted-279
Wav2Lip-master/evaluation/README.mdDeleted-63
Wav2Lip-master/evaluation/gen_videos_from_filelist.pyDeleted-238
Wav2Lip-master/evaluation/real_videos_inference.pyDeleted-305
Wav2Lip-master/evaluation/scores_LSE/SyncNetInstance_calc_scores.pyDeleted-210
Wav2Lip-master/evaluation/scores_LSE/calculate_scores_LRS.pyDeleted-53
Wav2Lip-master/evaluation/scores_LSE/calculate_scores_real_videos.pyDeleted-45
Wav2Lip-master/evaluation/scores_LSE/calculate_scores_real_videos.shDeleted-8
Wav2Lip-master/evaluation/test_filelists/README.mdDeleted-13
Wav2Lip-master/evaluation/test_filelists/ReSyncED/random_pairs.txtDeleted-160
Wav2Lip-master/evaluation/test_filelists/ReSyncED/tts_pairs.txtDeleted-18
Wav2Lip-master/evaluation/test_filelists/lrs2.txtDeleted
Wav2Lip-master/evaluation/test_filelists/lrs3.txtDeleted
Wav2Lip-master/evaluation/test_filelists/lrw.txtDeleted
Wav2Lip-master/face_detection/README.mdDeleted-1
Wav2Lip-master/face_detection/__init__.pyDeleted-7
Wav2Lip-master/face_detection/__pycache__/__init__.cpython-311.pycDeleted
Wav2Lip-master/face_detection/__pycache__/__init__.cpython-38.pycDeleted
Wav2Lip-master/face_detection/__pycache__/api.cpython-311.pycDeleted
Wav2Lip-master/face_detection/__pycache__/api.cpython-38.pycDeleted
Wav2Lip-master/face_detection/__pycache__/models.cpython-311.pycDeleted
Wav2Lip-master/face_detection/__pycache__/models.cpython-38.pycDeleted
Wav2Lip-master/face_detection/__pycache__/utils.cpython-311.pycDeleted
Wav2Lip-master/face_detection/__pycache__/utils.cpython-38.pycDeleted
Wav2Lip-master/face_detection/api.pyDeleted-79
Wav2Lip-master/face_detection/detection/__init__.pyDeleted-1
Wav2Lip-master/face_detection/detection/__pycache__/__init__.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/__pycache__/core.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/core.pyDeleted-130
Wav2Lip-master/face_detection/detection/sfd/__init__.pyDeleted-1
Wav2Lip-master/face_detection/detection/sfd/__pycache__/__init__.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/sfd/__pycache__/bbox.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/sfd/__pycache__/detect.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/sfd/__pycache__/net_s3fd.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/sfd/__pycache__/sfd_detector.cpython-38.pycDeleted
Wav2Lip-master/face_detection/detection/sfd/bbox.pyDeleted-129
Wav2Lip-master/face_detection/detection/sfd/detect.pyDeleted-112
Wav2Lip-master/face_detection/detection/sfd/net_s3fd.pyDeleted-129
Wav2Lip-master/face_detection/detection/sfd/s3fd.pthDeleted-3
Wav2Lip-master/face_detection/detection/sfd/sfd_detector.pyDeleted-59
Wav2Lip-master/face_detection/models.pyDeleted-261