├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── capture └── capture.jpg ├── embeddings └── carpet │ └── embedding.pickle ├── old └── README.md ├── requirements.txt ├── sampling_methods ├── kcenter_greedy.py └── sampling_def.py └── train.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # embedding.pickle 132 | ./embeddings/ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/home/changwoo/anaconda3/envs/pl/bin/python" 3 | } -------------------------------------------------------------------------------- /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 | # It's a branch for industry 2 | *The faiss version was added.//2024.01.06 3 | 4 | *The changes are as follows: 5 | 6 | ### 1.Use a ng instead of gt 7 | ~~~ 8 | class 9 | ├── test 10 | │ ├── good 11 | │ └── ng 12 | ├── train 13 | └── good 14 | 15 | ~~~ 16 | 17 | ### 2.Support Libtorch 18 | ~~~ 19 | *Two files are stored after the test. 20 | # extracted features , Instead of pickle 21 | patchcore_features.pt 22 | 23 | # wide_resnet50_2 24 | patchcore_model.pt 25 | 26 | *You can use c++ as follows. 27 | vision::models::WideResNet50_2 module_wideresnet_50_;//https://github.com/pytorch/vision 28 | auto anomaly_features = torch::jit::load("patchcore_features.pt"); 29 | anomaly_features.attr("feature").toTensor().to(at::kCUDA); 30 | 31 | torch::load(module_wideresnet_50_, "patchcore_model.pt"); 32 | module_wideresnet_50_->eval(); 33 | module_wideresnet_50_->to(at::kCUDA); 34 | 35 | auto inputs = get_inputs();//image tensor 36 | auto x = module_wideresnet_50_->conv1->forward(inputs); 37 | x = module_wideresnet_50_->bn1->forward(x).relu_(); 38 | x = torch::max_pool2d(x, 3, 2, 1); 39 | 40 | *instead of register_forward_hook 41 | auto outputs1 = module_wideresnet_50_->layer1->forward(x); 42 | auto outputs2 = module_wideresnet_50_->layer2->forward(outputs1); 43 | auto outputs3 = module_wideresnet_50_->layer3->forward(outputs2); 44 | 45 | auto m = AvgPool2d(AvgPool2dOptions(3).stride(1).padding(1)); 46 | auto embed1 = m(outputs2); 47 | auto embed2 = m(outputs3); 48 | 49 | auto embedding_concat = [](torch::Tensor x, torch::Tensor y) { 50 | int64 B1 = x.size(0), C1 = x.size(1), H1 = x.size(2), W1 = x.size(3); 51 | int64 B2 = y.size(0), C2 = y.size(1), H2 = y.size(2), W2 = y.size(3); 52 | int64 s = H1 / H2; 53 | 54 | x = F::unfold(x, F::UnfoldFuncOptions(s).dilation(1).stride(s)); 55 | x = x.view({B1, C1, -1, H2, W2}); 56 | auto z = torch::zeros({B1, C1 + C2, x.size(2), H2, W2}); 57 | for (int i = 0; i < x.size(2); i++) { 58 | auto temp = x.index({Slice(None, None), Slice(None, None), i, 59 | Slice(None, None), Slice(None, None)}); 60 | z.index({Slice(None, None), Slice(None, None), i, Slice(None, None), 61 | Slice(None, None)}) = torch::cat({temp, y}, 1); 62 | } 63 | 64 | z = z.view({B1, -1, H2 * W2}); 65 | z = F::fold(z, F::FoldFuncOptions({H1, W1}, {s, s}).stride(s)) 66 | .to(at::kCUDA); 67 | 68 | return z; 69 | }; 70 | 71 | auto embedding_vectors = embedding_concat(embed1, embed2); 72 | 73 | //reshape_embedding 74 | embedding_vectors.squeeze_(); 75 | embedding_vectors = embedding_vectors.reshape( 76 | {embedding_vectors.size(0), 77 | embedding_vectors.size(1) * embedding_vectors.size(2)}); 78 | embedding_vectors = embedding_vectors.permute({1, 0}); 79 | 80 | 81 | int p = 2; 82 | int k = 9; 83 | auto dist = torch::cdist(embedding_vectors, anomaly_features, p); 84 | auto knn = std::get<0>(dist.topk(k, -1, false)); 85 | int block_size =static_cast(std::sqrt(knn.size(0))); 86 | auto anomaly_map = knn.index({Slice(None, None), 0}).reshape({block_size, block_size}); 87 | double max_score = cfg_.vanomaly[category].anomalyMaxScore; 88 | double min_score = cfg_.vanomaly[category].anomalyMinScore; 89 | auto scores = (anomaly_map - min_score) / (max_score - min_score); 90 | 91 | auto scores_resized = 92 | F::interpolate( 93 | scores.unsqueeze(0).unsqueeze(0), 94 | F::InterpolateFuncOptions() 95 | .size(std::vector{cfg_.origin_height, cfg_.origin_width}) 96 | .align_corners(false) 97 | .mode(torch::kBilinear)) 98 | .squeeze() 99 | .squeeze(); 100 | 101 | auto anomaly_mat = tensor2dToMat(scores_resized.to(at::kCPU)); 102 | 103 | cv::Mat anomaly_colormap, anomaly_mat_scaled; 104 | anomaly_mat.at(0, 0) = 1; 105 | anomaly_mat.convertTo(anomaly_mat_scaled, CV_8UC3, 255.f); 106 | 107 | applyColorMap(anomaly_mat_scaled, anomaly_colormap, cv::COLORMAP_JET); 108 | cv::Mat anomaly_mat_origin_size; 109 | cv::resize(anomaly_colormap, anomaly_mat_origin_size, {cfg_.origin_height, cfg_.origin_width}); 110 | auto origin_mat = get_origin_image_buffers()[batch_idx]; 111 | 112 | cv::resize(origin_mat, anomaly_mat_origin_size, {cfg_.origin_height, cfg_.origin_width}); 113 | cv::Mat dst; 114 | cv::addWeighted(anomaly_mat_origin_size, 0.5, anomaly_colormap, 1 - 0.5, 0, dst); 115 | 116 | ... 117 | 118 | ~~~ 119 | 120 | ### 3.Support Faiss 121 | ~~~ 122 | If use faiss version of the main branch 123 | Refer to PatchCore.cpp 124 | ~~~ 125 | 126 | ### 4.Use all data for heatmap 127 | *We can see the difference between NG and GOOD. 128 | ![image](https://user-images.githubusercontent.com/17777591/130405811-7d29432f-5be2-4c5b-a324-d95f526bb725.png) 129 | ![image](https://user-images.githubusercontent.com/17777591/130405756-371c582f-6c8c-4f46-bc6d-5e572b9a1ccc.png) 130 | 131 | 132 | 133 | 134 | ### 5.Using ROC Curve for best threshold detection 135 | *Find the threshold value with the mean value of the anomaly map. 136 | ![image](https://user-images.githubusercontent.com/17777591/130405911-2c6077d0-80d8-41ba-914f-9683f0ac926f.png) 137 | 138 | 139 | # PatchCore anomaly detection 140 | Unofficial implementation of PatchCore(new SOTA) anomaly detection model 141 | 142 | 143 | Original Paper : 144 | Towards Total Recall in Industrial Anomaly Detection (Jun 2021) 145 | Karsten Roth, Latha Pemula, Joaquin Zepeda, Bernhard Schölkopf, Thomas Brox, Peter Gehler 146 | 147 | 148 | https://arxiv.org/abs/2106.08265 149 | https://paperswithcode.com/sota/anomaly-detection-on-mvtec-ad 150 | 151 | ![plot](./capture/capture.jpg) 152 | 153 | 154 | ### Usage 155 | ~~~ 156 | # install python 3.6, torch==1.8.1, torchvision==0.9.1 157 | pip install -r requirements.txt 158 | 159 | python train.py --phase train or test --dataset_path .../mvtec_anomaly_detection --category carpet --project_root_path path/to/save/results --coreset_sampling_ratio 0.01 --n_neighbors 9' 160 | 161 | # for fast try just specify your dataset_path and run 162 | python train.py --phase test --dataset_path .../mvtec_anomaly_detection --project_root_path ./ 163 | ~~~ 164 | 165 | -------------------------------------------------------------------------------- /capture/capture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dhkdnduq/PatchCore_anomaly_detection/3a093c27cae94e26433400367983ca719b0ff612/capture/capture.jpg -------------------------------------------------------------------------------- /embeddings/carpet/embedding.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dhkdnduq/PatchCore_anomaly_detection/3a093c27cae94e26433400367983ca719b0ff612/embeddings/carpet/embedding.pickle -------------------------------------------------------------------------------- /old/README.md: -------------------------------------------------------------------------------- 1 | # PatchCore anomaly detection 2 | Unofficial implementation of PatchCore(new SOTA) anomaly detection model 3 | 4 | 5 | Original Paper : 6 | Towards Total Recall in Industrial Anomaly Detection (Jun 2021) 7 | Karsten Roth, Latha Pemula, Joaquin Zepeda, Bernhard Schölkopf, Thomas Brox, Peter Gehler 8 | 9 | 10 | https://arxiv.org/abs/2106.08265 11 | 12 | notice(21/06/18) : 13 | This code is not yet verified. Any feedback is appreciated. 14 | 15 | ### Usage 16 | ~~~ 17 | # python 3.6 18 | pip install -r requirements.txt 19 | python train.py --phase train or test --dataset_path .../mvtec_anomaly_detection --category carpet --project_root_path path/to/save/results --coreset_sampling_ratio 0.01 --n_neighbors 9' 20 | ~~~ 21 | 22 | ### MVTecAD AUROC score (PatchCore-1%, mean of n trials) 23 | | Category | Paper
(image-level) | This code
(image-level) | Paper
(pixel-level) | This code
(pixel-level) | 24 | | :-----: | :-: | :-: | :-: | :-: | 25 | | carpet | 0.980 | 0.995(1) | 0.989 | 0.989(1) | 26 | | grid | 0.986 | 0.899(1) | 0.986 | 0.978(1) | 27 | | leather | 1.000 | 1.000 | 0.993 | 0.992(1) | 28 | | tile | 0.994 | 0.981(1) | 0.961 | 0.932(1) | 29 | | wood | 0.992 | - | 0.951 | - | 30 | | bottle | 1.000 | - | 0.985 | - | 31 | | cable | 0.993 | - | 0.982 | - | 32 | | capsule | 0.980 | - | 0.988 | - | 33 | | hazelnut | 1.000 | - | 0.986 | - | 34 | | metal nut | 0.997 | - | 0.984 | - | 35 | | pill | 0.970 | - | 0.971 | - | 36 | | screw | 0.964 | - | 0.992 | - | 37 | | toothbrush | 1.000 | - | 0.985 | - | 38 | | transistor | 0.999 | -| 0.949 | - | 39 | | zipper | 0.992 | - | 0.988 | - | 40 | | mean | 0.990 | - | 0.980 | - | 41 | 42 | ### Code Reference 43 | https://github.com/google/active-learning 44 | https://github.com/xiahaifeng1995/PaDiM-Anomaly-Detection-Localization-master 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python==4.5.2.52 2 | scikit-learn==0.24.2 3 | pytorch-lightning==1.3.3 4 | -------------------------------------------------------------------------------- /sampling_methods/kcenter_greedy.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Google Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Returns points that minimizes the maximum distance of any point to a center. 16 | 17 | Implements the k-Center-Greedy method in 18 | Ozan Sener and Silvio Savarese. A Geometric Approach to Active Learning for 19 | Convolutional Neural Networks. https://arxiv.org/abs/1708.00489 2017 20 | 21 | Distance metric defaults to l2 distance. Features used to calculate distance 22 | are either raw features or if a model has transform method then uses the output 23 | of model.transform(X). 24 | 25 | Can be extended to a robust k centers algorithm that ignores a certain number of 26 | outlier datapoints. Resulting centers are solution to multiple integer program. 27 | """ 28 | 29 | from __future__ import absolute_import 30 | from __future__ import division 31 | from __future__ import print_function 32 | 33 | import numpy as np 34 | from sklearn.metrics import pairwise_distances 35 | from sampling_methods.sampling_def import SamplingMethod 36 | 37 | 38 | class kCenterGreedy(SamplingMethod): 39 | 40 | def __init__(self, X, y, seed, metric='euclidean'): 41 | self.X = X 42 | self.y = y 43 | self.flat_X = self.flatten_X() 44 | self.name = 'kcenter' 45 | self.features = self.flat_X 46 | self.metric = metric 47 | self.min_distances = None 48 | self.n_obs = self.X.shape[0] 49 | self.already_selected = [] 50 | 51 | def update_distances(self, cluster_centers, only_new=True, reset_dist=False): 52 | """Update min distances given cluster centers. 53 | 54 | Args: 55 | cluster_centers: indices of cluster centers 56 | only_new: only calculate distance for newly selected points and update 57 | min_distances. 58 | rest_dist: whether to reset min_distances. 59 | """ 60 | 61 | if reset_dist: 62 | self.min_distances = None 63 | if only_new: 64 | cluster_centers = [d for d in cluster_centers 65 | if d not in self.already_selected] 66 | if cluster_centers: 67 | # Update min_distances for all examples given new cluster center. 68 | x = self.features[cluster_centers] 69 | dist = pairwise_distances(self.features, x, metric=self.metric) 70 | 71 | if self.min_distances is None: 72 | self.min_distances = np.min(dist, axis=1).reshape(-1,1) 73 | else: 74 | self.min_distances = np.minimum(self.min_distances, dist) 75 | 76 | def select_batch_(self, model, already_selected, N, **kwargs): 77 | """ 78 | Diversity promoting active learning method that greedily forms a batch 79 | to minimize the maximum distance to a cluster center among all unlabeled 80 | datapoints. 81 | 82 | Args: 83 | model: model with scikit-like API with decision_function implemented 84 | already_selected: index of datapoints already selected 85 | N: batch size 86 | 87 | Returns: 88 | indices of points selected to minimize distance to cluster centers 89 | """ 90 | 91 | try: 92 | # Assumes that the transform function takes in original data and not 93 | # flattened data. 94 | print('Getting transformed features...') 95 | self.features = model.transform(self.X) 96 | print('Calculating distances...') 97 | self.update_distances(already_selected, only_new=False, reset_dist=True) 98 | except: 99 | print('Using flat_X as features.') 100 | self.update_distances(already_selected, only_new=True, reset_dist=False) 101 | 102 | new_batch = [] 103 | 104 | for _ in range(N): 105 | if self.already_selected is None: 106 | # Initialize centers with a randomly selected datapoint 107 | ind = np.random.choice(np.arange(self.n_obs)) 108 | else: 109 | ind = np.argmax(self.min_distances) 110 | # New examples should not be in already selected since those points 111 | # should have min_distance of zero to a cluster center. 112 | assert ind not in already_selected 113 | 114 | self.update_distances([ind], only_new=True, reset_dist=False) 115 | new_batch.append(ind) 116 | print('Maximum distance from cluster centers is %0.2f' 117 | % max(self.min_distances)) 118 | 119 | 120 | self.already_selected = already_selected 121 | 122 | return new_batch 123 | 124 | -------------------------------------------------------------------------------- /sampling_methods/sampling_def.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017 Google Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Abstract class for sampling methods. 16 | 17 | Provides interface to sampling methods that allow same signature 18 | for select_batch. Each subclass implements select_batch_ with the desired 19 | signature for readability. 20 | """ 21 | 22 | from __future__ import absolute_import 23 | from __future__ import division 24 | from __future__ import print_function 25 | 26 | import abc 27 | import numpy as np 28 | 29 | class SamplingMethod(object): 30 | __metaclass__ = abc.ABCMeta 31 | 32 | @abc.abstractmethod 33 | def __init__(self, X, y, seed, **kwargs): 34 | self.X = X 35 | self.y = y 36 | self.seed = seed 37 | 38 | def flatten_X(self): 39 | shape = self.X.shape 40 | flat_X = self.X 41 | if len(shape) > 2: 42 | flat_X = np.reshape(self.X, (shape[0],np.product(shape[1:]))) 43 | return flat_X 44 | 45 | 46 | @abc.abstractmethod 47 | def select_batch_(self): 48 | return 49 | 50 | def select_batch(self, **kwargs): 51 | return self.select_batch_(**kwargs) 52 | 53 | def to_dict(self): 54 | return None -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import torch 3 | from torch.nn import functional as F 4 | from torch import nn 5 | from torchvision import transforms 6 | from torch.utils.data import Dataset, DataLoader 7 | import cv2 8 | import numpy as np 9 | import os 10 | import glob 11 | import shutil 12 | from PIL import Image 13 | from sklearn.metrics import roc_auc_score 14 | from torch import nn 15 | import pytorch_lightning as pl 16 | from sklearn.metrics import confusion_matrix 17 | import pickle 18 | from sampling_methods.kcenter_greedy import kCenterGreedy 19 | from sklearn.random_projection import SparseRandomProjection 20 | from sklearn.neighbors import NearestNeighbors 21 | from scipy.ndimage import gaussian_filter 22 | import gc 23 | import csv 24 | import time 25 | from sklearn.metrics import roc_auc_score, roc_curve 26 | import pandas as pd 27 | import matplotlib.pyplot as plt 28 | import seaborn as sns 29 | import matplotlib 30 | from torchvision.models import wide_resnet50_2 31 | 32 | 33 | class TrainFeature(torch.jit.ScriptModule): 34 | #__constants__ = ['feature'] 35 | 36 | def __init__(self,feature_): 37 | super(TrainFeature, self).__init__() 38 | #self.feature = feature_ 39 | self.register_buffer('feature', feature_) 40 | def forward(self): 41 | pass 42 | 43 | 44 | def copy_files(src, dst, ignores=[]): 45 | src_files = os.listdir(src) 46 | for file_name in src_files: 47 | ignore_check = [True for i in ignores if i in file_name] 48 | if ignore_check: 49 | continue 50 | full_file_name = os.path.join(src, file_name) 51 | if os.path.isfile(full_file_name): 52 | shutil.copy(full_file_name, os.path.join(dst,file_name)) 53 | if os.path.isdir(full_file_name): 54 | os.makedirs(os.path.join(dst, file_name), exist_ok=True) 55 | copy_files(full_file_name, os.path.join(dst, file_name), ignores) 56 | 57 | def prep_dirs(root): 58 | # make embeddings dir 59 | # embeddings_path = os.path.join(root, 'embeddings') 60 | embeddings_path = os.path.join('./', 'embeddings', args.category) 61 | os.makedirs(embeddings_path, exist_ok=True) 62 | # make sample dir 63 | sample_path = os.path.join(root, 'sample') 64 | os.makedirs(sample_path, exist_ok=True) 65 | # make source code record dir & copy 66 | source_code_save_path = os.path.join(root, 'src') 67 | os.makedirs(source_code_save_path, exist_ok=True) 68 | #copy_files('./', source_code_save_path, ['.git','.vscode','__pycache__','logs','README','samples','LICENSE']) # copy source code 69 | return embeddings_path, sample_path, source_code_save_path 70 | 71 | def embedding_concat(x, y): 72 | # from https://github.com/xiahaifeng1995/PaDiM-Anomaly-Detection-Localization-master 73 | B, C1, H1, W1 = x.size() 74 | _, C2, H2, W2 = y.size() 75 | s = int(H1 / H2) 76 | x = F.unfold(x, kernel_size=s, dilation=1, stride=s) 77 | x = x.view(B, C1, -1, H2, W2) 78 | z = torch.zeros(B, C1 + C2, x.size(2), H2, W2) 79 | for i in range(x.size(2)): 80 | z[:, :, i, :, :] = torch.cat((x[:, :, i, :, :], y), 1) 81 | z = z.view(B, -1, H2 * W2) 82 | z = F.fold(z, kernel_size=s, output_size=(H1, W1), stride=s) 83 | 84 | return z 85 | 86 | def reshape_embedding(embedding): 87 | embedding_list = [] 88 | for k in range(embedding.shape[0]): 89 | for i in range(embedding.shape[2]): 90 | for j in range(embedding.shape[3]): 91 | embedding_list.append(embedding[k, :, i, j]) 92 | 93 | return embedding_list 94 | 95 | #imagenet 96 | mean_train = [0.485, 0.456, 0.406] 97 | std_train = [0.229, 0.224, 0.225] 98 | 99 | class MVTecDataset(Dataset): 100 | def __init__(self, root, transform, phase): 101 | if phase=='train': 102 | self.img_path = os.path.join(root, 'train') 103 | else: 104 | self.img_path = os.path.join(root, 'test') 105 | 106 | self.transform = transform 107 | # load dataset 108 | self.img_paths, self.labels, self.types = self.load_dataset() # self.labels => good : 0, anomaly : 1 109 | 110 | def load_dataset(self): 111 | 112 | img_tot_paths = [] 113 | tot_labels = [] 114 | tot_types = [] 115 | 116 | defect_types = os.listdir(self.img_path) 117 | img_types = ('*.png','*.bmp','*.jpg') 118 | 119 | for defect_type in defect_types: 120 | img_paths = [] 121 | if defect_type == 'good': 122 | for img_type in img_types: 123 | img_paths.extend(glob.glob(os.path.join(self.img_path, defect_type) + '/'+ img_type)) 124 | 125 | img_tot_paths.extend(img_paths) 126 | tot_labels.extend([0]*len(img_paths)) 127 | tot_types.extend(['good']*len(img_paths)) 128 | else: 129 | for img_type in img_types: 130 | img_paths.extend(glob.glob(os.path.join(self.img_path, defect_type) + '/' + img_type)) 131 | 132 | img_paths.sort() 133 | img_tot_paths.extend(img_paths) 134 | tot_labels.extend([1]*len(img_paths)) 135 | tot_types.extend([defect_type]*len(img_paths)) 136 | 137 | 138 | return img_tot_paths, tot_labels, tot_types 139 | 140 | def __len__(self): 141 | return len(self.img_paths) 142 | 143 | def __getitem__(self, idx): 144 | img_path, label, img_type = self.img_paths[idx], self.labels[idx], self.types[idx] 145 | img = Image.open(img_path).convert('RGB') 146 | img = self.transform(img) 147 | 148 | return img,label, os.path.basename(img_path[:-4]), img_type 149 | 150 | 151 | def cvt2heatmap(gray): 152 | heatmap = cv2.applyColorMap(np.uint8(gray), cv2.COLORMAP_JET) 153 | return heatmap 154 | 155 | def heatmap_on_image(heatmap, image): 156 | if heatmap.shape != image.shape: 157 | heatmap = cv2.resize(heatmap, (image.shape[0], image.shape[1])) 158 | out = np.float32(heatmap)/255 + np.float32(image)/255 159 | out = out / np.max(out) 160 | return np.uint8(255 * out) 161 | 162 | def min_max_norm(image): 163 | a_min, a_max = image.min(), image.max() 164 | return (image-a_min)/(a_max - a_min) 165 | 166 | 167 | def cal_confusion_matrix(y_true, y_pred_no_thresh, thresh, img_path_list): 168 | pred_thresh = [] 169 | false_n = [] 170 | false_p = [] 171 | for i in range(len(y_pred_no_thresh)): 172 | if y_pred_no_thresh[i] > thresh: 173 | pred_thresh.append(1) 174 | if y_true[i] == 0: 175 | false_p.append(img_path_list[i]) 176 | else: 177 | pred_thresh.append(0) 178 | if y_true[i] == 1: 179 | false_n.append(img_path_list[i]) 180 | 181 | cm = confusion_matrix(y_true, pred_thresh) 182 | print(cm) 183 | print('false positive') 184 | print(false_p) 185 | print('false negative') 186 | print(false_n) 187 | 188 | def randomize_tensor(tensor): 189 | return tensor[torch.randperm(len(tensor))] 190 | 191 | 192 | 193 | 194 | class NN(): 195 | 196 | def __init__(self, X=None, Y=None, p=2): 197 | self.p = p 198 | self.train(X, Y) 199 | 200 | def train(self, X, Y): 201 | self.train_pts = X 202 | self.train_label = Y 203 | 204 | def __call__(self, x): 205 | return self.predict(x) 206 | 207 | def predict(self, x): 208 | if type(self.train_pts) == type(None) or type(self.train_label) == type(None): 209 | name = self.__class__.__name__ 210 | raise RuntimeError(f"{name} wasn't trained. Need to execute {name}.train() first") 211 | 212 | #dist = distance_matrix(x, self.train_pts, self.p) ** (1 / self.p) 213 | dist = torch.cdist(x, self.train_pts, self.p) 214 | labels = torch.argmin(dist, dim=1) 215 | return self.train_label[labels] 216 | class KNN(NN): 217 | 218 | def __init__(self, X=None, Y=None, k=3, p=2): 219 | self.k = k 220 | super().__init__(X, Y, p) 221 | 222 | def train(self, X, Y): 223 | super().train(X, Y) 224 | if type(Y) != type(None): 225 | self.unique_labels = self.train_label.unique() 226 | 227 | def predict(self, x): 228 | 229 | test = 1 / self.p 230 | #dist = distance_matrix(x, self.train_pts, self.p) ** (1 / self.p) 231 | dist = torch.cdist(x, self.train_pts, self.p) 232 | knn = dist.topk(self.k, largest=False) 233 | 234 | 235 | return knn 236 | 237 | 238 | class STPM(pl.LightningModule): 239 | def __init__(self, hparams): 240 | super(STPM, self).__init__() 241 | 242 | self.save_hyperparameters(hparams) 243 | 244 | self.init_features() 245 | def hook_t(module, input, output): 246 | self.features.append(output) 247 | 248 | self.model = torch.hub.load('pytorch/vision:v0.9.0', 'wide_resnet50_2', pretrained=True) 249 | #self.model = wide_resnet50_2(pretrained=True, progress=True) 250 | for param in self.model.parameters(): 251 | param.requires_grad = False 252 | 253 | self.model.layer2[-1].register_forward_hook(hook_t) 254 | self.model.layer3[-1].register_forward_hook(hook_t) 255 | 256 | self.criterion = torch.nn.MSELoss(reduction='sum') 257 | 258 | self.init_results_list() 259 | 260 | self.data_transforms = transforms.Compose([ 261 | transforms.Resize((args.input_size, args.input_size), Image.ANTIALIAS), 262 | transforms.ToTensor(), 263 | transforms.CenterCrop(args.input_size), 264 | transforms.Normalize(mean=mean_train, 265 | std=std_train)]) 266 | 267 | 268 | self.inv_normalize = transforms.Normalize(mean=[-0.485/0.229, -0.456/0.224, -0.406/0.255], std=[1/0.229, 1/0.224, 1/0.255]) 269 | 270 | def init_results_list(self): 271 | self.img_path_list = [] 272 | self.mean_score_norm = [] 273 | self.all_scores = [] 274 | self.all_scores_mean_norm = [] 275 | self.image_batch_list = [] 276 | self.x_type_list =[] 277 | self.y_true = [] 278 | def init_features(self): 279 | self.features = [] 280 | 281 | def forward(self, x_t): 282 | self.init_features() 283 | _ = self.model(x_t) 284 | return self.features 285 | 286 | def save_anomaly_map(self, anomaly_map, input_img, gt_img, file_name, x_type): 287 | if anomaly_map.shape != input_img.shape: 288 | anomaly_map = cv2.resize(anomaly_map, (input_img.shape[0], input_img.shape[1])) 289 | anomaly_map_norm = min_max_norm(anomaly_map) 290 | anomaly_map_norm_hm = cvt2heatmap(anomaly_map_norm*255) 291 | 292 | # anomaly map on image 293 | heatmap = cvt2heatmap(anomaly_map_norm*255) 294 | hm_on_img = heatmap_on_image(heatmap, input_img) 295 | 296 | # save images 297 | cv2.imwrite(os.path.join(self.sample_path, f'{x_type}_{file_name}.jpg'), input_img) 298 | cv2.imwrite(os.path.join(self.sample_path, f'{x_type}_{file_name}_amap.jpg'), anomaly_map_norm_hm) 299 | cv2.imwrite(os.path.join(self.sample_path, f'{x_type}_{file_name}_amap_on_img.jpg'), hm_on_img) 300 | 301 | def train_dataloader(self): 302 | image_datasets = MVTecDataset(root=os.path.join(args.dataset_path,args.category), transform=self.data_transforms, phase='train') 303 | train_loader = DataLoader(image_datasets, batch_size=args.batch_size, shuffle=True, num_workers=0) #, pin_memory=True) 304 | return train_loader 305 | 306 | def test_dataloader(self): 307 | test_datasets = MVTecDataset(root=os.path.join(args.dataset_path,args.category), transform=self.data_transforms, phase='test') 308 | test_loader = DataLoader(test_datasets, batch_size=1, shuffle=False, num_workers=0) #, pin_memory=True) # only work on batch_size=1, now. 309 | return test_loader 310 | 311 | def configure_optimizers(self): 312 | return None 313 | 314 | def on_train_start(self): 315 | self.model.eval() # to stop running_var move (maybe not critical) 316 | self.embedding_dir_path, self.sample_path, self.source_code_save_path = prep_dirs(self.logger.log_dir) 317 | self.embedding_list = [] 318 | 319 | def on_test_start(self): 320 | self.init_results_list() 321 | self.embedding_dir_path, self.sample_path, self.source_code_save_path = prep_dirs(self.logger.log_dir) 322 | self.embedding_coreset = pickle.load(open(os.path.join(self.embedding_dir_path, 'embedding.pickle'), 'rb')) 323 | embeded = torch.tensor(self.embedding_coreset) 324 | train_jit = TrainFeature(embeded) 325 | traced_model = torch.jit.script(train_jit) 326 | torch.jit.save(traced_model, "patchcore_features.pt") 327 | dummy_input = torch.randn(args.batch_size, 3, args.input_size, args.input_size, requires_grad=False).cuda() 328 | traced_script_module = torch.jit.trace(self.model, dummy_input) 329 | traced_script_module.save("patchcore_model.pt") 330 | 331 | 332 | 333 | def training_step(self, batch, batch_idx): # save locally aware patch features 334 | x, _, file_name, _ = batch 335 | features = self(x) 336 | embeddings = [] 337 | for feature in features: 338 | m = torch.nn.AvgPool2d(3, 1, 1) 339 | embeddings.append(m(feature)) 340 | embedding = embedding_concat(embeddings[0], embeddings[1]) 341 | self.embedding_list.extend(reshape_embedding(np.array(embedding))) 342 | gc.collect() 343 | 344 | def training_epoch_end(self, outputs): 345 | total_embeddings = np.array(self.embedding_list) 346 | # Random projection 347 | self.randomprojector = SparseRandomProjection(n_components='auto', eps=0.9) # 'auto' => Johnson-Lindenstrauss lemma 348 | self.randomprojector.fit(total_embeddings) 349 | # Coreset Subsampling 350 | selector = kCenterGreedy(total_embeddings,0,0) 351 | selected_idx = selector.select_batch(model=self.randomprojector, already_selected=[], N=int(total_embeddings.shape[0]*float(args.coreset_sampling_ratio))) 352 | self.embedding_coreset = total_embeddings[selected_idx] 353 | 354 | print('initial embedding size : ', total_embeddings.shape) 355 | print('final embedding size : ', self.embedding_coreset.shape) 356 | with open(os.path.join(self.embedding_dir_path, 'embedding.pickle'), 'wb') as f: 357 | pickle.dump(self.embedding_coreset, f) 358 | gc.collect() 359 | 360 | def test_step(self, batch, batch_idx): # Nearest Neighbour Search 361 | 362 | x, label, file_name, x_type = batch 363 | features = self(x) 364 | embeddings = [] 365 | for feature in features: 366 | m = torch.nn.AvgPool2d(3, 1, 1) 367 | embeddings.append(m(feature)) 368 | embedding_ = embedding_concat(embeddings[0], embeddings[1]) 369 | embedding_test = np.array(reshape_embedding(np.array(embedding_))) 370 | 371 | #reshape_embedding for libtorch 372 | #embedding_.squeeze_() 373 | #embedding_ = embedding_.reshape(embedding_.size(0),embedding_.size(1) * embedding_.size(2)) 374 | #embedding_test = embedding_.permute(1,0) 375 | ###################################### 376 | 377 | # NN 378 | knn = KNN(torch.from_numpy(self.embedding_coreset).cuda(),k=9) 379 | score_patches = knn(torch.from_numpy(embedding_test).cuda())[0].cpu().detach().numpy() 380 | self.img_path_list.extend(file_name) 381 | # support multi input size 382 | block_size = int(np.sqrt(len(score_patches))) 383 | anomaly_map = score_patches[:, 0].reshape((block_size, block_size)) 384 | self.all_scores.append(anomaly_map) 385 | self.image_batch_list.append(x) 386 | self.x_type_list.append(x_type) 387 | self.y_true.append(label.cpu().numpy()[0]) 388 | 389 | 390 | 391 | def Find_Optimal_Cutoff(self,target,predicted): 392 | fpr,tpr,threshold = roc_curve(target,predicted,pos_label=1) 393 | i = np.arange(len(tpr)) 394 | roc = pd.DataFrame({'tf': pd.Series(tpr - (1 - fpr), index=i), 'threshold': pd.Series(threshold, index=i)}) 395 | roc_t = roc.iloc[(roc.tf - 0).abs().argsort()[:1]] 396 | return list(roc_t['threshold']), threshold 397 | ''' 398 | plt.plot(fpr, tpr) 399 | plt.plot([0, 1], [0, 1], '--', color='black') 400 | plt.title('ROC Curve') 401 | plt.xlabel('False Positive Rate') 402 | plt.ylabel('True Positive Rate') 403 | plt.show() 404 | ''' 405 | 406 | def analyze_data(self): 407 | score_pathces = np.array(self.all_scores) 408 | for i,val in enumerate(score_pathces): 409 | self.all_scores_mean_norm.append(np.mean(val)) 410 | 411 | min_score = np.min(score_pathces) 412 | max_score = np.max(score_pathces) 413 | scores = (score_pathces - min_score) / (max_score - min_score) 414 | for i,heatmap in enumerate(scores): 415 | anomaly_map_resized = cv2.resize(heatmap, (args.input_size, args.input_size)) 416 | max_ = np.max(heatmap) 417 | min_ = np.min(heatmap) 418 | 419 | anomaly_map_resized_blur = gaussian_filter(anomaly_map_resized, sigma=4) 420 | anomaly_map_resized_blur[0][0] = 1. 421 | 422 | 423 | 424 | # save images 425 | x = self.image_batch_list[i] 426 | x = self.inv_normalize(x) 427 | input_x = cv2.cvtColor(x.permute(0, 2, 3, 1).cpu().numpy()[0] * 255, cv2.COLOR_BGR2RGB) 428 | if anomaly_map_resized_blur.shape != input_x.shape: 429 | anomaly_map_resized_blur = cv2.resize(anomaly_map_resized_blur, (input_x.shape[0], input_x.shape[1])) 430 | 431 | if args.anomal_threshold != 0: 432 | anomaly_threshold_index = anomaly_map_resized_blur[anomaly_map_resized_blur > args.anomal_threshold] 433 | anomaly_map_resized_blur[anomaly_map_resized_blur < args.anomal_threshold] = 0 434 | anomaly_threshold_area = anomaly_threshold_index.size 435 | anomaly_threshold_area = anomaly_threshold_area / float(anomaly_map_resized_blur.size) * 100. 436 | self.all_scores_mean_norm[i] = anomaly_threshold_area 437 | 438 | # anomaly map on image 439 | heatmap = cvt2heatmap(anomaly_map_resized_blur * 255) 440 | hm_on_img = heatmap_on_image(heatmap, input_x) 441 | 442 | # save images 443 | cv2.imwrite(os.path.join(self.sample_path, f'{self.x_type_list[i]}_{self.img_path_list[i]}.jpg'), input_x) 444 | cv2.imwrite(os.path.join(self.sample_path, f'{self.x_type_list[i]}_{self.img_path_list[i]}_amap.jpg'), heatmap) 445 | cv2.imwrite(os.path.join(self.sample_path, f'{self.x_type_list[i]}_{self.img_path_list[i]}_amap_on_img.jpg'), hm_on_img) 446 | 447 | 448 | def test_epoch_end(self, outputs): 449 | self.analyze_data() 450 | 451 | best_th, threshold = self.Find_Optimal_Cutoff(self.y_true, self.all_scores_mean_norm) 452 | print(f'\nbest threshold={best_th}') 453 | ng_index = np.where(np.array(self.y_true) == 1) 454 | if len(ng_index[0]) == 0: 455 | ng_index = len(self.y_true) 456 | else: 457 | ng_index = ng_index[0][0] 458 | fig = plt.figure() 459 | sns.histplot(self.all_scores_mean_norm[:ng_index], kde=True, color="blue", label="normal") 460 | sns.histplot(self.all_scores_mean_norm[ng_index:], kde=True, color="red", label="abnormal") 461 | fig.legend(labels=['normal', 'abnormal']) 462 | plt.xlabel("Anomaly score") 463 | plt.ylabel("Count") 464 | plt.savefig('Anomaly_score_histplot.jpg') 465 | 466 | 467 | def get_args(): 468 | parser = argparse.ArgumentParser(description='ANOMALYDETECTION') 469 | parser.add_argument('--phase', choices=['train','test'], default='train') 470 | parser.add_argument('--dataset_path', default=r'/home/changwoo/hdd/datasets/mvtec_anomaly_detection2') # 'D:\Dataset\mvtec_anomaly_detection')# 471 | parser.add_argument('--category', default='bottle') 472 | parser.add_argument('--num_epochs', default=1) 473 | parser.add_argument('--batch_size', default=1) 474 | parser.add_argument('--load_size', default=256) # 256 475 | parser.add_argument('--input_size', default=224) 476 | parser.add_argument('--coreset_sampling_ratio', default=0.001) 477 | parser.add_argument('--project_root_path', default=r'D:/deeplearning/PatchCore_anomaly_detection/') # 'D:\Project_Train_Results\mvtec_anomaly_detection\210624\test') # 478 | parser.add_argument('--save_src_code', default=True) 479 | parser.add_argument('--save_anomaly_map', default=True) 480 | parser.add_argument('--n_neighbors', type=int, default=9) 481 | parser.add_argument('--anomal_threshold', type=float, default=0) 482 | args = parser.parse_args() 483 | return args 484 | 485 | if __name__ == '__main__': 486 | 487 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 488 | args = get_args() 489 | 490 | trainer = pl.Trainer.from_argparse_args(args, default_root_dir=os.path.join(args.project_root_path, args.category), max_epochs=args.num_epochs, gpus=1) #, check_val_every_n_epoch=args.val_freq, num_sanity_val_steps=0) # ,fast_dev_run=True) 491 | model = STPM(hparams=args) 492 | if args.phase == 'train': 493 | trainer.fit(model) 494 | #trainer.test(model) 495 | elif args.phase == 'test': 496 | trainer.test(model) 497 | 498 | --------------------------------------------------------------------------------