├── .gitignore ├── LICENSE ├── README.md ├── assets ├── ICCV2021_VSOD_FSNet_Chinese.pdf ├── framework.jpg ├── motivation.jpg ├── qualitative.png └── quantitative.png ├── eval ├── CalMAE.m ├── Enhancedmeasure.m ├── Fmeasure_calu.m ├── README.md ├── S_object.m ├── S_region.m ├── StructureMeasure.m ├── calculateNumber.m ├── fileID.m ├── main_VSOD.m └── original_WFb.m ├── infer.py ├── lib ├── fsnet.py └── resnets.py ├── snapshot └── FSNet │ └── snapshot.pth ├── train.py └── utils ├── __init__.py ├── dataloader.py └── func.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Build and Release Folders 2 | bin-debug/ 3 | bin-release/ 4 | [Oo]bj/ 5 | [Bb]in/ 6 | 7 | # Other files and folders 8 | .settings/ 9 | .idea/ 10 | 11 | # Executables 12 | *.swf 13 | *.air 14 | *.ipa 15 | *.apk 16 | 17 | # Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties` 18 | # should NOT be excluded as they contain compiler settings and other important 19 | # information for Eclipse / Flash Builder. 20 | *.xml 21 | 22 | /snapshot/FSNet/2021-ICCV-FSNet-20epoch-new.pth 23 | /.idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Full-Duplex Strategy for Video Object Segmentation (ICCV, 2021) 2 | 3 | 4 | 5 | Authors: 6 | [Ge-Peng Ji](https://scholar.google.com/citations?user=oaxKYKUAAAAJ&hl=en), 7 | [Keren Fu](http://www.kerenfu.top/), 8 | [Zhe Wu](https://scholar.google.com/citations?hl=en&user=jT1s8GkAAAAJ), 9 | [Deng-Ping Fan](https://scholar.google.com/citations?hl=en&user=kakwJ5QAAAAJ)*, 10 | [Jianbing Shen](https://scholar.google.com/citations?hl=en&user=_Q3NTToAAAAJ), & 11 | [Ling Shao](https://scholar.google.com/citations?user=z84rLjoAAAAJ&hl=en&oi=ao) 12 | 13 | - This repository provides code for paper "_**Full-Duplex Strategy for Video Object Segmentation**_" accepted by the ICCV-2021 conference ([official version](https://openaccess.thecvf.com/content/ICCV2021/html/Ji_Full-Duplex_Strategy_for_Video_Object_Segmentation_ICCV_2021_paper.html) / [arXiv Version](https://arxiv.org/abs/2108.03151v2) / [Chinese translation](https://drive.google.com/file/d/1P4v_d_jOjG--FCDkxTY0wDl113evj27W/view?usp=sharing)). 14 | 15 | - This project is under construction. If you have any questions about our paper or bugs in our git project, feel free to contact me. 16 | 17 | - If you like our FSNet for your personal research, please cite this paper ([BibTeX](#4-citation)). 18 | 19 | # 1. News 20 | 21 | - [2022/10/22] Our journal extension has been open-accessed. ([Springer Link](https://link.springer.com/article/10.1007/s41095-021-0262-4)) 22 | - [2021/10/16] Our journal extension is accepted by [Computational Visual Media](https://www.springer.com/journal/41095). The pre-print version could be found at this [link](https://cg.cs.tsinghua.edu.cn/cvmj/papers/CVM0262.pdf). 23 | - [2021/08/24] Upload the training script for video object segmentation. 24 | - [2021/08/22] Upload the pre-trained snapshot and the pre-computed results on U-VOS and V-SOD tasks. 25 | - [2021/08/20] Release inference code, evaluation code (VSOD). 26 | - [2021/07/20] Create Github page. 27 | 28 | # 2. Introduction 29 | 30 | ## Why? 31 | 32 | Appearance and motion are two important sources of information in video object segmentation (VOS). Previous methods mainly focus on using simplex solutions, lowering the upper bound of feature collaboration among and across these two cues. 33 | 34 |

35 |
36 | 37 | Figure 1: Visual comparison between the simplex (i.e., (a) appearance-refined motion and (b) motion-refined appear- ance) and our full-duplex strategy. In contrast, our FS- Net offers a collaborative way to leverage the appearance and motion cues under the mutual restraint of full-duplex strategy, thus providing more accurate structure details and alleviating the short-term feature drifting issue. 38 | 39 |

40 | 41 | ## What? 42 | 43 | In this paper, we study a novel framework, termed the FSNet (Full-duplex Strategy Network), which designs a relational cross-attention module (RCAM) to achieve bidirectional message propagation across embedding subspaces. Furthermore, the bidirectional purification module (BPM) is introduced to update the inconsistent features between the spatial-temporal embeddings, effectively improving the model's robustness. 44 | 45 |

46 |
47 | 48 | Figure 2: The pipeline of our FSNet. The Relational Cross-Attention Module (RCAM) abstracts more discriminative representations between the motion and appearance cues using the full-duplex strategy. Then four Bidirectional Purification Modules (BPM) are stacked to further re-calibrate inconsistencies between the motion and appearance features. Finally, we utilize the decoder to generate our prediction. 49 | 50 |

51 | 52 | ## How? 53 | 54 | By considering the mutual restraint within the full-duplex strategy, our FSNet performs the cross-modal feature-passing (i.e., transmission and receiving) simultaneously before the fusion and decoding stage, making it robust to various challenging scenarios (e.g., motion blur, occlusion) in VOS. Extensive experiments on five popular benchmarks (i.e., DAVIS16, FBMS, MCL, SegTrack-V2, and DAVSOD19) show that our FSNet outperforms other state-of-the-arts for both the VOS and video salient object detection tasks. 55 | 56 |

57 |
58 | 59 | Figure 3: Qualitative results on five datasets, including DAVIS16, MCL, FBMS, SegTrack-V2, and DAVSOD19. 60 | 61 |

