mrneuralnet commited on
Commit
e875957
1 Parent(s): 9d56ebf

Initial commit

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ jpg filter=lfs diff=lfs merge=lfs -text
37
+ .jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ env
2
+ */__pycache__/*
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2019 Sheng-Yu Wang, Oliver Wang, Andrew Owens, Richard Zhang, Alexei A. Efros
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,12 +1,82 @@
1
- ---
2
- title: P PD
3
- emoji: 📈
4
- colorFrom: green
5
- colorTo: indigo
6
- sdk: streamlit
7
- sdk_version: 1.25.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## <b>Detecting Photoshopped Faces by Scripting Photoshop</b> <br>[[Project Page]](http://peterwang512.github.io/FALdetector) [[Paper]](https://arxiv.org/abs/1906.05856)
2
+
3
+ [Sheng-Yu Wang<sup>1</sup>](https://peterwang512.github.io/),
4
+ [Oliver Wang<sup>2</sup>](http://www.oliverwang.info/),
5
+ [Andrew Owens<sup>1</sup>](http://andrewowens.com/),
6
+ [Richard Zhang<sup>2</sup>](https://richzhang.github.io/),
7
+ [Alexei A. Efros<sup>1</sup>](https://people.eecs.berkeley.edu/~efros/). <br>
8
+ UC Berkeley<sup>1</sup>, Adobe Research<sup>2</sup>. <br>
9
+ In [ICCV, 2019](https://arxiv.org/abs/1906.05856).
10
+
11
+
12
+ <img src='https://peterwang512.github.io/FALdetector/images/teaser.png' align="center" width=900>
13
+
14
+ <b>9/30/2019 Update</b> The code and model weights have been updated to correspond to the v2 of our paper. Note that the global classifer architecture is changed from resnet-50 to drn-c-26.
15
+
16
+ <b>1/19/2019 Update</b> Dataset for evaluation is released! The link is [here](https://drive.google.com/file/d/1qCnwdbXFTf96g_LP-g_h-0BQcypNDuWB/view).
17
+
18
+ ## (0) Disclaimer
19
+ Welcome! Computer vision algorithms often work well on some images, but fail on others. Ours is like this too. We believe our work is a significant step forward in detecting and undoing facial warping by image editing tools. However, there are still many hard cases, and this is by no means a solved problem.
20
+
21
+ This is partly because our algorithm is trained on faces warped by the Face-aware Liquify tool in Photoshop, and will thus work well for these types of images, but not necessarily for others. We call this the "dataset bias" problem. Please see the paper for more details on this issue.
22
+
23
+ While we trained our models with various data augmentation to be more robust to downstream operations such as resizing, jpeg compression and saturation/brightness changes, there are many other retouches (e.g. airbrushing) that can alter the low-level statistics of the images to make the detection a really hard one.
24
+
25
+ Please enjoy our results and have fun trying out our models!
26
+
27
+
28
+
29
+
30
+ ## (1) Setup
31
+
32
+ ### Install packages
33
+ - Install PyTorch ([pytorch.org](http://pytorch.org))
34
+ - `pip install -r requirements.txt`
35
+
36
+ ### Download model weights
37
+ - Run `bash weights/download_weights.sh`
38
+
39
+
40
+ ## (2) Run our models
41
+
42
+ ### Global classifer
43
+ ```
44
+ python global_classifier.py --input_path examples/modified.jpg --model_path weights/global.pth
45
+ ```
46
+
47
+ ### Local Detector
48
+ ```
49
+ python local_detector.py --input_path examples/modified.jpg --model_path weights/local.pth --dest_folder out/
50
+ ```
51
+
52
+ **Note:** Our models are trained on faces cropped by the dlib CNN face detector. Although in both scripts we included the `--no_crop` option to run the models without face crops, it is used for images with already cropped faces.
53
+
54
+ ## (3) Dataset
55
+ A validation set consisting of 500 original and 500 modified images each from Flickr and OpenImage can be downloaded [here](https://drive.google.com/file/d/1qCnwdbXFTf96g_LP-g_h-0BQcypNDuWB/view). Due to licensing issues, the released validation set is different from the set we evaluate in the paper, and the training set will not be released.
56
+
57
+ In the zip file, original faces are in the `original` folder, and modified faces are in the `modified` folder. For reference, the `reference` folder contains the same faces in the `modified` folder, but those are before modification (original).
58
+
59
+ To evaluate the dataset, run:
60
+ ```
61
+ # Download the dataset
62
+ cd data
63
+ bash download_valset.sh
64
+ cd ..
65
+ # Run evaluation script. Model weights need to be downloaded.
66
+ python eval.py --dataroot data --global_pth weights/global.pth --local_pth weights/local.pth --gpu_id 0
67
+ ```
68
+ The following are the models' performances on the released set:
69
+
70
+ |Accuracy| AP |PSNR Increase|
71
+ |:------:|:---:|:-----------:|
72
+ | 93.9%|98.9%| +2.66|
73
+
74
+
75
+
76
+ ## (A) Acknowledgments
77
+
78
+ This repository borrows partially from the [pytorch-CycleGAN-and-pix2pix](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix), [drn](https://github.com/fyu/drn), and the PyTorch [torchvision models](https://github.com/pytorch/vision/tree/master/torchvision/models) repositories.
79
+
80
+ ## (B) Citation, Contact
81
+
82
+ If you find this useful for your research, please consider citing this [bibtex](https://peterwang512.github.io/FALdetector/cite.txt). Please contact Sheng-Yu Wang \<sheng-yu_wang at berkeley dot edu\> with any comments or feedback.
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ import os, shutil
4
+ import re
5
+ import time
6
+ import uuid
7
+
8
+ import cv2
9
+
10
+ import numpy as np
11
+ import streamlit as st
12
+ from PIL import Image
13
+ # from extract_video import extract_method_single_video
14
+
15
+ import shlex
16
+ import subprocess
17
+ from file_picker import st_file_selector
18
+
19
+ import os
20
+
21
+ from inference import classify_fake, heatmap_analysis
22
+
23
+ DEBUG = True
24
+ SAMPLE_FOLDER = 'examples'
25
+
26
+ def main():
27
+ st.markdown("###")
28
+ uploaded_file = st.file_uploader('Upload a picture', type=['jpg', 'jpeg', 'png'], accept_multiple_files=False)
29
+
30
+ with st.spinner(f'Loading samples...'):
31
+ while not os.path.isdir(SAMPLE_FOLDER):
32
+ time.sleep(1)
33
+ st.markdown("### or")
34
+ selected_file = st_file_selector(st, path=SAMPLE_FOLDER, key = 'selected', label = 'Choose a sample image')
35
+
36
+ if uploaded_file:
37
+ img = Image.open(uploaded_file).convert('RGB')
38
+ st.image(img)
39
+ elif selected_file:
40
+ img = Image.open(os.path.join(SAMPLE_FOLDER, selected_file)).convert('RGB')
41
+ st.image(img)
42
+ else:
43
+ return
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+ with st.spinner(f'Analyzing image...'):
52
+ try:
53
+ modified_probability = classify_fake(img)
54
+
55
+ except Exception as e:
56
+ if DEBUG:
57
+ st.write(e)
58
+ else:
59
+ st.text("Encountered a problem while analyzing image 🚨")
60
+ return
61
+
62
+ if modified_probability > 0.6:
63
+ st.error(' MODIFIED IMAGE! ', icon="🚨")
64
+ else:
65
+ st.success(" REAL IMAGE! ", icon="✅")
66
+
67
+ st.text("modified probability {:.2f}".format(modified_probability))
68
+
69
+
70
+ if modified_probability > 0.6:
71
+ with st.spinner(f'Analyzing heatmap...'):
72
+ try:
73
+ modified, reverse, heatmap = heatmap_analysis(img)
74
+
75
+ except Exception as e:
76
+ if DEBUG:
77
+ st.write(e)
78
+ else:
79
+ st.text("Encountered a problem while analyzing image 🚨")
80
+ return
81
+
82
+ st.write("### Heatmap")
83
+ st.image(heatmap)
84
+
85
+ st.write("### Reversed stretch imgae")
86
+ st.image(reverse)
87
+
88
+
89
+ if __name__ == "__main__":
90
+ st.set_page_config(
91
+ page_title="Nodeflux Photosop Detection", page_icon=":pencil2:"
92
+ )
93
+ st.title("Photosop Detection")
94
+ main()
data/download_valset.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ DOCUMENT_ID="1mzNxCyrUTBF7-lQGPLYT0HuUODvVvtsb"
3
+ FINAL_DOWNLOADED_FILENAME="val.zip"
4
+
5
+ curl -c /tmp/cookies "https://drive.google.com/uc?export=download&id=$DOCUMENT_ID" > /tmp/intermezzo.html
6
+ curl -L -b /tmp/cookies "https://drive.google.com$(cat /tmp/intermezzo.html | grep -Po 'uc-download-link" [^>]* href="\K[^"]*' | sed 's/\&amp;/\&/g')" > $FINAL_DOWNLOADED_FILENAME
7
+ unzip val.zip
8
+ rm val.zip
9
+
eval.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import argparse
3
+ import torch
4
+ import torchvision.transforms as transforms
5
+ import numpy as np
6
+ from PIL import Image
7
+
8
+ from networks.drn_seg import DRNSeg, DRNSub
9
+ from utils.tools import *
10
+ from utils.visualize import *
11
+ from sklearn.metrics import average_precision_score, accuracy_score
12
+
13
+
14
+ def load_global_classifier(model_path, gpu_id):
15
+ if torch.cuda.is_available() and gpu_id != -1:
16
+ device = 'cuda:{}'.format(gpu_id)
17
+ else:
18
+ device = 'cpu'
19
+ model = DRNSub(1)
20
+ state_dict = torch.load(model_path, map_location='cpu')
21
+ model.load_state_dict(state_dict['model'])
22
+ model.to(device)
23
+ model.device = device
24
+ model.eval()
25
+ return model
26
+
27
+
28
+ def load_local_detector(model_path, gpu_id):
29
+ if torch.cuda.is_available():
30
+ device = 'cuda:{}'.format(gpu_id)
31
+ else:
32
+ device = 'cpu'
33
+
34
+ model = DRNSeg(2)
35
+ state_dict = torch.load(model_path, map_location=device)
36
+ model.load_state_dict(state_dict['model'])
37
+ model.to(device)
38
+ model.device = device
39
+ model.eval()
40
+ return model
41
+
42
+
43
+ tf = transforms.Compose([transforms.ToTensor(),
44
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
45
+ std=[0.229, 0.224, 0.225])])
46
+ def load_data(img_path, device):
47
+ face = Image.open(img_path).convert('RGB')
48
+ face = resize_shorter_side(face, 400)[0]
49
+ face_tens = tf(face).to(device)
50
+ return face_tens, face
51
+
52
+
53
+ def classify_fake(model, img_path):
54
+ img = load_data(img_path, model.device)[0].unsqueeze(0)
55
+ # Prediction
56
+ with torch.no_grad():
57
+ prob = model(img)[0].sigmoid().cpu().item()
58
+ return prob
59
+
60
+
61
+ def calc_psnr(img0, img1, mask=None):
62
+ return -10 * np.log10(np.mean((img0 - img1)**2) + 1e-6)
63
+
64
+
65
+ def detect_warp(model, img_path):
66
+ img, modified = load_data(img_path, model.device)
67
+ # Warping field prediction
68
+ with torch.no_grad():
69
+ flow = model(img.unsqueeze(0))[0].cpu().numpy()
70
+ flow = np.transpose(flow, (1, 2, 0))
71
+
72
+ # Undoing the warps
73
+ flow = flow_resize(flow, modified.size)
74
+ modified_np = np.asarray(modified)
75
+ reverse_np = warp(modified_np, flow)
76
+ original = Image.open(img_path.replace('modified', 'reference')).convert('RGB')
77
+ original_np = np.asarray(original.resize(modified.size, Image.BICUBIC))
78
+
79
+ psnr_before = calc_psnr(original_np / 255, modified_np / 255)
80
+ psnr_after = calc_psnr(original_np / 255, reverse_np / 255)
81
+ return psnr_before, psnr_after
82
+
83
+
84
+ if __name__ == '__main__':
85
+ parser = argparse.ArgumentParser()
86
+ parser.add_argument(
87
+ "--dataroot", required=True, help='the root to the dataset')
88
+ parser.add_argument(
89
+ "--global_pth", required=True, help="path to the global model")
90
+ parser.add_argument(
91
+ "--local_pth", required=True, help="path to the local model")
92
+ parser.add_argument(
93
+ "--gpu_id", default='0', help="the id of the gpu to run model on")
94
+ args = parser.parse_args()
95
+
96
+ glb_model = load_global_classifier(args.global_pth, args.gpu_id)
97
+ lcl_model = load_local_detector(args.local_pth, args.gpu_id)
98
+
99
+ pred_prob, gt_prob, psnr_before, psnr_after = [], [], [], []
100
+ for img_path in glob.glob(args.dataroot + '/original/*'):
101
+ pred_prob.append(classify_fake(glb_model, img_path))
102
+ gt_prob.append(0)
103
+
104
+ for img_path in glob.glob(args.dataroot + '/modified/*'):
105
+ pred_prob.append(classify_fake(glb_model, img_path))
106
+ gt_prob.append(1)
107
+ psnrs = detect_warp(lcl_model, img_path)
108
+ psnr_before.append(psnrs[0])
109
+ psnr_after.append(psnrs[1])
110
+
111
+ pred_prob, gt_prob, psnr_before, psnr_after = \
112
+ np.array(pred_prob), np.array(gt_prob), np.array(psnr_before), np.array(psnr_after)
113
+ acc = accuracy_score(gt_prob, pred_prob > 0.5)
114
+ avg_precision = average_precision_score(gt_prob, pred_prob)
115
+ delta_psnr = psnr_after.mean() - psnr_before.mean()
116
+
117
+ print("Accuracy: ", acc)
118
+ print("Average precision: ", avg_precision)
119
+ print("PSNR increase: ", delta_psnr)
file_picker.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FilePicker for streamlit.
2
+ Still doesn't seem to be a good solution for a way to select files to process from the server Streamlit is running on.
3
+ Here's a pretty functional solution.
4
+ Usage:
5
+ ```
6
+ import streamlit as st
7
+ from filepicker import st_file_selector
8
+ tif_file = st_file_selector(st, key = 'tif', label = 'Choose tif file')
9
+ ```
10
+ """
11
+
12
+ import os
13
+ import streamlit as st
14
+
15
+ def update_dir(key):
16
+ choice = st.session_state[key]
17
+ if os.path.isdir(os.path.join(st.session_state[key+'curr_dir'], choice)):
18
+ st.session_state[key+'curr_dir'] = os.path.normpath(os.path.join(st.session_state[key+'curr_dir'], choice))
19
+ files = sorted(os.listdir(st.session_state[key+'curr_dir']))
20
+ if "images" in files:
21
+ files.remove("images")
22
+ st.session_state[key+'files'] = files
23
+
24
+ def st_file_selector(st_placeholder, path='.', label='Select a file/folder', key = 'selected'):
25
+ if key+'curr_dir' not in st.session_state:
26
+ base_path = '.' if path is None or path == '' else path
27
+ base_path = base_path if os.path.isdir(base_path) else os.path.dirname(base_path)
28
+ base_path = '.' if base_path is None or base_path == '' else base_path
29
+
30
+ files = sorted(os.listdir(base_path))
31
+ files.insert(0, 'Choose a file...')
32
+ if "images" in files:
33
+ files.remove("images")
34
+ st.session_state[key+'files'] = files
35
+ st.session_state[key+'curr_dir'] = base_path
36
+ else:
37
+ base_path = st.session_state[key+'curr_dir']
38
+
39
+ selected_file = st_placeholder.selectbox(label=label,
40
+ options=st.session_state[key+'files'],
41
+ key=key,
42
+ on_change = lambda: update_dir(key))
43
+
44
+ if selected_file == "Choose a file...":
45
+ return None
46
+
47
+ return selected_file
global_classifier.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import torch
5
+ from PIL import Image
6
+ import torchvision.transforms as transforms
7
+
8
+ from networks.drn_seg import DRNSub
9
+ from utils.tools import *
10
+ from utils.visualize import *
11
+
12
+
13
+ def load_classifier(model_path, gpu_id):
14
+ if torch.cuda.is_available() and gpu_id != -1:
15
+ device = 'cuda:{}'.format(gpu_id)
16
+ else:
17
+ device = 'cpu'
18
+ model = DRNSub(1)
19
+ state_dict = torch.load(model_path, map_location='cpu')
20
+ model.load_state_dict(state_dict['model'])
21
+ model.to(device)
22
+ model.device = device
23
+ model.eval()
24
+ return model
25
+
26
+
27
+ tf = transforms.Compose([transforms.ToTensor(),
28
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
29
+ std=[0.229, 0.224, 0.225])])
30
+ def classify_fake(model, img_path, no_crop=False,
31
+ model_file='utils/dlib_face_detector/mmod_human_face_detector.dat'):
32
+ # Data preprocessing
33
+ im_w, im_h = Image.open(img_path).size
34
+ if no_crop:
35
+ face = Image.open(img_path).convert('RGB')
36
+ else:
37
+ faces = face_detection(img_path, verbose=False, model_file=model_file)
38
+ if len(faces) == 0:
39
+ print("no face detected by dlib, exiting")
40
+ sys.exit()
41
+ face, box = faces[0]
42
+ face = resize_shorter_side(face, 400)[0]
43
+ face_tens = tf(face).to(model.device)
44
+
45
+ # Prediction
46
+ with torch.no_grad():
47
+ prob = model(face_tens.unsqueeze(0))[0].sigmoid().cpu().item()
48
+ return prob
49
+
50
+
51
+ if __name__ == '__main__':
52
+ parser = argparse.ArgumentParser()
53
+ parser.add_argument(
54
+ "--input_path", required=True, help="the model input")
55
+ parser.add_argument(
56
+ "--model_path", required=True, help="path to the drn model")
57
+ parser.add_argument(
58
+ "--gpu_id", default='0', help="the id of the gpu to run model on")
59
+ parser.add_argument(
60
+ "--no_crop",
61
+ action="store_true",
62
+ help="do not use a face detector, instead run on the full input image")
63
+ args = parser.parse_args()
64
+
65
+ model = load_classifier(args.model_path, args.gpu_id)
66
+ prob = classify_fake(model, args.input_path, args.no_crop)
67
+ print("Probibility being modified by Photoshop FAL: {:.2f}%".format(prob*100))
inference.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import numpy as np
5
+ import torch
6
+ import torchvision.transforms as transforms
7
+ from PIL import Image
8
+
9
+ from networks.drn_seg import DRNSeg, DRNSub
10
+ from utils.tools import *
11
+ from utils.visualize import *
12
+
13
+ def load_classifier(model_path, gpu_id):
14
+ if torch.cuda.is_available() and gpu_id != -1:
15
+ device = 'cuda:{}'.format(gpu_id)
16
+ else:
17
+ device = 'cpu'
18
+ model = DRNSub(1)
19
+ state_dict = torch.load(model_path, map_location='cpu')
20
+ model.load_state_dict(state_dict['model'])
21
+ model.to(device)
22
+ model.device = device
23
+ model.eval()
24
+ return model
25
+
26
+
27
+
28
+ local_model_path = 'weights/local.pth'
29
+ global_model_path = 'weights/global.pth'
30
+ gpu_id = 0
31
+
32
+ # Loading the model
33
+ if torch.cuda.is_available():
34
+ device = 'cuda:{}'.format(gpu_id)
35
+ else:
36
+ device = 'cpu'
37
+
38
+ local_model = DRNSeg(2)
39
+ state_dict = torch.load(local_model_path, map_location=device)
40
+ local_model.load_state_dict(state_dict['model'])
41
+ local_model.to(device)
42
+ local_model.eval()
43
+
44
+ global_model = load_classifier(global_model_path, gpu_id)
45
+
46
+ # prob = classify_fake(model, args.input_path, args.no_crop)
47
+
48
+ # Data preprocessing
49
+ tf = transforms.Compose([
50
+ transforms.ToTensor(),
51
+ transforms.Normalize(
52
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
53
+ ])
54
+
55
+
56
+ def classify_fake(img, no_crop=False, global_model=global_model,
57
+ model_file='utils/dlib_face_detector/mmod_human_face_detector.dat'):
58
+ # Data preprocessing
59
+ im_w, im_h = img.size
60
+ if no_crop:
61
+ face = img
62
+ else:
63
+ faces = face_detection(img, verbose=False, model_file=model_file)
64
+ if len(faces) == 0:
65
+ print("no face detected by dlib, exiting")
66
+ sys.exit()
67
+ face, box = faces[0]
68
+ face = resize_shorter_side(face, 400)[0]
69
+ face_tens = tf(face).to(global_model.device)
70
+
71
+ # Prediction
72
+ with torch.no_grad():
73
+ prob = global_model(face_tens.unsqueeze(0))[0].sigmoid().cpu().item()
74
+ return prob
75
+
76
+
77
+
78
+ def heatmap_analysis(img, no_crop=False):
79
+
80
+ im_w, im_h = img.size
81
+ if no_crop:
82
+ face = imgs
83
+ else:
84
+ faces = face_detection(img, verbose=False)
85
+ if len(faces) == 0:
86
+ print("no face detected by dlib, exiting")
87
+ sys.exit()
88
+ face, box = faces[0]
89
+ face = resize_shorter_side(face, 400)[0]
90
+ face_tens = tf(face).to(device)
91
+
92
+ # Warping field prediction
93
+ with torch.no_grad():
94
+ flow = local_model(face_tens.unsqueeze(0))[0].cpu().numpy()
95
+ flow = np.transpose(flow, (1, 2, 0))
96
+ h, w, _ = flow.shape
97
+
98
+ # Undoing the warps
99
+ modified = face.resize((w, h), Image.BICUBIC)
100
+ modified_np = np.asarray(modified)
101
+ reverse_np = warp(modified_np, flow)
102
+ reverse = Image.fromarray(reverse_np)
103
+
104
+ flow_magn = np.sqrt(flow[:, :, 0]**2 + flow[:, :, 1]**2)
105
+ cv_out = get_heatmap_cv(modified_np, flow_magn, 7)
106
+ heatmap = Image.fromarray(cv_out)
107
+ return modified, reverse, heatmap
108
+
109
+ # Saving the results
110
+ # modified.save(
111
+ # os.path.join(dest_folder, 'cropped_input.jpg'),
112
+ # quality=90)
113
+ # reverse.save(
114
+ # os.path.join(dest_folder, 'warped.jpg'),
115
+ # quality=90)
116
+ # flow_magn = np.sqrt(flow[:, :, 0]**2 + flow[:, :, 1]**2)
117
+ # save_heatmap_cv(
118
+ # modified_np, flow_magn,
119
+ # os.path.join(dest_folder, 'heatmap.jpg'))
local_detector.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import numpy as np
5
+ import torch
6
+ import torchvision.transforms as transforms
7
+ from PIL import Image
8
+
9
+ from networks.drn_seg import DRNSeg
10
+ from utils.tools import *
11
+ from utils.visualize import *
12
+
13
+
14
+ if __name__ == '__main__':
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument(
17
+ "--input_path", required=True, help="the model input")
18
+ parser.add_argument(
19
+ "--dest_folder", required=True, help="folder to store the results")
20
+ parser.add_argument(
21
+ "--model_path", required=True, help="path to the drn model")
22
+ parser.add_argument(
23
+ "--gpu_id", default='0', help="the id of the gpu to run model on")
24
+ parser.add_argument(
25
+ "--no_crop",
26
+ action="store_true",
27
+ help="do not use a face detector, instead run on the full input image")
28
+ args = parser.parse_args()
29
+
30
+ img_path = args.input_path
31
+ dest_folder = args.dest_folder
32
+ model_path = args.model_path
33
+ gpu_id = args.gpu_id
34
+
35
+ # Loading the model
36
+ if torch.cuda.is_available():
37
+ device = 'cuda:{}'.format(gpu_id)
38
+ else:
39
+ device = 'cpu'
40
+
41
+ model = DRNSeg(2)
42
+ state_dict = torch.load(model_path, map_location=device)
43
+ model.load_state_dict(state_dict['model'])
44
+ model.to(device)
45
+ model.eval()
46
+
47
+ # Data preprocessing
48
+ tf = transforms.Compose([
49
+ transforms.ToTensor(),
50
+ transforms.Normalize(
51
+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
52
+ ])
53
+
54
+ im_w, im_h = Image.open(img_path).size
55
+ if args.no_crop:
56
+ face = Image.open(img_path).convert('RGB')
57
+ else:
58
+ faces = face_detection(img_path, verbose=False)
59
+ if len(faces) == 0:
60
+ print("no face detected by dlib, exiting")
61
+ sys.exit()
62
+ face, box = faces[0]
63
+ face = resize_shorter_side(face, 400)[0]
64
+ face_tens = tf(face).to(device)
65
+
66
+ # Warping field prediction
67
+ with torch.no_grad():
68
+ flow = model(face_tens.unsqueeze(0))[0].cpu().numpy()
69
+ flow = np.transpose(flow, (1, 2, 0))
70
+ h, w, _ = flow.shape
71
+
72
+ # Undoing the warps
73
+ modified = face.resize((w, h), Image.BICUBIC)
74
+ modified_np = np.asarray(modified)
75
+ reverse_np = warp(modified_np, flow)
76
+ reverse = Image.fromarray(reverse_np)
77
+
78
+ # Saving the results
79
+ modified.save(
80
+ os.path.join(dest_folder, 'cropped_input.jpg'),
81
+ quality=90)
82
+ reverse.save(
83
+ os.path.join(dest_folder, 'warped.jpg'),
84
+ quality=90)
85
+ flow_magn = np.sqrt(flow[:, :, 0]**2 + flow[:, :, 1]**2)
86
+ save_heatmap_cv(
87
+ modified_np, flow_magn,
88
+ os.path.join(dest_folder, 'heatmap.jpg'))
networks/__init__.py ADDED
File without changes
networks/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (147 Bytes). View file
 
networks/__pycache__/drn.cpython-39.pyc ADDED
Binary file (10.6 kB). View file
 
networks/__pycache__/drn_seg.cpython-39.pyc ADDED
Binary file (3.48 kB). View file
 
networks/drn.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pdb
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import math
6
+ import torch.utils.model_zoo as model_zoo
7
+
8
+ torch.backends.cudnn.benchmark = True
9
+ BatchNorm = nn.BatchNorm2d
10
+
11
+
12
+ # __all__ = ['DRN', 'drn26', 'drn42', 'drn58']
13
+
14
+
15
+ webroot = 'https://tigress-web.princeton.edu/~fy/drn/models/'
16
+
17
+ model_urls = {
18
+ 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
19
+ 'drn-c-26': webroot + 'drn_c_26-ddedf421.pth',
20
+ 'drn-c-42': webroot + 'drn_c_42-9d336e8c.pth',
21
+ 'drn-c-58': webroot + 'drn_c_58-0a53a92c.pth',
22
+ 'drn-d-22': webroot + 'drn_d_22-4bd2f8ea.pth',
23
+ 'drn-d-38': webroot + 'drn_d_38-eebb45f0.pth',
24
+ 'drn-d-54': webroot + 'drn_d_54-0e0534ff.pth',
25
+ 'drn-d-105': webroot + 'drn_d_105-12b40979.pth'
26
+ }
27
+
28
+
29
+ def conv3x3(in_planes, out_planes, stride=1, padding=1, dilation=1):
30
+ return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
31
+ padding=padding, bias=False, dilation=dilation)
32
+
33
+
34
+ class BasicBlock(nn.Module):
35
+ expansion = 1
36
+
37
+ def __init__(self, inplanes, planes, stride=1, downsample=None,
38
+ dilation=(1, 1), residual=True):
39
+ super(BasicBlock, self).__init__()
40
+ self.conv1 = conv3x3(inplanes, planes, stride,
41
+ padding=dilation[0], dilation=dilation[0])
42
+ self.bn1 = BatchNorm(planes)
43
+ self.relu = nn.ReLU(inplace=True)
44
+ self.conv2 = conv3x3(planes, planes,
45
+ padding=dilation[1], dilation=dilation[1])
46
+ self.bn2 = BatchNorm(planes)
47
+ self.downsample = downsample
48
+ self.stride = stride
49
+ self.residual = residual
50
+
51
+ def forward(self, x):
52
+ residual = x
53
+
54
+ out = self.conv1(x)
55
+ out = self.bn1(out)
56
+ out = self.relu(out)
57
+
58
+ out = self.conv2(out)
59
+ out = self.bn2(out)
60
+
61
+ if self.downsample is not None:
62
+ residual = self.downsample(x)
63
+ if self.residual:
64
+ out += residual
65
+ out = self.relu(out)
66
+
67
+ return out
68
+
69
+
70
+ class Bottleneck(nn.Module):
71
+ expansion = 4
72
+
73
+ def __init__(self, inplanes, planes, stride=1, downsample=None,
74
+ dilation=(1, 1), residual=True):
75
+ super(Bottleneck, self).__init__()
76
+ self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
77
+ self.bn1 = BatchNorm(planes)
78
+ self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
79
+ padding=dilation[1], bias=False,
80
+ dilation=dilation[1])
81
+ self.bn2 = BatchNorm(planes)
82
+ self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
83
+ self.bn3 = BatchNorm(planes * 4)
84
+ self.relu = nn.ReLU(inplace=True)
85
+ self.downsample = downsample
86
+ self.stride = stride
87
+
88
+ def forward(self, x):
89
+ residual = x
90
+
91
+ out = self.conv1(x)
92
+ out = self.bn1(out)
93
+ out = self.relu(out)
94
+
95
+ out = self.conv2(out)
96
+ out = self.bn2(out)
97
+ out = self.relu(out)
98
+
99
+ out = self.conv3(out)
100
+ out = self.bn3(out)
101
+
102
+ if self.downsample is not None:
103
+ residual = self.downsample(x)
104
+
105
+ out += residual
106
+ out = self.relu(out)
107
+
108
+ return out
109
+
110
+
111
+ class DRN(nn.Module):
112
+
113
+ def __init__(self, block, layers, num_classes=1000,
114
+ channels=(16, 32, 64, 128, 256, 512, 512, 512),
115
+ out_map=False, out_middle=False, pool_size=28, arch='D'):
116
+ super(DRN, self).__init__()
117
+ self.inplanes = channels[0]
118
+ self.out_map = out_map
119
+ self.out_dim = channels[-1]
120
+ self.out_middle = out_middle
121
+ self.arch = arch
122
+
123
+ if arch == 'C':
124
+ self.conv1 = nn.Conv2d(3, channels[0], kernel_size=7, stride=1,
125
+ padding=3, bias=False)
126
+ self.bn1 = BatchNorm(channels[0])
127
+ self.relu = nn.ReLU(inplace=True)
128
+
129
+ self.layer1 = self._make_layer(
130
+ BasicBlock, channels[0], layers[0], stride=1)
131
+ self.layer2 = self._make_layer(
132
+ BasicBlock, channels[1], layers[1], stride=2)
133
+ elif arch == 'D':
134
+ self.layer0 = nn.Sequential(
135
+ nn.Conv2d(3, channels[0], kernel_size=7, stride=1, padding=3,
136
+ bias=False),
137
+ BatchNorm(channels[0]),
138
+ nn.ReLU(inplace=True)
139
+ )
140
+
141
+ self.layer1 = self._make_conv_layers(
142
+ channels[0], layers[0], stride=1)
143
+ self.layer2 = self._make_conv_layers(
144
+ channels[1], layers[1], stride=2)
145
+
146
+ self.layer3 = self._make_layer(block, channels[2], layers[2], stride=2)
147
+ self.layer4 = self._make_layer(block, channels[3], layers[3], stride=2)
148
+ self.layer5 = self._make_layer(block, channels[4], layers[4],
149
+ dilation=2, new_level=False)
150
+ self.layer6 = None if layers[5] == 0 else \
151
+ self._make_layer(block, channels[5], layers[5], dilation=4,
152
+ new_level=False)
153
+
154
+ if arch == 'C':
155
+ self.layer7 = None if layers[6] == 0 else \
156
+ self._make_layer(BasicBlock, channels[6], layers[6], dilation=2,
157
+ new_level=False, residual=False)
158
+ self.layer8 = None if layers[7] == 0 else \
159
+ self._make_layer(BasicBlock, channels[7], layers[7], dilation=1,
160
+ new_level=False, residual=False)
161
+ elif arch == 'D':
162
+ self.layer7 = None if layers[6] == 0 else \
163
+ self._make_conv_layers(channels[6], layers[6], dilation=2)
164
+ self.layer8 = None if layers[7] == 0 else \
165
+ self._make_conv_layers(channels[7], layers[7], dilation=1)
166
+
167
+ if num_classes > 0:
168
+ self.avgpool = nn.AvgPool2d(pool_size)
169
+ self.fc = nn.Conv2d(self.out_dim, num_classes, kernel_size=1,
170
+ stride=1, padding=0, bias=True)
171
+ for m in self.modules():
172
+ if isinstance(m, nn.Conv2d):
173
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
174
+ m.weight.data.normal_(0, math.sqrt(2. / n))
175
+ elif isinstance(m, BatchNorm):
176
+ m.weight.data.fill_(1)
177
+ m.bias.data.zero_()
178
+
179
+ def _make_layer(self, block, planes, blocks, stride=1, dilation=1,
180
+ new_level=True, residual=True):
181
+ assert dilation == 1 or dilation % 2 == 0
182
+ downsample = None
183
+ if stride != 1 or self.inplanes != planes * block.expansion:
184
+ downsample = nn.Sequential(
185
+ nn.Conv2d(self.inplanes, planes * block.expansion,
186
+ kernel_size=1, stride=stride, bias=False),
187
+ BatchNorm(planes * block.expansion),
188
+ )
189
+
190
+ layers = list()
191
+ layers.append(block(
192
+ self.inplanes, planes, stride, downsample,
193
+ dilation=(1, 1) if dilation == 1 else (
194
+ dilation // 2 if new_level else dilation, dilation),
195
+ residual=residual))
196
+ self.inplanes = planes * block.expansion
197
+ for i in range(1, blocks):
198
+ layers.append(block(self.inplanes, planes, residual=residual,
199
+ dilation=(dilation, dilation)))
200
+
201
+ return nn.Sequential(*layers)
202
+
203
+ def _make_conv_layers(self, channels, convs, stride=1, dilation=1):
204
+ modules = []
205
+ for i in range(convs):
206
+ modules.extend([
207
+ nn.Conv2d(self.inplanes, channels, kernel_size=3,
208
+ stride=stride if i == 0 else 1,
209
+ padding=dilation, bias=False, dilation=dilation),
210
+ BatchNorm(channels),
211
+ nn.ReLU(inplace=True)])
212
+ self.inplanes = channels
213
+ return nn.Sequential(*modules)
214
+
215
+ def forward(self, x):
216
+ y = list()
217
+
218
+ if self.arch == 'C':
219
+ x = self.conv1(x)
220
+ x = self.bn1(x)
221
+ x = self.relu(x)
222
+ elif self.arch == 'D':
223
+ x = self.layer0(x)
224
+
225
+ x = self.layer1(x)
226
+ y.append(x)
227
+ x = self.layer2(x)
228
+ y.append(x)
229
+
230
+ x = self.layer3(x)
231
+ y.append(x)
232
+
233
+ x = self.layer4(x)
234
+ y.append(x)
235
+
236
+ x = self.layer5(x)
237
+ y.append(x)
238
+
239
+ if self.layer6 is not None:
240
+ x = self.layer6(x)
241
+ y.append(x)
242
+
243
+ if self.layer7 is not None:
244
+ x = self.layer7(x)
245
+ y.append(x)
246
+
247
+ if self.layer8 is not None:
248
+ x = self.layer8(x)
249
+ y.append(x)
250
+
251
+ if self.out_map:
252
+ x = self.fc(x)
253
+ else:
254
+ x = self.avgpool(x)
255
+ x = self.fc(x)
256
+ x = x.view(x.size(0), -1)
257
+
258
+ if self.out_middle:
259
+ return x, y
260
+ else:
261
+ return x
262
+
263
+
264
+ class DRN_A(nn.Module):
265
+
266
+ def __init__(self, block, layers, num_classes=1000):
267
+ self.inplanes = 64
268
+ super(DRN_A, self).__init__()
269
+ self.out_dim = 512 * block.expansion
270
+ self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
271
+ bias=False)
272
+ self.bn1 = nn.BatchNorm2d(64)
273
+ self.relu = nn.ReLU(inplace=True)
274
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
275
+ self.layer1 = self._make_layer(block, 64, layers[0])
276
+ self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
277
+ self.layer3 = self._make_layer(block, 256, layers[2], stride=1,
278
+ dilation=2)
279
+ self.layer4 = self._make_layer(block, 512, layers[3], stride=1,
280
+ dilation=4)
281
+ self.avgpool = nn.AvgPool2d(28, stride=1)
282
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
283
+
284
+ for m in self.modules():
285
+ if isinstance(m, nn.Conv2d):
286
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
287
+ m.weight.data.normal_(0, math.sqrt(2. / n))
288
+ elif isinstance(m, BatchNorm):
289
+ m.weight.data.fill_(1)
290
+ m.bias.data.zero_()
291
+
292
+ # for m in self.modules():
293
+ # if isinstance(m, nn.Conv2d):
294
+ # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
295
+ # elif isinstance(m, nn.BatchNorm2d):
296
+ # nn.init.constant_(m.weight, 1)
297
+ # nn.init.constant_(m.bias, 0)
298
+
299
+ def _make_layer(self, block, planes, blocks, stride=1, dilation=1):
300
+ downsample = None
301
+ if stride != 1 or self.inplanes != planes * block.expansion:
302
+ downsample = nn.Sequential(
303
+ nn.Conv2d(self.inplanes, planes * block.expansion,
304
+ kernel_size=1, stride=stride, bias=False),
305
+ nn.BatchNorm2d(planes * block.expansion),
306
+ )
307
+
308
+ layers = []
309
+ layers.append(block(self.inplanes, planes, stride, downsample))
310
+ self.inplanes = planes * block.expansion
311
+ for i in range(1, blocks):
312
+ layers.append(block(self.inplanes, planes,
313
+ dilation=(dilation, dilation)))
314
+
315
+ return nn.Sequential(*layers)
316
+
317
+ def forward(self, x):
318
+ x = self.conv1(x)
319
+ x = self.bn1(x)
320
+ x = self.relu(x)
321
+ x = self.maxpool(x)
322
+
323
+ x = self.layer1(x)
324
+ x = self.layer2(x)
325
+ x = self.layer3(x)
326
+ x = self.layer4(x)
327
+
328
+ x = self.avgpool(x)
329
+ x = x.view(x.size(0), -1)
330
+ x = self.fc(x)
331
+
332
+ return x
333
+
334
+
335
+ def drn_a_50(pretrained=False, **kwargs):
336
+ model = DRN_A(Bottleneck, [3, 4, 6, 3], **kwargs)
337
+ if pretrained:
338
+ model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
339
+ return model
340
+
341
+
342
+ def drn_c_26(pretrained=False, **kwargs):
343
+ model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='C', **kwargs)
344
+ if pretrained:
345
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-c-26']))
346
+ return model
347
+
348
+
349
+ def drn_c_42(pretrained=False, **kwargs):
350
+ model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', **kwargs)
351
+ if pretrained:
352
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-c-42']))
353
+ return model
354
+
355
+
356
+ def drn_c_58(pretrained=False, **kwargs):
357
+ model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='C', **kwargs)
358
+ if pretrained:
359
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-c-58']))
360
+ return model
361
+
362
+
363
+ def drn_d_22(pretrained=False, **kwargs):
364
+ model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 1, 1], arch='D', **kwargs)
365
+ if pretrained:
366
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-22']))
367
+ return model
368
+
369
+
370
+ def drn_d_24(pretrained=False, **kwargs):
371
+ model = DRN(BasicBlock, [1, 1, 2, 2, 2, 2, 2, 2], arch='D', **kwargs)
372
+ if pretrained:
373
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-24']))
374
+ return model
375
+
376
+
377
+ def drn_d_38(pretrained=False, **kwargs):
378
+ model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', **kwargs)
379
+ if pretrained:
380
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-38']))
381
+ return model
382
+
383
+
384
+ def drn_d_40(pretrained=False, **kwargs):
385
+ model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', **kwargs)
386
+ if pretrained:
387
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-40']))
388
+ return model
389
+
390
+
391
+ def drn_d_54(pretrained=False, **kwargs):
392
+ model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 1, 1], arch='D', **kwargs)
393
+ if pretrained:
394
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-54']))
395
+ return model
396
+
397
+
398
+ def drn_d_56(pretrained=False, **kwargs):
399
+ model = DRN(Bottleneck, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', **kwargs)
400
+ if pretrained:
401
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-56']))
402
+ return model
403
+
404
+
405
+ def drn_d_105(pretrained=False, **kwargs):
406
+ model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 1, 1], arch='D', **kwargs)
407
+ if pretrained:
408
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-105']))
409
+ return model
410
+
411
+
412
+ def drn_d_107(pretrained=False, **kwargs):
413
+ model = DRN(Bottleneck, [1, 1, 3, 4, 23, 3, 2, 2], arch='D', **kwargs)
414
+ if pretrained:
415
+ model.load_state_dict(model_zoo.load_url(model_urls['drn-d-107']))
416
+ return model
networks/drn_seg.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from networks.drn import drn_c_26
5
+
6
+
7
+ def fill_up_weights(up):
8
+ w = up.weight.data
9
+ f = math.ceil(w.size(2) / 2)
10
+ c = (2 * f - 1 - f % 2) / (2. * f)
11
+ for i in range(w.size(2)):
12
+ for j in range(w.size(3)):
13
+ w[0, 0, i, j] = \
14
+ (1 - math.fabs(i / f - c)) * (1 - math.fabs(j / f - c))
15
+ for c in range(1, w.size(0)):
16
+ w[c, 0, :, :] = w[0, 0, :, :]
17
+
18
+
19
+ class DRNSeg(nn.Module):
20
+ def __init__(self, classes, pretrained_drn=False,
21
+ pretrained_model=None, use_torch_up=False):
22
+ super(DRNSeg, self).__init__()
23
+
24
+ model = drn_c_26(pretrained=pretrained_drn)
25
+ self.base = nn.Sequential(*list(model.children())[:-2])
26
+ if pretrained_model:
27
+ self.load_pretrained(pretrained_model)
28
+
29
+ self.seg = nn.Conv2d(model.out_dim, classes,
30
+ kernel_size=1, bias=True)
31
+
32
+ m = self.seg
33
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
34
+ m.weight.data.normal_(0, math.sqrt(2. / n))
35
+ m.bias.data.zero_()
36
+ if use_torch_up:
37
+ self.up = nn.UpsamplingBilinear2d(scale_factor=8)
38
+ else:
39
+ up = nn.ConvTranspose2d(classes, classes, 16, stride=8, padding=4,
40
+ output_padding=0, groups=classes,
41
+ bias=False)
42
+ fill_up_weights(up)
43
+ up.weight.requires_grad = False
44
+ self.up = up
45
+
46
+ def forward(self, x):
47
+ x = self.base(x)
48
+ x = self.seg(x)
49
+ y = self.up(x)
50
+ return y
51
+
52
+ def optim_parameters(self, memo=None):
53
+ for param in self.base.parameters():
54
+ yield param
55
+ for param in self.seg.parameters():
56
+ yield param
57
+
58
+ def load_pretrained(self, pretrained_model):
59
+ print("loading the pretrained drn model from %s" % pretrained_model)
60
+ state_dict = torch.load(pretrained_model, map_location='cpu')
61
+ if hasattr(state_dict, '_metadata'):
62
+ del state_dict._metadata
63
+
64
+ # filter out unnecessary keys
65
+ pretrained_dict = state_dict['model']
66
+ pretrained_dict = {k[5:]: v for k, v in pretrained_dict.items() if k.split('.')[0] == 'base'}
67
+
68
+ # load the pretrained state dict
69
+ self.base.load_state_dict(pretrained_dict)
70
+
71
+
72
+ class DRNSub(nn.Module):
73
+ def __init__(self, num_classes, pretrained_model=None, fix_base=False):
74
+ super(DRNSub, self).__init__()
75
+
76
+ drnseg = DRNSeg(2)
77
+ if pretrained_model:
78
+ print("loading the pretrained drn model from %s" % pretrained_model)
79
+ state_dict = torch.load(pretrained_model, map_location='cpu')
80
+ drnseg.load_state_dict(state_dict['model'])
81
+
82
+ self.base = drnseg.base
83
+ if fix_base:
84
+ for param in self.base.parameters():
85
+ param.requires_grad = False
86
+
87
+ self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
88
+ self.fc = nn.Linear(512, num_classes)
89
+
90
+ def forward(self, x):
91
+ x = self.base(x)
92
+ x = self.avgpool(x)
93
+ x = x.view(x.size(0), -1)
94
+ x = self.fc(x)
95
+ return x
out/cropped_input.jpg ADDED
out/heatmap.jpg ADDED
out/warped.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ dlib
3
+ mmcv
4
+ scipy
5
+ numpy
6
+ matplotlib
7
+ opencv_python
8
+ Pillow
9
+ torch>=0.4.0
10
+ torchvision
utils/__init__.py ADDED
File without changes
utils/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (144 Bytes). View file
 
utils/__pycache__/tools.cpython-39.pyc ADDED
Binary file (3.79 kB). View file
 
utils/__pycache__/visualize.cpython-39.pyc ADDED
Binary file (2.01 kB). View file
 
utils/dlib_face_detector/mmod_human_face_detector.dat ADDED
Binary file (730 kB). View file
 
utils/tools.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ from PIL import Image
6
+ from dlib import cnn_face_detection_model_v1 as face_detect_model
7
+
8
+
9
+ def center_crop(im, length):
10
+ w, h = im.size
11
+ left = w//2 - length//2
12
+ right = w//2 + length//2
13
+ top = h//2 - length//2
14
+ bottom = h//2 + length//2
15
+ return im.crop((left, top, right, bottom)), (left, top)
16
+
17
+
18
+ def remove_boundary(img):
19
+ """
20
+ Remove boundary artifacts that FAL causes.
21
+ """
22
+ w, h = img.size
23
+ left = w//80
24
+ top = h//50
25
+ right = w*79//80
26
+ bottom = h*24//25
27
+ return img.crop((left, top, right, bottom))
28
+
29
+
30
+ def resize_shorter_side(img, min_length):
31
+ """
32
+ Resize the shorter side of img to min_length while
33
+ preserving the aspect ratio.
34
+ """
35
+ ow, oh = img.size
36
+ mult = 8
37
+ if ow < oh:
38
+ if ow == min_length and oh % mult == 0:
39
+ return img, (ow, oh)
40
+ w = min_length
41
+ h = int(min_length * oh / ow)
42
+ else:
43
+ if oh == min_length and ow % mult == 0:
44
+ return img, (ow, oh)
45
+ h = min_length
46
+ w = int(min_length * ow / oh)
47
+ return img.resize((w, h), Image.BICUBIC), (w, h)
48
+
49
+
50
+ def flow_resize(flow, sz):
51
+ oh, ow, _ = flow.shape
52
+ w, h = sz
53
+ u_ = cv2.resize(flow[:,:,0], (w, h))
54
+ v_ = cv2.resize(flow[:,:,1], (w, h))
55
+ u_ *= w / float(ow)
56
+ v_ *= h / float(oh)
57
+ return np.dstack((u_,v_))
58
+
59
+
60
+ def warp(im, flow, alpha=1, interp=cv2.INTER_CUBIC):
61
+ height, width, _ = flow.shape
62
+ cart = np.dstack(np.meshgrid(np.arange(width), np.arange(height)))
63
+ pixel_map = (cart + alpha * flow).astype(np.float32)
64
+ warped = cv2.remap(
65
+ im,
66
+ pixel_map[:, :, 0],
67
+ pixel_map[:, :, 1],
68
+ interp,
69
+ borderMode=cv2.BORDER_REPLICATE)
70
+ return warped
71
+
72
+
73
+ cnn_face_detector = None
74
+ def face_detection(
75
+ img,
76
+ verbose=False,
77
+ model_file='utils/dlib_face_detector/mmod_human_face_detector.dat'):
78
+ """
79
+ Detects faces using dlib cnn face detection, and extend the bounding box
80
+ to include the entire face.
81
+ """
82
+ def shrink(img, max_length=2048):
83
+ ow, oh = img.size
84
+ if max_length >= max(ow, oh):
85
+ return img, 1.0
86
+
87
+ if ow > oh:
88
+ mult = max_length / ow
89
+ else:
90
+ mult = max_length / oh
91
+ w = int(ow * mult)
92
+ h = int(oh * mult)
93
+ return img.resize((w, h), Image.BILINEAR), mult
94
+
95
+ global cnn_face_detector
96
+ if cnn_face_detector is None:
97
+ cnn_face_detector = face_detect_model(model_file)
98
+
99
+ w, h = img.size
100
+ img_shrinked, mult = shrink(img)
101
+
102
+ im = np.asarray(img_shrinked)
103
+ if len(im.shape) != 3 or im.shape[2] != 3:
104
+ return []
105
+
106
+ crop_ims = []
107
+ dets = cnn_face_detector(im, 0)
108
+ for k, d in enumerate(dets):
109
+ top = d.rect.top() / mult
110
+ bottom = d.rect.bottom() / mult
111
+ left = d.rect.left() / mult
112
+ right = d.rect.right() / mult
113
+
114
+ wid = right - left
115
+ left = max(0, left - wid // 2.5)
116
+ top = max(0, top - wid // 1.5)
117
+ right = min(w - 1, right + wid // 2.5)
118
+ bottom = min(h - 1, bottom + wid // 2.5)
119
+
120
+ if d.confidence > 1:
121
+ if verbose:
122
+ print("%d-th face detected: (%d, %d, %d, %d)" %
123
+ (k, left, top, right, bottom))
124
+ crop_im = img.crop((left, top, right, bottom))
125
+ crop_ims.append((crop_im, (left, top, right, bottom)))
126
+
127
+ return crop_ims
128
+
129
+
130
+ def mkdirs(paths):
131
+ if isinstance(paths, list) and not isinstance(paths, str):
132
+ for path in paths:
133
+ mkdir(path)
134
+ else:
135
+ mkdir(paths)
136
+
137
+
138
+ def mkdir(path):
139
+ if not os.path.exists(path):
140
+ os.makedirs(path)
utils/visualize.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import numpy as np
5
+ import torchvision
6
+ from PIL import Image
7
+
8
+
9
+ def unnormalize(tens, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
10
+ # assume tensor of shape NxCxHxW
11
+ return tens * torch.Tensor(std)[None, :, None, None] + torch.Tensor(
12
+ mean)[None, :, None, None]
13
+
14
+
15
+ def get_heatmap_cv(img, magn, max_flow_mag):
16
+ min_flow_mag = .5
17
+ cv_magn = np.clip(
18
+ 255 * (magn - min_flow_mag) / (max_flow_mag - min_flow_mag),
19
+ a_min=0,
20
+ a_max=255).astype(np.uint8)
21
+ if img.dtype != np.uint8:
22
+ img = (255 * img).astype(np.uint8)
23
+
24
+ heatmap_img = cv2.applyColorMap(cv_magn, cv2.COLORMAP_JET)
25
+ heatmap_img = heatmap_img[..., ::-1]
26
+
27
+ h, w = magn.shape
28
+ img_alpha = np.ones((h, w), dtype=np.double)[:, :, None]
29
+ heatmap_alpha = np.clip(
30
+ magn / max_flow_mag, a_min=0, a_max=1)[:, :, None]**.7
31
+ heatmap_alpha[heatmap_alpha < .2]**.5
32
+ pm_hm = heatmap_img * heatmap_alpha
33
+ pm_img = img * img_alpha
34
+ cv_out = pm_hm + pm_img * (1 - heatmap_alpha)
35
+ cv_out = np.clip(cv_out, a_min=0, a_max=255).astype(np.uint8)
36
+
37
+ return cv_out
38
+
39
+
40
+ def get_heatmap_batch(img_batch, pred_batch):
41
+ imgrid = torchvision.utils.make_grid(img_batch).cpu()
42
+ magn_batch = torch.norm(pred_batch, p=2, dim=1, keepdim=True)
43
+ magngrid = torchvision.utils.make_grid(magn_batch)
44
+ magngrid = magngrid[0, :, :]
45
+ imgrid = unnormalize(imgrid).squeeze_()
46
+
47
+ cv_magn = magngrid.detach().cpu().numpy()
48
+ cv_img = imgrid.permute(1, 2, 0).detach().cpu().numpy()
49
+ cv_out = get_heatmap_cv(cv_img, cv_magn, max_flow_mag=9)
50
+ out = np.asarray(cv_out).astype(np.double) / 255.0
51
+
52
+ out = torch.from_numpy(out).permute(2, 0, 1)
53
+ return out
54
+
55
+
56
+ def save_heatmap_cv(img, magn, path, max_flow_mag=7):
57
+ cv_out = get_heatmap_cv(img, magn, max_flow_mag)
58
+ out = Image.fromarray(cv_out)
59
+ out.save(path, quality=95)
weights/download_weights.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ wget https://www.dropbox.com/s/rb8zpvrbxbbutxc/global.pth?dl=0 -O ./weights/global.pth
2
+ wget https://www.dropbox.com/s/pby9dhpr6cqziyl/local.pth?dl=0 -O ./weights/local.pth
weights/global.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aeaf8e135c018fb5298c0ed3d2fc47b39dd656708463f86713187ca62bb9586d
3
+ size 82546417
weights/local.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f4413d59e61f6ecb2960263385e3b17e248acd3d1db4575666c0a02d121c7aaa
3
+ size 247495840