62 | 63 | # 3. Usage 64 | 65 | ## How to Inference? 66 | 67 | - Download the test dataset from [Baidu Driver](https://pan.baidu.com/s/1lTYWFXvOnAkmH5EdvHgeyQ) (PSW: aaw8) or [Google Driver](https://drive.google.com/file/d/1ZjJoCy8YVLbDlHZXHTZHx7cdaonePlqp/view?usp=sharing) and save it at `./dataset/*`. 68 | 69 | - Install necessary libraries: `PyTorch 1.1+`, `scipy 1.2.2`, `PIL` 70 | 71 | - Download the pre-trained weights from [Baidu Driver](https://pan.baidu.com/s/1GRUg-n1EEV_nku-2nG3QRw) (psw: 36lm) or [Google Driver](https://drive.google.com/file/d/1rXSG2ruiw1pzUJN-m8BJAfEcjxheYe0D/view?usp=sharing). 72 | Saving the pre-trained weights at `./snapshot/FSNet/2021-ICCV-FSNet-20epoch-new.pth` 73 | 74 | - Just run `python inference.py` to generate the segmentation results. 75 | 76 | - About the post-processing technique DenseCRF we used in the original paper, you can find it here: [DSS-CRF](https://github.com/Andrew-Qibin/dss_crf). 77 | 78 | ## How to train our model from scratch? 79 | 80 | Download the train dataset from [Baidu Driver](https://pan.baidu.com/s/12l1VVZqQsQJL5clty10DbQ) (PSW: u01t) or [Google Driver (VOS-TrainSet_StaticAndVideo.zip)](https://drive.google.com/file/d/1NKjAwqbd6nd1SrlgCB3C1UP5dhouSeIF/view?usp=sharing)/[Google Driver (VOS-TrainSet_Video.zip)](https://drive.google.com/file/d/1aoneB-wbnATRHV8OVcjNd5zBlGOxftQv/view?usp=sharing) and save it at `./dataset/*`. Our training pipeline consists of three steps: 81 | 82 | - First, train the model using the combination of static SOD dataset (i.e., DUTS) with 12,926 samples and U-VOS datasets (i.e., DAVIS16 & FBMS) with 2,373 samples. 83 | - Set `--train_type='pretrain_rgb'` and run `python train.py` in terminal 84 | 85 | - Second, train the model using the optical-flow map of U-VOS datasets (i.e., DAVIS16 & FBMS). 86 | - Set `--train_type='pretrain_flow'` and run `python train.py` in terminal 87 | 88 | - Third, train the model using the pair of frame and optical flow of U-VOS datasets (i.e., DAVIS16 & FBMS). 89 | - Set `--train_type='finetune'` and run `python train.py` in terminal 90 | 91 | # 4. Benchmark 92 | 93 | ## Unsupervised/Zero-shot Video Object Segmentation (U/Z-VOS) task 94 | 95 | > NOTE: In the U-VOS, all the prediction results are strictly binary. We only adopt the naive binarization algorithm 96 | > (i.e., threshold=0.5) in our experiments. 97 | 98 | 99 | - Quantitative results (NOTE: The following results **have slight improvement** compared with the reported results in our conference paper): 100 | 101 | | | mean-J | recall-J | decay-J | mean-F | recall-F | decay-F | T | 102 | |-------|--------|----------|---------|--------|----------|---------|-------| 103 | | FSNet (w/ CRF) | 0.834 | 0.945 | 0.032 | 0.831 | 0.902 | 0.026 | 0.213 | 104 | | FSNet (w/o CRF) | 0.823 | 0.943 | 0.033 | 0.833 | 0.919 | 0.028 | 0.213 | 105 | 106 | - Pre-Computed Results: Please download the prediction results of FSNet, refer to [Baidu Driver](https://pan.baidu.com/s/12fvRu-_Ca9qzYJVnmcucKA) (psw: ojsl) or [Google Driver](https://drive.google.com/file/d/1p3CGVyHuHfrCi6xaNtUdbrFa08H4Uj-b/view?usp=sharing). 107 | 108 | - Evaluation Toolbox: We use the standard evaluation toolbox from [DAVIS16](https://github.com/davisvideochallenge/davis-matlab/tree/davis-2016). 109 | (Note that all the pre-computed segmentations are downloaded from this [link](https://davischallenge.org/davis2016/soa_compare.html)). 110 | 111 | 112 | ## Video Salient Object Detection (V-SOD) task 113 | 114 | > NOTE: In the V-SOD, all the prediction results are non-binary. 115 | 116 | - Pre-Computed Results: Please download the prediction results of FSNet ([Baidu Driver](https://pan.baidu.com/s/1xWvuTIXM6YujhYFaWC9hsQ), PSW: rgk1) or [Google Driver](https://drive.google.com/file/d/1gScv9xmFRN6hX0ZehDMXhwtm6oNobkke/view?usp=sharing). 117 | 118 | - Evaluation Toolbox: We use the standard evaluation toolbox from [DAVSOD benchmark](https://github.com/DengPingFan/DAVSOD). 119 | 120 | # 4. Citation 121 | 122 | @article{ji2022fsnet-CVMJ, 123 | title={Full-Duplex Strategy for Video Object Segmentation}, 124 | author={Ji, Ge-Peng and Fan, Deng-Ping and Fu, Keren and Wu, Zhe and Shen, Jianbing and Shao, Ling}, 125 | journal={Computational Visual Media}, 126 | pages={155–175}, 127 | volume={8}, 128 | issue={1}, 129 | year={2022}, 130 | publisher={Springer} 131 | } 132 | 133 | @inproceedings{ji2021full, 134 | title={Full-Duplex Strategy for Video Object Segmentation}, 135 | author={Ji, Ge-Peng and Fu, Keren and Wu, Zhe and Fan, Deng-Ping and Shen, Jianbing and Shao, Ling}, 136 | booktitle={Proceedings of the IEEE/CVF international conference on computer vision}, 137 | pages={4922--4933}, 138 | year={2021} 139 | } 140 | 141 | # 5. Acknowledgements 142 | 143 | Many thanks to my collaborator [Ph.D. Zhe Wu](https://scholar.google.com/citations?hl=en&user=jT1s8GkAAAAJ), 144 | who provides excellent work [SCRN](https://github.com/wuzhe71/SCRN) and design inspirations. 145 | -------------------------------------------------------------------------------- /assets/ICCV2021_VSOD_FSNet_Chinese.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/assets/ICCV2021_VSOD_FSNet_Chinese.pdf -------------------------------------------------------------------------------- /assets/framework.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/assets/framework.jpg -------------------------------------------------------------------------------- /assets/motivation.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/assets/motivation.jpg -------------------------------------------------------------------------------- /assets/qualitative.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/assets/qualitative.png -------------------------------------------------------------------------------- /assets/quantitative.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/assets/quantitative.png -------------------------------------------------------------------------------- /eval/CalMAE.m: -------------------------------------------------------------------------------- 1 | function mae = CalMAE(smap, gtImg) 2 | % eval Author: Wangjiang Zhu 3 | % Email: wangjiang88119@gmail.com 4 | % Date: 3/24/2014 5 | if size(smap, 1) ~= size(gtImg, 1) || size(smap, 2) ~= size(gtImg, 2) 6 | error('Saliency map and gt Image have different sizes!\n'); 7 | end 8 | 9 | if ~islogical(gtImg) 10 | gtImg = gtImg(:,:,1) > 128; 11 | end 12 | 13 | smap = im2double(smap(:,:,1)); 14 | fgPixels = smap(gtImg); 15 | fgErrSum = length(fgPixels) - sum(fgPixels); 16 | bgErrSum = sum(smap(~gtImg)); 17 | mae = (fgErrSum + bgErrSum) / numel(gtImg); -------------------------------------------------------------------------------- /eval/Enhancedmeasure.m: -------------------------------------------------------------------------------- 1 | function [score]= Emeasure(FM,GT) 2 | % Emeasure Compute the Enhanced Alignment measure (as proposed in "Enhanced-alignment 3 | % Measure for Binary Foreground Map Evaluation" [Deng-Ping Fan et. al - IJCAI'18 oral paper]) 4 | % Usage: 5 | % score = Emeasure(FM,GT) 6 | % Input: 7 | % FM - Binary foreground map. Type: double. 8 | % GT - Binary ground truth. Type: double. 9 | % Output: 10 | % score - The Enhanced alignment score 11 | 12 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Important Note:%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 13 | %The code is for academic purposes only. Please cite this paper if you make use of it: 14 | 15 | %@conference{Fan2018Enhanced, title={Enhanced-alignment Measure for Binary Foreground Map Evaluation}, 16 | % author={Fan, Deng-Ping and Gong, Cheng and Cao, Yang and Ren, Bo and Cheng, Ming-Ming and Borji, Ali}, 17 | % year = {2018}, 18 | % booktitle = {IJCAI} 19 | % } 20 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 21 | 22 | FM = logical(FM); 23 | GT = logical(GT); 24 | 25 | %Use double for computations. 26 | dFM = double(FM); 27 | dGT = double(GT); 28 | 29 | %Special case: 30 | if (sum(dGT(:))==0)% if the GT is completely black 31 | enhanced_matrix = 1.0 - dFM; %only calculate the black area of intersection 32 | elseif(sum(~dGT(:))==0)%if the GT is completely white 33 | enhanced_matrix = dFM; %only calcualte the white area of intersection 34 | else 35 | %Normal case: 36 | 37 | %1.compute alignment matrix 38 | align_matrix = AlignmentTerm(dFM,dGT); 39 | %2.compute enhanced alignment matrix 40 | enhanced_matrix = EnhancedAlignmentTerm(align_matrix); 41 | end 42 | 43 | %3.Emeasure score 44 | [w,h] = size(GT); 45 | score = sum(enhanced_matrix(:))./(w*h - 1 + eps); 46 | end 47 | 48 | % Alignment Term 49 | function [align_Matrix] = AlignmentTerm(dFM,dGT) 50 | 51 | %compute global mean 52 | mu_FM = mean2(dFM); 53 | mu_GT = mean2(dGT); 54 | 55 | %compute the bias matrix 56 | align_FM = dFM - mu_FM; 57 | align_GT = dGT - mu_GT; 58 | 59 | %compute alignment matrix 60 | align_Matrix = 2.*(align_GT.*align_FM)./(align_GT.*align_GT + align_FM.*align_FM + eps); 61 | 62 | end 63 | 64 | % Enhanced Alignment Term function. f(x) = 1/4*(1 + x)^2) 65 | function enhanced = EnhancedAlignmentTerm(align_Matrix) 66 | enhanced = ((align_Matrix + 1).^2)/4; 67 | end 68 | 69 | 70 | -------------------------------------------------------------------------------- /eval/Fmeasure_calu.m: -------------------------------------------------------------------------------- 1 | %% 2 | function [PreFtem, RecallFtem, FmeasureF] = Fmeasure_calu(sMap,gtMap,gtsize, threshold) 3 | %threshold = 2* mean(sMap(:)) ; 4 | if ( threshold > 1 ) 5 | threshold = 1; 6 | end 7 | 8 | Label3 = zeros( gtsize ); 9 | Label3( sMap>=threshold ) = 1; 10 | 11 | NumRec = length( find( Label3==1 ) ); 12 | LabelAnd = Label3 & gtMap; 13 | NumAnd = length( find ( LabelAnd==1 ) ); 14 | num_obj = sum(sum(gtMap)); 15 | 16 | if NumAnd == 0 17 | PreFtem = 0; 18 | RecallFtem = 0; 19 | FmeasureF = 0; 20 | else 21 | PreFtem = NumAnd/NumRec; 22 | RecallFtem = NumAnd/num_obj; 23 | FmeasureF = ( ( 1.3* PreFtem * RecallFtem ) / ( .3 * PreFtem + RecallFtem ) ); 24 | end 25 | 26 | %Fmeasure = [PreFtem, RecallFtem, FmeasureF]; 27 | 28 | -------------------------------------------------------------------------------- /eval/README.md: -------------------------------------------------------------------------------- 1 | # Evaluation Toolboox for VSOD task 2 | 3 | ## Introduction 4 | 5 | - We directly utilize the benchmark tool from [DAVSOD](https://github.com/DengPingFan/DAVSOD/tree/master/EvaluateTool) 6 | - You can evaluate the model performance (S-measure, E-measure, F-measure and MAE) using the one-key matlab 7 | code `main_VSOD.m` in `./FSNet/eval/` directory. 8 | 9 | 10 | ## Related Citations (BibTeX) 11 | 12 | If you find this useful, please cite the related works as follows: SSAV model/DAVSOD dataset 13 | ``` 14 | @InProceedings{Fan_2019_CVPR, 15 | author = {Fan, Deng-Ping and Wang, Wenguan and Cheng, Ming-Ming and Shen, Jianbing}, 16 | title = {Shifting More Attention to Video Salient Object Detection}, 17 | booktitle = {IEEE CVPR}, 18 | year = {2019} 19 | } 20 | ``` 21 | 22 | Metrics 23 | ``` 24 | @inproceedings{Fan2018Enhanced, 25 | author={Fan, Deng-Ping and Gong, Cheng and Cao, Yang and Ren, Bo and Cheng, Ming-Ming and Borji, Ali}, 26 | title={{Enhanced-alignment Measure for Binary Foreground Map Evaluation}}, 27 | booktitle={IJCAI}, 28 | pages={698--704}, 29 | year={2018} 30 | } 31 | 32 | @inproceedings{fan2017structure, 33 | author = {Fan, Deng-Ping and Cheng, Ming-Ming and Liu, Yun and Li, Tao and Borji, Ali}, 34 | title = {{Structure-measure: A New Way to Evaluate Foreground Maps}}, 35 | booktitle = {IEEE ICCV}, 36 | year = {2017}, 37 | pages = {4548-4557} 38 | } 39 | ``` -------------------------------------------------------------------------------- /eval/S_object.m: -------------------------------------------------------------------------------- 1 | function Q = S_object(prediction,GT) 2 | % S_object Computes the object similarity between foreground maps and ground 3 | % truth(as proposed in "Structure-measure:A new way to evaluate foreground 4 | % maps" [Deng-Ping Fan et. al - ICCV 2017]) 5 | % Usage: 6 | % Q = S_object(prediction,GT) 7 | % Input: 8 | % prediction - Binary/Non binary foreground map with values in the range 9 | % [0 1]. Type: double. 10 | % GT - Binary ground truth. Type: logical. 11 | % Output: 12 | % Q - The object similarity score 13 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 14 | 15 | % compute the similarity of the foreground in the object level 16 | prediction_fg = prediction; 17 | prediction_fg(~GT)=0; 18 | O_FG = Object(prediction_fg,GT); 19 | 20 | % compute the similarity of the background 21 | prediction_bg = 1.0 - prediction; 22 | prediction_bg(GT) = 0; 23 | O_BG = Object(prediction_bg,~GT); 24 | 25 | % combine the foreground measure and background measure together 26 | u = mean2(GT); 27 | Q = u * O_FG + (1 - u) * O_BG; 28 | 29 | end 30 | 31 | function score = Object(prediction,GT) 32 | 33 | % check the input 34 | if isempty(prediction) 35 | score = 0; 36 | return; 37 | end 38 | if isinteger(prediction) 39 | prediction = double(prediction); 40 | end 41 | if (~isa( prediction, 'double' )) 42 | error('prediction should be of type: double'); 43 | end 44 | if ((max(prediction(:))>1) || min(prediction(:))<0) 45 | error('prediction should be in the range of [0 1]'); 46 | end 47 | if(~islogical(GT)) 48 | error('GT should be of type: logical'); 49 | end 50 | 51 | % compute the mean of the foreground or background in prediction 52 | x = mean2(prediction(GT)); 53 | 54 | % compute the standard deviations of the foreground or background in prediction 55 | sigma_x = std(prediction(GT)); 56 | 57 | score = 2.0 * x./(x^2 + 1.0 + sigma_x + eps); 58 | end -------------------------------------------------------------------------------- /eval/S_region.m: -------------------------------------------------------------------------------- 1 | function Q = S_region(prediction,GT) 2 | % S_region computes the region similarity between the foreground map and 3 | % ground truth(as proposed in "Structure-measure:A new way to evaluate 4 | % foreground maps" [Deng-Ping Fan et. al - ICCV 2017]) 5 | % Usage: 6 | % Q = S_region(prediction,GT) 7 | % Input: 8 | % prediction - Binary/Non binary foreground map with values in the range 9 | % [0 1]. Type: double. 10 | % GT - Binary ground truth. Type: logical. 11 | % Output: 12 | % Q - The region similarity score 13 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 14 | 15 | % find the centroid of the GT 16 | [X,Y] = centroid(GT); 17 | 18 | % divide GT into 4 regions 19 | [GT_1,GT_2,GT_3,GT_4,w1,w2,w3,w4] = divideGT(GT,X,Y); 20 | 21 | %Divede prediction into 4 regions 22 | [prediction_1,prediction_2,prediction_3,prediction_4] = Divideprediction(prediction,X,Y); 23 | 24 | %Compute the ssim score for each regions 25 | Q1 = ssim(prediction_1,GT_1); 26 | Q2 = ssim(prediction_2,GT_2); 27 | Q3 = ssim(prediction_3,GT_3); 28 | Q4 = ssim(prediction_4,GT_4); 29 | 30 | %Sum the 4 scores 31 | Q = w1 * Q1 + w2 * Q2 + w3 * Q3 + w4 * Q4; 32 | 33 | end 34 | 35 | function [X,Y] = centroid(GT) 36 | % Centroid Compute the centroid of the GT 37 | % Usage: 38 | % [X,Y] = Centroid(GT) 39 | % Input: 40 | % GT - Binary ground truth. Type: logical. 41 | % Output: 42 | % [X,Y] - The coordinates of centroid. 43 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 44 | [rows,cols] = size(GT); 45 | 46 | if(sum(GT(:))==0) 47 | X = round(cols/2); 48 | Y = round(rows/2); 49 | else 50 | total=sum(GT(:)); 51 | i=1:cols; 52 | j=(1:rows)'; 53 | X=round(sum(sum(GT,1).*i)/total); 54 | Y=round(sum(sum(GT,2).*j)/total); 55 | 56 | %dGT = double(GT); 57 | %x = ones(rows,1)*(1:cols); 58 | %y = (1:rows)'*ones(1,cols); 59 | %area = sum(dGT(:)); 60 | %X = round(sum(sum(dGT.*x))/area); 61 | %Y = round(sum(sum(dGT.*y))/area); 62 | end 63 | 64 | end 65 | 66 | % divide the GT into 4 regions according to the centroid of the GT and return the weights 67 | function [LT,RT,LB,RB,w1,w2,w3,w4] = divideGT(GT,X,Y) 68 | % LT - left top; 69 | % RT - right top; 70 | % LB - left bottom; 71 | % RB - right bottom; 72 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 73 | 74 | %width and height of the GT 75 | [hei,wid] = size(GT); 76 | area = wid * hei; 77 | 78 | %copy the 4 regions 79 | LT = GT(1:Y,1:X); 80 | RT = GT(1:Y,X+1:wid); 81 | LB = GT(Y+1:hei,1:X); 82 | RB = GT(Y+1:hei,X+1:wid); 83 | 84 | %The different weight (each block proportional to the GT foreground region). 85 | w1 = (X*Y)./area; 86 | w2 = ((wid-X)*Y)./area; 87 | w3 = (X*(hei-Y))./area; 88 | w4 = 1.0 - w1 - w2 - w3; 89 | end 90 | 91 | %Divide the prediction into 4 regions according to the centroid of the GT 92 | function [LT,RT,LB,RB] = Divideprediction(prediction,X,Y) 93 | 94 | %width and height of the prediction 95 | [hei,wid] = size(prediction); 96 | 97 | %copy the 4 regions 98 | LT = prediction(1:Y,1:X); 99 | RT = prediction(1:Y,X+1:wid); 100 | LB = prediction(Y+1:hei,1:X); 101 | RB = prediction(Y+1:hei,X+1:wid); 102 | 103 | end 104 | 105 | function Q = ssim(prediction,GT) 106 | % ssim computes the region similarity between foreground maps and ground 107 | % truth(as proposed in "Structure-measure: A new way to evaluate foreground 108 | % maps" [Deng-Ping Fan et. al - ICCV 2017]) 109 | % Usage: 110 | % Q = ssim(prediction,GT) 111 | % Input: 112 | % prediction - Binary/Non binary foreground map with values in the range 113 | % [0 1]. Type: double. 114 | % GT - Binary ground truth. Type: logical. 115 | % Output: 116 | % Q - The region similarity score 117 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 118 | 119 | dGT = double(GT); 120 | 121 | [hei,wid] = size(prediction); 122 | N = wid*hei; 123 | 124 | %Compute the mean of SM,GT 125 | x = mean2(prediction); 126 | y = mean2(dGT); 127 | 128 | %Compute the variance of SM,GT 129 | sigma_x2 = sum(sum((prediction - x).^2))./(N - 1 + eps);%sigma_x2 = var(prediction(:)) 130 | sigma_y2 = sum(sum((dGT - y).^2))./(N - 1 + eps); %sigma_y2 = var(dGT(:)); 131 | 132 | %Compute the covariance between SM and GT 133 | sigma_xy = sum(sum((prediction - x).*(dGT - y)))./(N - 1 + eps); 134 | 135 | alpha = 4 * x * y * sigma_xy; 136 | beta = (x.^2 + y.^2).*(sigma_x2 + sigma_y2); 137 | 138 | if(alpha ~= 0) 139 | Q = alpha./(beta + eps); 140 | elseif(alpha == 0 && beta == 0) 141 | Q = 1.0; 142 | else 143 | Q = 0; 144 | end 145 | 146 | end 147 | -------------------------------------------------------------------------------- /eval/StructureMeasure.m: -------------------------------------------------------------------------------- 1 | function Q = StructureMeasure(prediction,GT) 2 | % StructureMeasure computes the similarity between the foreground map and 3 | % ground truth(as proposed in "Structure-measure: A new way to evaluate 4 | % foreground maps" [Deng-Ping Fan et. al - ICCV 2017]) 5 | % Usage: 6 | % Q = StructureMeasure(prediction,GT) 7 | % Input: 8 | % prediction - Binary/Non binary foreground map with values in the range 9 | % [0 1]. Type: double. 10 | % GT - Binary ground truth. Type: logical. 11 | % Output: 12 | % Q - The computed similarity score 13 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 14 | 15 | % Check input 16 | if (~isa(prediction,'double')) 17 | error('The prediction should be double type...'); 18 | end 19 | if ((max(prediction(:))>1) || min(prediction(:))<0) 20 | error('The prediction should be in the range of [0 1]...'); 21 | end 22 | if (~islogical(GT)) 23 | error('GT should be logical type...'); 24 | end 25 | 26 | y = mean2(GT); 27 | 28 | if (y==0)% if the GT is completely black 29 | x = mean2(prediction); 30 | Q = 1.0 - x; %only calculate the area of intersection 31 | elseif(y==1)%if the GT is completely white 32 | x = mean2(prediction); 33 | Q = x; %only calcualte the area of intersection 34 | else 35 | alpha = 0.5; 36 | Q = alpha*S_object(prediction,GT)+(1-alpha)*S_region(prediction,GT); 37 | if (Q<0) 38 | Q=0; 39 | end 40 | end 41 | 42 | end 43 | -------------------------------------------------------------------------------- /eval/calculateNumber.m: -------------------------------------------------------------------------------- 1 | function [NUM,file,fileExt] = calculateNumber(imgPath) 2 | imgExt = {'*.bmp', '*.jpg', '*.png'}; 3 | k=1; 4 | d1 = dir([imgPath char(imgExt(k))]); 5 | file = {d1(~[d1.isdir]).name}; 6 | if isempty(file) 7 | k = k + 1; 8 | d1 = dir([imgPath char(imgExt(k))]); 9 | file = {d1(~[d1.isdir]).name}; 10 | if isempty(file) 11 | k = k + 1; 12 | d1 = dir([imgPath char(imgExt(k))]); 13 | file = {d1(~[d1.isdir]).name}; 14 | NUM = length(file); 15 | else 16 | NUM = length(file); 17 | end 18 | else 19 | NUM = length(file); 20 | end 21 | fileExt = char(imgExt(k)); 22 | end -------------------------------------------------------------------------------- /eval/fileID.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GewelsJI/FSNet/0125cbb8af05962c384dcca5a094c9fc119f1b4a/eval/fileID.m -------------------------------------------------------------------------------- /eval/main_VSOD.m: -------------------------------------------------------------------------------- 1 | clear; close; clc; 2 | 3 | %set Dataset Path 4 | salDir = '../result/'; 5 | gtDir = '/media/nercms/NERCMS/YuchengChou/VSOD_TestSet/'; 6 | Results_Save_Path = './EvalTxt/FSNet-c/'; 7 | 8 | Models = {'FSNet-New'}; %'2015-CVPR-SAG', '2014-TCSVT-SPVM', 9 | Datasets = {'DAVIS'};%, 'FBMS', 'SegTrack-V2', 'MCL', 'DAVSOD', 'DAVSOD-Difficult-20', 'DAVSOD-Normal-25'}; %', 'DAVSOD-Difficult-20', 'FBMS', 'SegTrack-V2', 'ViSal','YouTube-Objects', 'DAVSOD', 'DAVSOD-Normal-25' ,'MCL', 'UVSD', 'VOS' 10 | 11 | Thresholds = 1:-1/255:0; 12 | 13 | for m = 1:length(Models) 14 | 15 | modelName = Models{m} 16 | 17 | resVideoPath = [salDir modelName '/']; 18 | 19 | videoFiles = dir(gtDir); 20 | 21 | videoNUM = length(videoFiles)-2; 22 | 23 | [video_Smeasure, video_wFmeasure, video_adpFmeasure, video_adpEmeasure, video_MAE] = deal(zeros(1,videoNUM)); 24 | [video_Fmeasure,video_Emeasure] = deal(zeros(videoNUM,256)); 25 | 26 | for videonum = 1:length(Datasets) 27 | videofolder = Datasets{videonum} 28 | filePath = [Results_Save_Path modelName '/']; 29 | 30 | if ~exist(filePath, 'dir') 31 | mkdir(filePath); 32 | end 33 | 34 | fileID = fopen([filePath modelName '_' videofolder '_result.txt'], 'w'); 35 | 36 | 37 | seqPath = [gtDir '/' videofolder '/']; % modified by Gepeng_Ji 38 | seqFiles = dir(seqPath); 39 | 40 | seqNUM = length(seqFiles)-2; 41 | 42 | [seq_Smeasure, seq_wFmeasure, seq_adpFmeasure, seq_adpEmeasure, seq_MAE] = deal(zeros(1,seqNUM)); 43 | [seq_Fmeasure,seq_Emeasure] = deal(zeros(seqNUM,256)); 44 | 45 | for seqnum = 1: seqNUM 46 | 47 | seqfolder = seqFiles(seqnum+2).name; 48 | 49 | gt_imgPath = [seqPath seqfolder '/GT/']; 50 | [fileNUM, gt_imgFiles, fileExt] = calculateNumber(gt_imgPath); 51 | resPath = [resVideoPath videofolder '/' seqfolder '/']; 52 | 53 | [Smeasure, wFmeasure, adpFmeasure, adpEmeasure, mae] = deal(zeros(1, fileNUM-2)); 54 | [threshold_Fmeasure, threshold_Emeasure] = deal(zeros(fileNUM-2,256)); 55 | 56 | tic; 57 | for i = 2:fileNUM-1 %skip the first and last gt file for some of the optical-flow based method 58 | 59 | name = char(gt_imgFiles{i}); 60 | fprintf('[Processing] Model: %s, Dataset: %s, Seq: %s (%d/%d), Name: %s (%d/%d)\n',modelName, videofolder, seqfolder, seqnum, seqNUM, name, i-1, fileNUM-2); 61 | 62 | %load gt 63 | gt = imread([gt_imgPath name]); 64 | if numel(size(gt))>2 65 | gt = rgb2gray(gt); 66 | end 67 | if ~islogical(gt) 68 | gt = gt(:,:,1) > 128; 69 | end 70 | 71 | %load salency 72 | sal = imread([resPath name]); 73 | %check size 74 | if size(sal, 1) ~= size(gt, 1) || size(sal, 2) ~= size(gt, 2) 75 | sal = imresize(sal,size(gt)); 76 | imwrite(sal,[resPath name]); 77 | fprintf('Error occurs in the path: %s!!!\n', [resPath name]); 78 | end 79 | 80 | sal = im2double(sal(:,:,1)); 81 | 82 | %normalize sal to [0, 1] 83 | sal = reshape(mapminmax(sal(:)',0,1),size(sal)); 84 | 85 | Smeasure(i-1) = StructureMeasure(sal,logical(gt)); 86 | 87 | wFmeasure(i-1) = original_WFb(sal, logical(gt)); 88 | 89 | % Using the 2 times of average of sal map as the threshold. 90 | threshold = 2* mean(sal(:)) ; 91 | [~,~,adpFmeasure(i-1)] = Fmeasure_calu(sal,double(gt),size(gt),threshold); 92 | % Mean Absolute Error 93 | mae(i-1) = mean2(abs(double(logical(gt)) - sal)); 94 | 95 | Bi_sal = zeros(size(sal)); 96 | Bi_sal(sal>threshold) = 1; 97 | adpEmeasure(i) = Enhancedmeasure(Bi_sal, gt); 98 | 99 | for t = 1:length(Thresholds) 100 | threshold = Thresholds(t); 101 | [~, ~, threshold_Fmeasure(i-1,t)] = Fmeasure_calu(sal, double(gt), size(gt), threshold); 102 | Bi_sal = zeros(size(sal)); 103 | Bi_sal(sal>threshold) = 1; 104 | threshold_Emeasure(i-1,t) = Enhancedmeasure(Bi_sal, gt); 105 | end 106 | 107 | end 108 | toc; 109 | 110 | seq_Smeasure(seqnum) = mean2(Smeasure); 111 | 112 | seq_wFmeasure(seqnum)= mean2(wFmeasure); 113 | 114 | seq_adpFmeasure(seqnum) = mean2(adpFmeasure); 115 | seq_Fmeasure(seqnum,:) = mean(threshold_Fmeasure,1); 116 | seq_maxF = max(seq_Fmeasure(seqnum,:)); 117 | seq_meanF = mean(seq_Fmeasure(seqnum,:)); 118 | 119 | seq_adpEmeasure(seqnum) = mean2(adpEmeasure); 120 | seq_Emeasure(seqnum,:) = mean(threshold_Emeasure,1); 121 | seq_meanE = mean(seq_Emeasure(seqnum,:)); 122 | seq_maxE = max(seq_Emeasure(seqnum,:)); 123 | 124 | 125 | seq_MAE(seqnum) = mean2(mae); 126 | 127 | fprintf(fileID,'(%s Dataset, %s Sequence) seq_Smeasure:%.3f;seq_wFmeasure:%.3f;seq_adpFmeasure:%.3f;seq_maxF:%.3f;seq_meanF:%.3f;seq_adpEmeasure:%.3f;seq_maxE:%.3f;seq_meanE:%.3f;seq_MAE:%.3f\n', ... 128 | videofolder,seqfolder,seq_Smeasure(seqnum),seq_wFmeasure(seqnum), seq_adpFmeasure(seqnum),seq_maxF,seq_meanF,seq_adpEmeasure(seqnum),seq_maxE,seq_meanE,seq_MAE(seqnum)); 129 | fprintf('(%s Dataset, %s Sequence) seq_Smeasure:%.3f;seq_wFmeasure:%.3f;seq_adpFmeasure:%.3f;seq_maxF:%.3f;seq_meanF:%.3f;seq_adpEmeasure:%.3f;seq_maxE:%.3f;seq_meanE:%.3f;seq_MAE:%.3f\n', ... 130 | videofolder,seqfolder,seq_Smeasure(seqnum),seq_wFmeasure(seqnum), seq_adpFmeasure(seqnum),seq_maxF,seq_meanF,seq_adpEmeasure(seqnum),seq_maxE,seq_meanE,seq_MAE(seqnum)); 131 | 132 | end 133 | 134 | video_Smeasure(videonum) = mean2(seq_Smeasure); 135 | video_wFmeasure(videonum) = mean2(seq_wFmeasure); 136 | video_adpFmeasure(videonum) = mean2(seq_adpFmeasure); 137 | video_adpEmeasure(videonum) = mean2(seq_adpEmeasure); 138 | 139 | video_Fmeasure(videonum,:) = mean(seq_Fmeasure,1); 140 | maxF = max(video_Fmeasure(videonum,:)); 141 | meanF = mean(video_Fmeasure(videonum,:)); 142 | 143 | video_Emeasure(videonum,:) = mean(seq_Emeasure,1); 144 | maxE = max(video_Emeasure(videonum,:)); 145 | meanE = mean(video_Emeasure(videonum,:)); 146 | 147 | video_MAE(videonum) = mean2(seq_MAE); 148 | % TODO: PR-Curve 149 | % save([resPath]) 150 | fprintf(fileID,'(%s Dataset) seq_Smeasure:%.3f;seq_wFmeasure:%.3f;seq_adpF:%.3f;seq_maxF:%.3f;seq_meanF:%.3f;seq_adpE:%.3f;seq_maxE:%.3f;seq_meanE:%.3f;seq_MAE:%.3f\n',... 151 | videofolder,video_Smeasure(videonum),video_wFmeasure(videonum),video_adpFmeasure(videonum),maxF,meanF,video_adpEmeasure(videonum),maxE,meanE,video_MAE(videonum)); 152 | fprintf('(%s Dataset) seq_Smeasure:%.3f;seq_wFmeasure:%.3f;seq_adpF:%.3f;seq_maxF:%.3f;seq_meanF:%.3f;seq_adpE:%.3f;seq_maxE:%.3f;seq_meanE:%.3f;seq_MAE:%.3f\n',... 153 | videofolder,video_Smeasure(videonum),video_wFmeasure(videonum),video_adpFmeasure(videonum),maxF,meanF,video_adpEmeasure(videonum),maxE,meanE,video_MAE(videonum)); 154 | end 155 | 156 | fclose(fileID); 157 | 158 | end 159 | 160 | -------------------------------------------------------------------------------- /eval/original_WFb.m: -------------------------------------------------------------------------------- 1 | function [Q]= original_WFb(FG,GT) 2 | % WFb Compute the Weighted F-beta measure (as proposed in "How to Evaluate 3 | % Foreground Maps?" [Margolin et. al - CVPR'14]) 4 | % Usage: 5 | % Q = FbW(FG,GT) 6 | % Input: 7 | % FG - Binary/Non binary foreground map with values in the range [0 1]. Type: double. 8 | % GT - Binary ground truth. Type: logical. 9 | % Output: 10 | % Q - The Weighted F-beta score 11 | 12 | %Check input 13 | if (~isa( FG, 'double' )) 14 | error('FG should be of type: double'); 15 | end 16 | if ((max(FG(:))>1) || min(FG(:))<0) 17 | error('FG should be in the range of [0 1]'); 18 | end 19 | if (~islogical(GT)) 20 | error('GT should be of type: logical'); 21 | end 22 | 23 | dGT = double(GT); %Use double for computations. 24 | 25 | if~(max(dGT(:))) 26 | Q = 0; 27 | else 28 | E = abs(FG-dGT); 29 | % [Ef, Et, Er] = deal(abs(FG-GT)); 30 | 31 | [Dst,IDXT] = bwdist(dGT); 32 | %Pixel dependency 33 | K = fspecial('gaussian',7,5); 34 | Et = E; 35 | Et(~GT)=Et(IDXT(~GT)); %To deal correctly with the edges of the foreground region 36 | EA = imfilter(Et,K); 37 | MIN_E_EA = E; 38 | MIN_E_EA(GT & EA 1: 19 | # for the multiple gpus 20 | model = torch.nn.DataParallel(model, device_ids=opt.gpu_id) 21 | model.load_state_dict(pretrain) 22 | else: 23 | # for a single gpu 24 | new_dict = collections.OrderedDict() 25 | for k, v in pretrain.items(): 26 | new_dict[k.replace('module.', '')] = v 27 | model.load_state_dict(new_dict) 28 | 29 | model.eval() 30 | 31 | for dataset in opt.test_dataset: 32 | save_path = opt.test_save + dataset + '/' 33 | os.makedirs(save_path, exist_ok=True) 34 | 35 | test_loader, dataset_size = get_test_loader( 36 | test_root=opt.dataset_path + dataset, batchsize=opt.batchsize, 37 | trainsize=opt.testsize, shuffle=False, num_workers=3, pin_memory=True) 38 | with torch.no_grad(): 39 | img_count = 1 40 | time_total = 0 41 | for step, data_pack in enumerate(test_loader): 42 | images, flows, img_paths = data_pack 43 | bs, _, _, _ = images.size() 44 | 45 | images = images.cuda() 46 | flows = flows.cuda() 47 | 48 | time_start = time.clock() 49 | sals, edge = model(images, flows) 50 | cur_time = (time.clock() - time_start) 51 | 52 | time_total += cur_time 53 | 54 | for index in range(bs): 55 | sal = sals[index, :, :, :].unsqueeze(0) 56 | tmp = img_paths[index].split('/') 57 | os.makedirs(os.path.join(save_path, tmp[-3]), exist_ok=True) 58 | sal_name = tmp[-3] + '/' + tmp[-1].replace('.jpg', '.png') 59 | 60 | gt = Image.open(img_paths[index]) 61 | gt = np.asarray(gt, np.float32) 62 | gt /= (gt.max() + 1e-8) 63 | 64 | sal = F.upsample(sal, size=(gt.shape[0], gt.shape[1]), mode='bilinear', align_corners=True) 65 | sal = sal.sigmoid().data.cpu().numpy().squeeze() 66 | sal = (sal - sal.min()) / (sal.max() - sal.min() + 1e-8) 67 | misc.imsave(save_path + sal_name, sal) 68 | 69 | print('[INFO-Test] Dataset: {}, Image: {} ({}/{}), ' 70 | 'TimeCom: {}'.format(dataset, sal_name, img_count, dataset_size, cur_time / bs)) 71 | img_count += 1 72 | print("\n[INFO-Test-Done] FPS: {}".format(dataset_size / time_total)) 73 | 74 | 75 | if __name__ == "__main__": 76 | parser = argparse.ArgumentParser() 77 | parser.add_argument('--gpu_id', type=list, 78 | default=[0], help='choose the specific device') 79 | parser.add_argument('--testsize', type=int, 80 | default=352, help='the model input') 81 | parser.add_argument('--test_dataset', type=list, help='your test dataset name assigned in the img/gt dictionary', 82 | default=['DAVIS', 'FBMS', 'SegTrack-V2', 'MCL', 'DAVSOD', 'DAVSOD-Difficult-20', 'DAVSOD-Normal-25']) 83 | parser.add_argument('--model_path', type=str, 84 | default='./snapshot/FSNet/2021-ICCV-FSNet-20epoch-new.pth') 85 | parser.add_argument('--test_save', type=str, 86 | default='./result/FSNet-New/') 87 | parser.add_argument('--batchsize', type=int, 88 | default=32) # we only set BS=24 for efficient inference 89 | parser.add_argument('-dataset_path', type=str, 90 | default='./dataset/TestSet/') 91 | 92 | option = parser.parse_args() 93 | 94 | demo(opt=option) 95 | -------------------------------------------------------------------------------- /lib/fsnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | import torchvision.models as models 6 | from lib.resnets import ResNet50 7 | 8 | 9 | class BasicConv2d(nn.Module): 10 | def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1): 11 | super(BasicConv2d, self).__init__() 12 | self.conv_bn = nn.Sequential( 13 | nn.Conv2d(in_planes, out_planes, 14 | kernel_size=kernel_size, stride=stride, 15 | padding=padding, dilation=dilation, bias=False), 16 | nn.BatchNorm2d(out_planes) 17 | ) 18 | 19 | def forward(self, x): 20 | x = self.conv_bn(x) 21 | return x 22 | 23 | 24 | class DimReduce(nn.Module): 25 | def __init__(self, in_channel, out_channel): 26 | super(DimReduce, self).__init__() 27 | self.reduce = nn.Sequential( 28 | BasicConv2d(in_channel, out_channel, 1), 29 | BasicConv2d(out_channel, out_channel, 3, padding=1), 30 | BasicConv2d(out_channel, out_channel, 3, padding=1) 31 | ) 32 | 33 | def forward(self, x): 34 | return self.reduce(x) 35 | 36 | 37 | class conv_upsample(nn.Module): 38 | def __init__(self, channel): 39 | super(conv_upsample, self).__init__() 40 | self.conv = BasicConv2d(channel, channel, 1) 41 | 42 | def forward(self, x, target): 43 | if x.size()[2:] != target.size()[2:]: 44 | x = self.conv(F.upsample(x, size=target.size()[2:], mode='bilinear', align_corners=True)) 45 | return x 46 | 47 | 48 | class BPM(nn.Module): 49 | def __init__(self, channel): 50 | super(BPM, self).__init__() 51 | self.conv1 = conv_upsample(channel) 52 | self.conv2 = conv_upsample(channel) 53 | self.conv3 = conv_upsample(channel) 54 | self.conv4 = conv_upsample(channel) 55 | self.conv5 = conv_upsample(channel) 56 | self.conv6 = conv_upsample(channel) 57 | self.conv7 = conv_upsample(channel) 58 | self.conv8 = conv_upsample(channel) 59 | self.conv9 = conv_upsample(channel) 60 | self.conv10 = conv_upsample(channel) 61 | self.conv11 = conv_upsample(channel) 62 | self.conv12 = conv_upsample(channel) 63 | 64 | self.conv_f1 = nn.Sequential( 65 | BasicConv2d(5*channel, channel, 3, padding=1), 66 | BasicConv2d(channel, channel, 3, padding=1) 67 | ) 68 | self.conv_f2 = nn.Sequential( 69 | BasicConv2d(4*channel, channel, 3, padding=1), 70 | BasicConv2d(channel, channel, 3, padding=1) 71 | ) 72 | self.conv_f3 = nn.Sequential( 73 | BasicConv2d(3*channel, channel, 3, padding=1), 74 | BasicConv2d(channel, channel, 3, padding=1) 75 | ) 76 | self.conv_f4 = nn.Sequential( 77 | BasicConv2d(2*channel, channel, 3, padding=1), 78 | BasicConv2d(channel, channel, 3, padding=1) 79 | ) 80 | 81 | self.conv_f5 = nn.Sequential( 82 | BasicConv2d(channel, channel, 3, padding=1), 83 | BasicConv2d(channel, channel, 3, padding=1) 84 | ) 85 | self.conv_f6 = nn.Sequential( 86 | BasicConv2d(channel, channel, 3, padding=1), 87 | BasicConv2d(channel, channel, 3, padding=1) 88 | ) 89 | self.conv_f7 = nn.Sequential( 90 | BasicConv2d(channel, channel, 3, padding=1), 91 | BasicConv2d(channel, channel, 3, padding=1) 92 | ) 93 | self.conv_f8 = nn.Sequential( 94 | BasicConv2d(channel, channel, 3, padding=1), 95 | BasicConv2d(channel, channel, 3, padding=1) 96 | ) 97 | 98 | def forward(self, x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4): 99 | x_sf1 = x_s1 + self.conv_f1(torch.cat((x_s1, x_e1, 100 | self.conv1(x_e2, x_s1), 101 | self.conv2(x_e3, x_s1), 102 | self.conv3(x_e4, x_s1)), 1)) 103 | x_sf2 = x_s2 + self.conv_f2(torch.cat((x_s2, x_e2, 104 | self.conv4(x_e3, x_s2), 105 | self.conv5(x_e4, x_s2)), 1)) 106 | x_sf3 = x_s3 + self.conv_f3(torch.cat((x_s3, x_e3, 107 | self.conv6(x_e4, x_s3)), 1)) 108 | x_sf4 = x_s4 + self.conv_f4(torch.cat((x_s4, x_e4), 1)) 109 | 110 | x_ef1 = x_e1 + self.conv_f5(x_e1 * x_s1 * 111 | self.conv7(x_s2, x_e1) * 112 | self.conv8(x_s3, x_e1) * 113 | self.conv9(x_s4, x_e1)) 114 | x_ef2 = x_e2 + self.conv_f6(x_e2 * x_s2 * 115 | self.conv10(x_s3, x_e2) * 116 | self.conv11(x_s4, x_e2)) 117 | x_ef3 = x_e3 + self.conv_f7(x_e3 * x_s3 * 118 | self.conv12(x_s4, x_e3)) 119 | x_ef4 = x_e4 + self.conv_f8(x_e4 * x_s4) 120 | 121 | return x_sf1, x_sf2, x_sf3, x_sf4, x_ef1, x_ef2, x_ef3, x_ef4 122 | 123 | 124 | class PyramidPooling(nn.Module): 125 | """ 126 | Pyramid pooling module 127 | """ 128 | def __init__(self, in_channels, out_channels, **kwargs): 129 | super(PyramidPooling, self).__init__() 130 | inter_channels = int(in_channels / 4) 131 | self.conv1 = BasicConv2d(in_channels, inter_channels, 1, **kwargs) 132 | self.conv2 = BasicConv2d(in_channels, inter_channels, 1, **kwargs) 133 | self.conv3 = BasicConv2d(in_channels, inter_channels, 1, **kwargs) 134 | self.conv4 = BasicConv2d(in_channels, inter_channels, 1, **kwargs) 135 | self.out = BasicConv2d(in_channels * 2, out_channels, 1) 136 | 137 | def pool(self, x, size): 138 | avgpool = nn.AdaptiveAvgPool2d(size) 139 | return avgpool(x) 140 | 141 | def upsample(self, x, size): 142 | return F.interpolate(x, size, mode='bilinear', align_corners=True) 143 | 144 | def forward(self, x): 145 | size = x.size()[2:] 146 | 147 | feat1 = self.upsample(self.conv1(self.pool(x, 1)), size) 148 | feat2 = self.upsample(self.conv2(self.pool(x, 2)), size) 149 | feat3 = self.upsample(self.conv3(self.pool(x, 3)), size) 150 | feat4 = self.upsample(self.conv4(self.pool(x, 6)), size) 151 | x = torch.cat([x, feat1, feat2, feat3, feat4], dim=1) 152 | x = self.out(x) 153 | return x 154 | 155 | 156 | class Decoder(nn.Module): 157 | def __init__(self, channel): 158 | super(Decoder, self).__init__() 159 | self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) 160 | self.conv_upsample1 = BasicConv2d(channel, channel, 3, padding=1) 161 | self.conv_upsample2 = BasicConv2d(channel, channel, 3, padding=1) 162 | self.conv_upsample3 = BasicConv2d(channel, channel, 3, padding=1) 163 | 164 | self.ppm1 = PyramidPooling(channel, channel) 165 | self.ppm2 = PyramidPooling(channel, channel) 166 | self.ppm3 = PyramidPooling(channel, channel) 167 | self.ppm4 = PyramidPooling(channel, channel) 168 | 169 | self.conv_cat1 = nn.Sequential( 170 | BasicConv2d(2*channel, 2*channel, 3, padding=1), 171 | BasicConv2d(2*channel, channel, 1) 172 | ) 173 | self.conv_cat2 = nn.Sequential( 174 | BasicConv2d(2*channel, 2*channel, 3, padding=1), 175 | BasicConv2d(2*channel, channel, 1) 176 | ) 177 | self.conv_cat3 = nn.Sequential( 178 | BasicConv2d(2*channel, 2*channel, 3, padding=1), 179 | BasicConv2d(2*channel, channel, 1) 180 | ) 181 | self.output = nn.Sequential( 182 | BasicConv2d(channel, channel, 3, padding=1), 183 | nn.Conv2d(channel, 1, 1) 184 | ) 185 | 186 | def forward(self, x1, x2, x3, x4): 187 | x4 = self.ppm4(x4) 188 | x3 = torch.cat((x3, self.conv_upsample1(self.upsample(x4))), 1) 189 | x3 = self.conv_cat1(x3) 190 | 191 | x3 = self.ppm3(x3) 192 | x2 = torch.cat((x2, self.conv_upsample2(self.upsample(x3))), 1) 193 | x2 = self.conv_cat2(x2) 194 | 195 | x2 = self.ppm2(x2) 196 | x1 = torch.cat((x1, self.conv_upsample3(self.upsample(x2))), 1) 197 | x1 = self.conv_cat3(x1) 198 | 199 | x1 = self.ppm1(x1) 200 | x = self.output(x1) 201 | 202 | return x 203 | 204 | 205 | class FSNet(nn.Module): 206 | def __init__(self, channel=32): 207 | super(FSNet, self).__init__() 208 | self.resnet = ResNet50() 209 | 210 | # Attention Channel 211 | self.atten_rgb_0 = self.channel_attention(64) 212 | self.atten_flow_0 = self.channel_attention(64) 213 | 214 | self.maxpool_m = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 215 | 216 | self.atten_rgb_1 = self.channel_attention(64 * 4) 217 | self.atten_flow_1 = self.channel_attention(64 * 4) 218 | 219 | self.atten_rgb_2 = self.channel_attention(128 * 4) 220 | self.atten_flow_2 = self.channel_attention(128 * 4) 221 | 222 | self.atten_rgb_3 = self.channel_attention(256 * 4) 223 | self.atten_flow_3 = self.channel_attention(256 * 4) 224 | 225 | self.atten_rgb_4 = self.channel_attention(512 * 4) 226 | self.atten_flow_4 = self.channel_attention(512 * 4) 227 | 228 | self.reduce_a1 = DimReduce(256, channel) 229 | self.reduce_a2 = DimReduce(512, channel) 230 | self.reduce_a3 = DimReduce(1024, channel) 231 | self.reduce_a4 = DimReduce(2048, channel) 232 | 233 | self.reduce_m1 = DimReduce(256, channel) 234 | self.reduce_m2 = DimReduce(512, channel) 235 | self.reduce_m3 = DimReduce(1024, channel) 236 | self.reduce_m4 = DimReduce(2048, channel) 237 | 238 | self.bpm1 = BPM(channel) 239 | self.bpm2 = BPM(channel) 240 | self.bpm3 = BPM(channel) 241 | self.bpm4 = BPM(channel) 242 | 243 | self.output_s = Decoder(channel) 244 | self.output_e = Decoder(channel) 245 | 246 | self.RGBF_conv3 = BasicConv2d(2048, 1024, kernel_size=3, padding=1) 247 | 248 | for m in self.modules(): 249 | if isinstance(m, nn.Conv2d): 250 | m.weight.data.normal_(std=0.01) 251 | elif isinstance(m, nn.BatchNorm2d): 252 | m.weight.data.fill_(1) 253 | m.bias.data.zero_() 254 | 255 | self.initialize_weights() 256 | 257 | def forward(self, x, y): 258 | size = x.size()[2:] 259 | # ---- block_0 ---- 260 | x = self.resnet.conv1_rgb(x) 261 | x = self.resnet.bn1_rgb(x) 262 | x = self.resnet.relu_rgb(x) 263 | y = self.resnet.conv1_flow(y) 264 | y = self.resnet.bn1_flow(y) 265 | y = self.resnet.relu_flow(y) 266 | 267 | atten_rgb = self.atten_rgb_0(x) 268 | atten_flow = self.atten_flow_0(y) 269 | m0 = x.mul(atten_flow) + y.mul(atten_rgb) # (BS, 64, 176, 176) 270 | 271 | # ---- block_1 ---- 272 | x = self.resnet.maxpool_rgb(x) 273 | y = self.resnet.maxpool_flow(y) 274 | m0 = self.resnet.maxpool(m0) 275 | 276 | x1 = self.resnet.layer1_rgb(x) 277 | y1 = self.resnet.layer1_flow(y) 278 | m1 = self.resnet.layer1(m0) 279 | 280 | atten_rgb = self.atten_rgb_1(x1) 281 | atten_flow = self.atten_flow_1(y1) 282 | m1 = m1 + x1.mul(atten_flow) + y1.mul(atten_rgb) # (BS, 256, 88, 88) 283 | 284 | # ---- block_2 ---- 285 | x2 = self.resnet.layer2_rgb(x1) 286 | y2 = self.resnet.layer2_flow(y1) 287 | m2 = self.resnet.layer2(m1) 288 | 289 | atten_rgb = self.atten_rgb_2(x2) 290 | atten_flow = self.atten_flow_2(y2) 291 | m2 = m2 + x2.mul(atten_flow) + y2.mul(atten_rgb) # (bs, 512, 44, 44) 292 | 293 | # ---- block_3 ---- 294 | x3 = self.resnet.layer3_rgb(x2) 295 | y3 = self.resnet.layer3_flow(y2) 296 | m3 = self.resnet.layer3(m2) 297 | 298 | atten_rgb = self.atten_rgb_3(x3) 299 | atten_flow = self.atten_flow_3(y3) 300 | m3 = m3 + x3.mul(atten_flow) + y3.mul(atten_rgb) 301 | 302 | # ---- block_4 ---- 303 | x4 = self.resnet.layer4_rgb(x3) 304 | y4 = self.resnet.layer4_flow(y3) 305 | m4 = self.resnet.layer4(m3) 306 | 307 | atten_rgb = self.atten_rgb_4(x4) 308 | atten_flow = self.atten_flow_4(y4) 309 | m4 = m4 + x4.mul(atten_flow) + y4.mul(atten_rgb) 310 | 311 | # ---- feature abstraction ---- 312 | x_s1 = self.reduce_a1(m1) 313 | x_s2 = self.reduce_a2(m2) 314 | x_s3 = self.reduce_a3(m3) 315 | x_s4 = self.reduce_a4(m4) 316 | 317 | x_e1 = self.reduce_m1(y1) 318 | x_e2 = self.reduce_m2(y2) 319 | x_e3 = self.reduce_m3(y3) 320 | x_e4 = self.reduce_m4(y4) 321 | 322 | # ---- four bi- refinement units ---- 323 | x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4 = self.bpm1(x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4) 324 | x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4 = self.bpm2(x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4) 325 | x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4 = self.bpm3(x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4) 326 | x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4 = self.bpm4(x_s1, x_s2, x_s3, x_s4, x_e1, x_e2, x_e3, x_e4) 327 | 328 | # ---- feature aggregation using naive u-net ---- 329 | pred_s = self.output_s(x_s1, x_s2, x_s3, x_s4) 330 | pred_e = self.output_e(x_e1, x_e2, x_e3, x_e4) 331 | 332 | pred_s = F.upsample(pred_s, size=size, mode='bilinear', align_corners=True) 333 | pred_e = F.upsample(pred_e, size=size, mode='bilinear', align_corners=True) 334 | 335 | return pred_s, pred_e 336 | 337 | def channel_attention(self, num_channel, ablation=False): 338 | # todo add convolution here 339 | pool = nn.AdaptiveAvgPool2d(1) 340 | conv = nn.Conv2d(num_channel, num_channel, kernel_size=1) 341 | 342 | activation = nn.Sigmoid() # todo: modify the activation function 343 | 344 | return nn.Sequential(*[pool, conv, activation]) 345 | 346 | def initialize_weights(self): 347 | res50 = models.resnet50(pretrained=True) 348 | pretrained_dict = res50.state_dict() 349 | all_params = {} 350 | for k, v in self.resnet.state_dict().items(): 351 | if k in pretrained_dict.keys(): 352 | v = pretrained_dict[k] 353 | all_params[k] = v 354 | elif '_flow' in k: 355 | name = k.split('_flow')[0] + k.split('_flow')[1] 356 | v = pretrained_dict[name] 357 | all_params[k] = v 358 | elif '_rgb' in k: 359 | name = k.split('_rgb')[0] + k.split('_rgb')[1] 360 | v = pretrained_dict[name] 361 | all_params[k] = v 362 | 363 | assert len(all_params.keys()) == len(self.resnet.state_dict().keys()) 364 | self.resnet.load_state_dict(all_params) -------------------------------------------------------------------------------- /lib/resnets.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import math 3 | 4 | 5 | def conv3x3(in_planes, out_planes, stride=1): 6 | """3x3 convolution with padding""" 7 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 8 | padding=1, bias=False) 9 | 10 | 11 | class BasicBlock(nn.Module): 12 | expansion = 1 13 | 14 | def __init__(self, inplanes, planes, stride=1, downsample=None): 15 | super(BasicBlock, self).__init__() 16 | self.conv1 = conv3x3(inplanes, planes, stride) 17 | self.bn1 = nn.BatchNorm2d(planes) 18 | self.relu = nn.ReLU(inplace=True) 19 | self.conv2 = conv3x3(planes, planes) 20 | self.bn2 = nn.BatchNorm2d(planes) 21 | self.downsample = downsample 22 | self.stride = stride 23 | 24 | def forward(self, x): 25 | residual = x 26 | 27 | out = self.conv1(x) 28 | out = self.bn1(out) 29 | out = self.relu(out) 30 | 31 | out = self.conv2(out) 32 | out = self.bn2(out) 33 | 34 | if self.downsample is not None: 35 | residual = self.downsample(x) 36 | 37 | out += residual 38 | out = self.relu(out) 39 | 40 | return out 41 | 42 | 43 | class Bottleneck(nn.Module): 44 | expansion = 4 45 | 46 | def __init__(self, inplanes, planes, stride=1, downsample=None): 47 | super(Bottleneck, self).__init__() 48 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) 49 | self.bn1 = nn.BatchNorm2d(planes) 50 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, 51 | padding=1, bias=False) 52 | self.bn2 = nn.BatchNorm2d(planes) 53 | self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) 54 | self.bn3 = nn.BatchNorm2d(planes * 4) 55 | self.relu = nn.ReLU(inplace=True) 56 | self.downsample = downsample 57 | self.stride = stride 58 | 59 | def forward(self, x): 60 | residual = x 61 | 62 | out = self.conv1(x) 63 | out = self.bn1(out) 64 | out = self.relu(out) 65 | 66 | out = self.conv2(out) 67 | out = self.bn2(out) 68 | out = self.relu(out) 69 | 70 | out = self.conv3(out) 71 | out = self.bn3(out) 72 | 73 | if self.downsample is not None: 74 | residual = self.downsample(x) 75 | 76 | out += residual 77 | out = self.relu(out) 78 | 79 | return out 80 | 81 | 82 | class ResNet50(nn.Module): 83 | # ResNet (modified) 84 | def __init__(self): 85 | super(ResNet50, self).__init__() 86 | # ---- rgb ---- 87 | self.inplanes = 64 88 | self.conv1_rgb = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) 89 | self.bn1_rgb = nn.BatchNorm2d(64) 90 | self.relu_rgb = nn.ReLU(inplace=True) 91 | self.maxpool_rgb = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 92 | self.layer1_rgb = self._make_layer(Bottleneck, 64, 3) 93 | self.layer2_rgb = self._make_layer(Bottleneck, 128, 4, stride=2) 94 | self.layer3_rgb = self._make_layer(Bottleneck, 256, 6, stride=2) 95 | self.layer4_rgb = self._make_layer(Bottleneck, 512, 3, stride=2) 96 | # ---- flow --- 97 | self.inplanes = 64 98 | self.conv1_flow = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) 99 | self.bn1_flow = nn.BatchNorm2d(64) 100 | self.relu_flow = nn.ReLU(inplace=True) 101 | self.maxpool_flow = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 102 | self.layer1_flow = self._make_layer(Bottleneck, 64, 3) 103 | self.layer2_flow = self._make_layer(Bottleneck, 128, 4, stride=2) 104 | self.layer3_flow = self._make_layer(Bottleneck, 256, 6, stride=2) 105 | self.layer4_flow = self._make_layer(Bottleneck, 512, 3, stride=2) 106 | # ---- merge ---- 107 | self.inplanes = 64 108 | self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) 109 | self.bn1 = nn.BatchNorm2d(64) 110 | self.relu = nn.ReLU(inplace=True) 111 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 112 | self.layer1 = self._make_layer(Bottleneck, 64, 3) 113 | self.layer2 = self._make_layer(Bottleneck, 128, 4, stride=2) 114 | self.layer3 = self._make_layer(Bottleneck, 256, 6, stride=2) 115 | self.layer4 = self._make_layer(Bottleneck, 512, 3, stride=2) 116 | 117 | for m in self.modules(): 118 | if isinstance(m, nn.Conv2d): 119 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 120 | m.weight.data.normal_(0, math.sqrt(2. / n)) 121 | elif isinstance(m, nn.BatchNorm2d): 122 | m.weight.data.fill_(1) 123 | m.bias.data.zero_() 124 | 125 | def _make_layer(self, block, planes, blocks, stride=1): 126 | downsample = None 127 | if stride != 1 or self.inplanes != planes * block.expansion: 128 | downsample = nn.Sequential( 129 | nn.Conv2d(self.inplanes, planes * block.expansion, 130 | kernel_size=1, stride=stride, bias=False), 131 | nn.BatchNorm2d(planes * block.expansion), 132 | ) 133 | 134 | layers = [] 135 | layers.append(block(self.inplanes, planes, stride, downsample)) 136 | self.inplanes = planes * block.expansion 137 | for i in range(1, blocks): 138 | layers.append(block(self.inplanes, planes)) 139 | 140 | return nn.Sequential(*layers) 141 | 142 | def forward(self, x): 143 | x = self.conv1(x) # 1/2 144 | x = self.bn1(x) 145 | x = self.relu(x) 146 | x = self.maxpool(x) # 1/4 147 | 148 | x = self.layer1(x) 149 | x = self.layer2(x) # 1/8 150 | x = self.layer3(x) # 1/ 16 151 | x = self.layer4(x) # 1/32 152 | 153 | return x -------------------------------------------------------------------------------- /snapshot/FSNet/snapshot.pth: -------------------------------------------------------------------------------- 1 | please download the pre-trained snapshot! -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | from torch.optim import lr_scheduler 4 | from torch.autograd import Variable 5 | import os 6 | import argparse 7 | from datetime import datetime 8 | from utils.dataloader import get_train_loader 9 | from utils.func import AvgMeter, update_predict 10 | from lib.fsnet import FSNet 11 | 12 | 13 | def main(): 14 | parser = argparse.ArgumentParser() 15 | parser.add_argument('--epoch', type=int, default=20, help='epoch number') 16 | parser.add_argument('--lr', type=float, default=2e-3, help='learning rate') 17 | parser.add_argument('--batchsize', type=int, default=16, help='batch size') 18 | parser.add_argument('--trainsize', type=int, default=352, help='input size') 19 | parser.add_argument('--trainset', type=str, default='FSNet') 20 | parser.add_argument('--train_type', type=str, default='finetune', help='finetune or pretrain_rgb or pretrain_flow') 21 | opt = parser.parse_args() 22 | 23 | # build models 24 | model = FSNet().cuda() 25 | 26 | if opt.train_type == 'finetune': 27 | save_path = '../snapshot/{}/'.format(opt.trainset) 28 | # ---- data preparing ---- 29 | src_dir = './dataset/TrainSet_Video' 30 | image_root = src_dir + '/Imgs/' 31 | flow_root = src_dir + '/Flow/' 32 | gt_root = src_dir + '/ground-truth/' 33 | 34 | train_loader = get_train_loader(image_root=image_root, flow_root=flow_root, gt_root=gt_root, 35 | batchsize=opt.batchsize, trainsize=opt.trainsize, shuffle=True, 36 | num_workers=4, pin_memory=True) 37 | total_step = len(train_loader) 38 | # 39 | update_predict(model) 40 | elif opt.train_type == 'pretrain_rgb': 41 | save_path = '../snapshot/{}_rgb/'.format(opt.trainset) 42 | # ---- data preparing ---- 43 | src_dir = './data/TrainSet_StaticAndVideo' 44 | image_root = src_dir + '/Imgs/' 45 | gt_root = src_dir + '/GTs/' 46 | 47 | train_loader = get_train_loader(image_root=image_root, flow_root=image_root, gt_root=gt_root, 48 | batchsize=opt.batchsize, trainsize=opt.trainsize, shuffle=True, 49 | num_workers=4, pin_memory=True) 50 | total_step = len(train_loader) 51 | elif opt.train_type == 'pretrain_flow': 52 | save_path = '../snapshot/{}_flow/'.format(opt.trainset) 53 | # ---- data preparing ---- 54 | src_dir = './dataset/TrainSet_Video' 55 | flow_root = src_dir + '/Flow/' 56 | gt_root = src_dir + '/ground-truth/' 57 | 58 | train_loader = get_train_loader(image_root=flow_root, flow_root=flow_root, gt_root=gt_root, 59 | batchsize=opt.batchsize, trainsize=opt.trainsize, shuffle=True, 60 | num_workers=4, pin_memory=True) 61 | total_step = len(train_loader) 62 | else: 63 | raise AttributeError('No train_type: {}'.format(opt.train_type)) 64 | 65 | # ---- parallel model ---- 66 | model = torch.nn.DataParallel(model, device_ids=[0, 1]) 67 | 68 | params = model.parameters() 69 | optimizer = torch.optim.SGD(params, opt.lr, momentum=0.9, weight_decay=5e-4) 70 | scheduler = lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1) 71 | BCE = torch.nn.BCEWithLogitsLoss() 72 | 73 | # ---- multi-scale training ---- 74 | size_rates = [0.75, 1, 1.25] 75 | 76 | # training 77 | for epoch in range(0, opt.epoch): 78 | scheduler.step() 79 | model.train() 80 | loss_record1, loss_record2 = AvgMeter(), AvgMeter() 81 | 82 | for i, pack in enumerate(train_loader, start=1): 83 | for rate in size_rates: 84 | optimizer.zero_grad() 85 | # ---- get data ---- 86 | images, flows, gts = pack 87 | images = Variable(images).cuda() 88 | flows = Variable(flows).cuda() 89 | gts = Variable(gts).cuda() 90 | # ---- multi-scale training ---- 91 | trainsize = int(round(opt.trainsize*rate/32)*32) 92 | if rate != 1: 93 | images = F.upsample(images, size=(trainsize, trainsize), mode='bilinear', align_corners=True) 94 | flows = F.upsample(flows, size=(trainsize, trainsize), mode='bilinear', align_corners=True) 95 | gts = F.upsample(gts, size=(trainsize, trainsize), mode='bilinear', align_corners=True) 96 | # ---- forward ---- 97 | preds = model(images, flows) 98 | # ---- cal loss ---- 99 | loss1 = BCE(preds[0], gts) 100 | loss2 = BCE(preds[1], gts) 101 | loss = loss1 + loss2 102 | # ---- backward ---- 103 | loss.backward() 104 | optimizer.step() 105 | # ---- show loss ---- 106 | if rate == 1: 107 | loss_record1.update(loss1.data, opt.batchsize) 108 | loss_record2.update(loss2.data, opt.batchsize) 109 | if i % 25 == 0 or i == total_step: 110 | print('{} Epoch [{:03d}/{:03d}], Step [{:04d}/{:04d}], Loss1: {:.4f}, Loss2: {:.4f}'. 111 | format(datetime.now(), epoch, opt.epoch, i, total_step, loss_record1.show(), loss_record2.show())) 112 | 113 | os.makedirs(save_path, exist_ok=True) 114 | if epoch > 15: 115 | if (epoch+1) % 1 == 0: 116 | torch.save(model.state_dict(), save_path + opt.trainset + '-{}epoch.pth'.format(epoch)) 117 | print('[Model Saved] Path: {}'.format(save_path + opt.trainset + '-{}epoch.pth'.format(epoch))) 118 | 119 | 120 | if __name__ == '__main__': 121 | main() 122 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /utils/dataloader.py: -------------------------------------------------------------------------------- 1 | import os, glob, random 2 | from PIL import Image 3 | import torch.utils.data as data 4 | import torchvision.transforms as transforms 5 | 6 | 7 | class VideoObjDataset(data.Dataset): 8 | def __init__(self, image_root, flow_root, gt_root, trainsize): 9 | self.trainsize = trainsize 10 | self.images = [image_root + f for f in os.listdir(image_root) if f.endswith('.jpg')] 11 | self.flows = [flow_root + f for f in os.listdir(flow_root) if f.endswith('.jpg')] 12 | self.gts = [gt_root + f for f in os.listdir(gt_root) if f.endswith('.png')] 13 | 14 | self.images = sorted(self.images) 15 | self.flows = sorted(self.flows) 16 | self.gts = sorted(self.gts) 17 | 18 | self.size = len(self.images) 19 | 20 | self.img_transform = transforms.Compose([ 21 | transforms.Resize((self.trainsize, self.trainsize)), 22 | transforms.ToTensor(), 23 | transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) 24 | self.gt_transform = transforms.Compose([ 25 | transforms.Resize((self.trainsize, self.trainsize)), 26 | transforms.ToTensor()]) 27 | 28 | def __getitem__(self, index): 29 | image = self.rgb_loader(self.images[index]) 30 | flow = self.rgb_loader(self.flows[index]) 31 | gt = self.binary_loader(self.gts[index]) 32 | 33 | image = self.img_transform(image) 34 | flow = self.img_transform(flow) 35 | gt = self.gt_transform(gt) 36 | 37 | return image, flow, gt 38 | 39 | def rgb_loader(self, path): 40 | with open(path, 'rb') as f: 41 | img = Image.open(f) 42 | return img.convert('RGB') 43 | 44 | def binary_loader(self, path): 45 | with open(path, 'rb') as f: 46 | img = Image.open(f) 47 | return img.convert('L') 48 | 49 | def __len__(self): 50 | return self.size 51 | 52 | 53 | def get_train_loader(image_root, flow_root, gt_root, batchsize, trainsize, 54 | shuffle=True, num_workers=12, pin_memory=True): 55 | 56 | dataset = VideoObjDataset(image_root, flow_root, gt_root, trainsize) 57 | data_loader = data.DataLoader(dataset=dataset, 58 | batch_size=batchsize, 59 | shuffle=shuffle, 60 | num_workers=num_workers, 61 | pin_memory=pin_memory) 62 | return data_loader 63 | 64 | 65 | class test_loader(data.Dataset): 66 | def __init__(self, test_root, testsize): 67 | self.testsize = testsize 68 | self.images, self.flows = [], [] 69 | 70 | for seqName in os.listdir(test_root): 71 | seqImage = os.path.join(test_root, seqName, 'Frame') 72 | seqFlow = os.path.join(test_root, seqName, 'OF_FlowNet2') 73 | self.images += sorted([seqImage + '/' + f for f in os.listdir(seqImage) if f.endswith('.jpg')])[:-1] 74 | self.flows += sorted([seqFlow + "/" + f for f in os.listdir(seqFlow) if f.endswith('.jpg')]) 75 | assert len(self.images) == len(self.flows) 76 | 77 | self.transform = transforms.Compose([ 78 | transforms.Resize((self.testsize, self.testsize)), 79 | transforms.ToTensor(), 80 | transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) 81 | 82 | self.size = len(self.images) 83 | 84 | def __getitem__(self, index): 85 | assert self.images[index].split('/')[-1] == self.flows[index].split('/')[-1] 86 | images = self.rgb_loader(self.images[index]) 87 | flows = self.rgb_loader(self.flows[index]) 88 | 89 | images = self.transform(images) 90 | flows = self.transform(flows) 91 | 92 | img_path_list = self.images[index] 93 | 94 | return images, flows, img_path_list 95 | 96 | def rgb_loader(self, path): 97 | with open(path, 'rb') as f: 98 | img = Image.open(f) 99 | return img.convert('RGB') 100 | 101 | def binary_loader(self, path): 102 | with open(path, 'rb') as f: 103 | img = Image.open(f) 104 | return img.convert('L') 105 | 106 | def __len__(self): 107 | return self.size 108 | 109 | 110 | def get_test_loader(test_root, batchsize, trainsize, shuffle=False, num_workers=12, pin_memory=True): 111 | 112 | dataset = test_loader(test_root, trainsize) 113 | dataset_size = dataset.size 114 | 115 | data_loader = data.DataLoader(dataset=dataset, 116 | batch_size=batchsize, 117 | shuffle=shuffle, 118 | num_workers=num_workers, 119 | pin_memory=pin_memory) 120 | return data_loader, dataset_size -------------------------------------------------------------------------------- /utils/func.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.autograd import Variable 3 | import numpy as np 4 | 5 | fx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]).astype(np.float32) 6 | fy = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]).astype(np.float32) 7 | fx = np.reshape(fx, (1, 1, 3, 3)) 8 | fy = np.reshape(fy, (1, 1, 3, 3)) 9 | fx = Variable(torch.from_numpy(fx)).cuda() 10 | fy = Variable(torch.from_numpy(fy)).cuda() 11 | contour_th = 1.5 12 | 13 | 14 | class AvgMeter(object): 15 | def __init__(self, num=40): 16 | self.num = num 17 | self.reset() 18 | 19 | def reset(self): 20 | self.val = 0 21 | self.avg = 0 22 | self.sum = 0 23 | self.count = 0 24 | self.losses = [] 25 | 26 | def update(self, val, n=1): 27 | self.val = val 28 | self.sum += val * n 29 | self.count += n 30 | self.avg = self.sum / self.count 31 | self.losses.append(val) 32 | 33 | def show(self): 34 | return torch.mean(torch.stack(self.losses[np.maximum(len(self.losses)-self.num, 0):])) 35 | 36 | 37 | def update_predict(model): 38 | # load pretrained model (rgb+interaction modules) 39 | # ---- copy model-a to model-b ---- 40 | model_dict = model.state_dict() # copy base models to the object models 41 | state_dict = torch.load('../snapshot/FSNet/2021-ICCV-FSNet_rgb-20epoch-new.pth') # 42 | # ---- for checking state_dict ---- 43 | # for k, v in state_dict.items(): 44 | # print(k, ':', v.min(), v.max()) 45 | new_state_dict = {k.replace('module.', ''): v for k, v in state_dict.items() if k.replace('module.', '') in model_dict} 46 | model_dict.update(new_state_dict) 47 | model.load_state_dict(model_dict) 48 | 49 | # load pretrained model (flow) 50 | # ---- copy model-a to model-b ---- 51 | model_dict = model.state_dict() # copy base models to the object models 52 | state_dict = torch.load('../snapshot/FSNet/2021-ICCV-FSNet_flow-20epoch-new.pth') # 53 | # new_state_dict = {k: v for k, v in state_dict.items() if k in model_dict} 54 | load_keyword_list = ['resnet.conv1_flow', 'resnet.bn1_flow', 'resnet.layer1_flow', 'resnet.layer2_flow', 55 | 'resnet.layer3_flow', 'resnet.layer4_flow'] 56 | for keyword in load_keyword_list: 57 | for k, v in state_dict.items(): 58 | if 'running_mean' not in k and 'running_var' not in k: 59 | if keyword in k: 60 | model_dict[k] = v 61 | print('[Checking] load flow branch -> key-name: {}'.format(k)) 62 | # model_dict.update(new_state_dict) 63 | model.load_state_dict(model_dict) --------------------------------------------------------------------------------