diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56936a0b312bcda2f2a0ab7b64baf3ad0d8b27be --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2021 Min Seok (Karel) Lee + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/__pycache__/config.cpython-39.pyc b/__pycache__/config.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f37316c85ac7ad729fc6a460b7bd7ed41c91c2 Binary files /dev/null and b/__pycache__/config.cpython-39.pyc differ diff --git a/__pycache__/dataloader.cpython-39.pyc b/__pycache__/dataloader.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..872150414de7e94c6c2c05bf95a478eec1cc928e Binary files /dev/null and b/__pycache__/dataloader.cpython-39.pyc differ diff --git a/__pycache__/inference.cpython-39.pyc b/__pycache__/inference.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..178db507c1c6e7a40d448db4bb61b2e23bb1ce64 Binary files /dev/null and b/__pycache__/inference.cpython-39.pyc differ diff --git a/__pycache__/trainer.cpython-39.pyc b/__pycache__/trainer.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51d2e24c6869832ff58e1bfda133d8a1489a59fe Binary files /dev/null and b/__pycache__/trainer.cpython-39.pyc differ diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..c063f26f0c7800986405d5dd369ec7b23c458e77 --- /dev/null +++ b/app.py @@ -0,0 +1,207 @@ +import streamlit as st +import os +import subprocess +from PIL import Image, ImageOps +import torch +from diffusers import StableDiffusionInpaintPipeline +import transformers +import matplotlib.pyplot as plt +import matplotlib.image as mpimg +import cv2 +import diffusers +import accelerate +import warnings +import numpy as np +import os +import shutil +warnings.filterwarnings("ignore") + +st.title('Background Generation') + +st.write('This app generates new backgrounds for images.') + +# set environment variable for dll +os.environ['KMP_DUPLICATE_LIB_OK']='True' + +@st.cache_data +def mode(width, height): + output_width = np.floor_divide(width, 8) * 8 + output_height = np.floor_divide(height, 8) * 8 + return output_width, output_height + +def get_prompt(): + prompt = st.text_input('Enter your prompt here:', placeholder="Imagine our perfume bottle amidst a lush garden, surrounded by blooming flowers and vibrant colors.") + return prompt + +def get_negative_prompt(): + negative_prompt = st.text_input('Enter your negative prompt here:', placeholder="low quality, out of frame, watermark.. etc.") + return negative_prompt + +def get_user_input(): + st.subheader("Upload an image file, Press Clean Background Button.") + uploaded_file = st.file_uploader("Upload a JPG image file", type=["jpg", "jpeg"]) + + if uploaded_file is not None: + user_file_path = os.path.join("data/custom_dataset/", uploaded_file.name) + + # Open the uploaded image + uploaded_image = Image.open(uploaded_file) + + # Check if the width is larger than 640 + if uploaded_image.width > 640: + # Calculate the proportional height based on the desired width of 640 pixels + aspect_ratio = uploaded_image.width / uploaded_image.height + resized_height = int(640 / aspect_ratio) + # Resize the image to a width of 640 pixels and proportional height + resized_image = uploaded_image.resize((640, resized_height)) + else: + resized_image = uploaded_image + + return resized_image, user_file_path + + return None, None + + +def clean_files(directory): + files = os.listdir(directory) + for file in files: + file_path = os.path.join(directory, file) + if os.path.isfile(file_path): + os.remove(file_path) + +uploaded_file, user_file_path = get_user_input() +button_1 = st.button("Clean Background") + +button_1_clicked = False # Variable to track button state + +def run_subprocess(): + mask_created = False + command = "python main.py inference --dataset custom_dataset/ --arch 7 --img_size 640 --save_map True" + subprocess.run(command, shell=True) + mask_created = True + + +# Perform the necessary actions when the "Clean Background" button is clicked +st.write(button_1) + +# Log data for analyzing the app later. +def log(copy = False): + custom_dataset_directory = "data/custom_dataset/" + processed_directory = "data/processed" + for filename in os.listdir(custom_dataset_directory): + file_path = os.path.join(custom_dataset_directory, filename) + + if copy == True: + shutil.copy(file_path, processed_directory) # Copy files + else: + shutil.move(file_path, processed_directory) # Move files + + +def load_images(): + x = user_file_path.split('/')[-1] + uploaded_file_name = os.path.basename(user_file_path) + image_path = os.path.join("data/custom_dataset/", x) + dif_image = Image.open(image_path) + + mask_path = os.path.join("mask/custom_dataset/", x.replace('.jpg', '.png')) + png_image = Image.open(mask_path) + inverted_image = ImageOps.invert(png_image) + return dif_image , inverted_image + +if button_1: + button_1_clicked = True + # Move items from data/custom_dataset/ to data/processed + log( copy= True) + clean_files("data/custom_dataset/") + if uploaded_file is not None: + uploaded_file.save(user_file_path) + run_subprocess() + st.success("Background cleaned.") + log(copy = True) + dif_image , inverted_image = load_images() + + +st.subheader("Text your prompt and choose parameters, then press Run Model button") + +# Create a two-column layout +col1, col2 = st.columns(2) + +# Get user input for prompts +with col1: + input_prompt = st.text_area('Enter Prompt', height=80) +with col2: + input_negative_prompt = st.text_area('Enter Negative Prompt', height=80) + +num_inference_steps = st.slider('Number of Inference Steps:', min_value=5, max_value=50, value=10) +num_images_per_prompt = st.slider('Image Count to be Produced:', min_value=1, max_value=2, value=1) + +# use seed with torch generator +torch.manual_seed(0) +# seed +seed = st.slider('Seed:', min_value=0, max_value=100, value=1) +generator = [torch.Generator(device="cuda").manual_seed(seed) for i in range(num_images_per_prompt)] + +#generator = torch.Generator(device="cuda").manual_seed(0) +run_model_button = st.button("Run Model") + +@st.cache_resource +def initialize_pipe(): + pipe = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting", + revision="fp16", + torch_dtype=torch.float16, + safety_checker = None, + requires_safety_checker = False).to("cuda") + + pipe.safety_checker = None + pipe.requires_safety_checker = False + return pipe + +def image_resize(dif_image): + output_width, output_height = mode(dif_image.width, dif_image.height) + while output_height > 800: + output_height = output_height // 1.5 + output_width = output_width // 1.5 + output_width, output_height = mode(output_width, output_height) + return output_width, output_height + + +def show_output(x5): + if len(x5) == 1: + col1, col2 = st.columns(2) + with col1 : + st.image(inverted_image, width=256, caption='Generated Mask', use_column_width=False) + with col2: + st.image(x5[0], width=256, caption='Generated Image', use_column_width=False) + + elif len(x5) == 2: + col1, col2, col3 = st.columns(3) + with col1 : + col1.image(inverted_image, width=256, caption='Generated Mask', use_column_width=False) + with col2 : + col2.image(x5[0], width=256, caption='Gener ted Image', use_column_width=False) + with col3 : + col3.image(x5[1], width=256, caption='Generated Image-2', use_column_width=False) + +# Check if the button is clicked and all inputs are provided +if run_model_button == True and input_prompt is not None : + st.write("Running the model...") + dif_image , inverted_image = load_images() + output_width, output_height = image_resize(dif_image) + base_prompt = "high resolution, high quality, use mask. Do not distort the shape of the object. make the object stand out, show it clearly and vividly, preserving the shape of the object, use the mask" + prompt = input_prompt + " " + base_prompt + + st.write("Pipe working with {0} inference steps and {1} image will be created for prompt".format(num_inference_steps, num_images_per_prompt)) + + pipe = initialize_pipe() + + output_height = 128 + output_width = 128 + + x5 = pipe(image=dif_image, mask_image=inverted_image, num_inference_steps=num_inference_steps, generator= generator, + num_images_per_prompt=num_images_per_prompt, prompt=prompt, negative_prompt=input_negative_prompt, + height=output_height, width=output_width).images + + show_output(x5) + torch.cuda.empty_cache() +else: + st.write("Please provide prompt and click the 'Run Model' button to proceed.") \ No newline at end of file diff --git a/config.py b/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd44c31bcfa39ec576d6c3720c63e4f7d7ac87e --- /dev/null +++ b/config.py @@ -0,0 +1,47 @@ +import argparse + +def getConfig(): + parser = argparse.ArgumentParser() + parser.add_argument('action', type=str, default='train', help='Model Training or Testing options') + parser.add_argument('--exp_num', default=0, type=str, help='experiment_number') + parser.add_argument('--dataset', type=str, default='DUTS', help='DUTS') + parser.add_argument('--data_path', type=str, default='data/') + + # Model parameter settings + parser.add_argument('--arch', type=str, default='0', help='Backbone Architecture') + parser.add_argument('--channels', type=list, default=[24, 40, 112, 320]) + parser.add_argument('--RFB_aggregated_channel', type=int, nargs='*', default=[32, 64, 128]) + parser.add_argument('--frequency_radius', type=int, default=16, help='Frequency radius r in FFT') + parser.add_argument('--denoise', type=float, default=0.93, help='Denoising background ratio') + parser.add_argument('--gamma', type=float, default=0.1, help='Confidence ratio') + + # Training parameter settings + parser.add_argument('--img_size', type=int, default=320) + parser.add_argument('--batch_size', type=int, default=32) + parser.add_argument('--epochs', type=int, default=100) + parser.add_argument('--lr', type=float, default=5e-5) + parser.add_argument('--optimizer', type=str, default='Adam') + parser.add_argument('--weight_decay', type=float, default=1e-4) + parser.add_argument('--criterion', type=str, default='API', help='API or bce') + parser.add_argument('--scheduler', type=str, default='Reduce', help='Reduce or Step') + parser.add_argument('--aug_ver', type=int, default=2, help='1=Normal, 2=Hard') + parser.add_argument('--lr_factor', type=float, default=0.1) + parser.add_argument('--clipping', type=float, default=2, help='Gradient clipping') + parser.add_argument('--patience', type=int, default=5, help="Scheduler ReduceLROnPlateau's parameter & Early Stopping(+5)") + parser.add_argument('--model_path', type=str, default='results/') + parser.add_argument('--seed', type=int, default=42) + parser.add_argument('--save_map', type=bool, default=None, help='Save prediction map') + + + # Hardware settings + parser.add_argument('--multi_gpu', type=bool, default=True) + parser.add_argument('--num_workers', type=int, default=4) + cfg = parser.parse_args() + + return cfg + + +if __name__ == '__main__': + cfg = getConfig() + cfg = vars(cfg) + print(cfg) \ No newline at end of file diff --git a/data/custom_dataset/images.jpg b/data/custom_dataset/images.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bdf57e67415a28e4bcafe849132e47b76cc0da1e Binary files /dev/null and b/data/custom_dataset/images.jpg differ diff --git a/data/processed/110000026240767.jpg b/data/processed/110000026240767.jpg new file mode 100644 index 0000000000000000000000000000000000000000..21d9bd656aab997c6381673fad08e33255caf61e Binary files /dev/null and b/data/processed/110000026240767.jpg differ diff --git a/data/processed/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.jpg b/data/processed/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.jpg new file mode 100644 index 0000000000000000000000000000000000000000..abca80c909849db74fffad844d08ef64192e1a52 Binary files /dev/null and b/data/processed/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.jpg differ diff --git a/data/processed/images (1).jpg b/data/processed/images (1).jpg new file mode 100644 index 0000000000000000000000000000000000000000..76a37c7ab1bdc03523c71825fb3b903dae605731 Binary files /dev/null and b/data/processed/images (1).jpg differ diff --git a/data/processed/images.jpg b/data/processed/images.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bdf57e67415a28e4bcafe849132e47b76cc0da1e Binary files /dev/null and b/data/processed/images.jpg differ diff --git a/data/processed/indir (1).jpg b/data/processed/indir (1).jpg new file mode 100644 index 0000000000000000000000000000000000000000..0056d3ec8f7e6030dc9f3a1c0716375a1e186c17 Binary files /dev/null and b/data/processed/indir (1).jpg differ diff --git a/data/processed/photo-1541643600914-78b084683601.jpg b/data/processed/photo-1541643600914-78b084683601.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0f0801cde5fc2ac634722a871db9d6d02196bcf2 Binary files /dev/null and b/data/processed/photo-1541643600914-78b084683601.jpg differ diff --git a/data/processed/smart-collection-512-narciso-rodriguez-black-600x800-0.jpg b/data/processed/smart-collection-512-narciso-rodriguez-black-600x800-0.jpg new file mode 100644 index 0000000000000000000000000000000000000000..44683fc7c7a644ee1b784f67e247ccd34535792f Binary files /dev/null and b/data/processed/smart-collection-512-narciso-rodriguez-black-600x800-0.jpg differ diff --git a/dataloader.py b/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..3dff0fc04670bf08c2fd5c824e51c294e1e9e4ba --- /dev/null +++ b/dataloader.py @@ -0,0 +1,147 @@ +import cv2 +import glob +import torch +import numpy as np +import albumentations as albu +from pathlib import Path +from albumentations.pytorch.transforms import ToTensorV2 +from torch.utils.data import Dataset, DataLoader +from sklearn.model_selection import train_test_split + + +class DatasetGenerate(Dataset): + def __init__(self, img_folder, gt_folder, edge_folder, phase: str = 'train', transform=None, seed=None): + self.images = sorted(glob.glob(img_folder + '/*')) + self.gts = sorted(glob.glob(gt_folder + '/*')) + self.edges = sorted(glob.glob(edge_folder + '/*')) + self.transform = transform + + train_images, val_images, train_gts, val_gts, train_edges, val_edges = train_test_split(self.images, self.gts, + self.edges, + test_size=0.05, + random_state=seed) + if phase == 'train': + self.images = train_images + self.gts = train_gts + self.edges = train_edges + elif phase == 'val': + self.images = val_images + self.gts = val_gts + self.edges = val_edges + else: # Testset + pass + + def __getitem__(self, idx): + image = cv2.imread(self.images[idx]) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + mask = cv2.imread(self.gts[idx]) + mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + edge = cv2.imread(self.edges[idx]) + edge = cv2.cvtColor(edge, cv2.COLOR_BGR2GRAY) + + if self.transform is not None: + augmented = self.transform(image=image, masks=[mask, edge]) + image = augmented['image'] + mask = np.expand_dims(augmented['masks'][0], axis=0) # (1, H, W) + mask = mask / 255.0 + edge = np.expand_dims(augmented['masks'][1], axis=0) # (1, H, W) + edge = edge / 255.0 + + return image, mask, edge + + def __len__(self): + return len(self.images) + + +class Test_DatasetGenerate(Dataset): + def __init__(self, img_folder, gt_folder=None, transform=None): + self.images = sorted(glob.glob(img_folder + '/*')) + self.gts = sorted(glob.glob(gt_folder + '/*')) if gt_folder is not None else None + self.transform = transform + + def __getitem__(self, idx): + image_name = Path(self.images[idx]).stem + image = cv2.imread(self.images[idx]) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + original_size = image.shape[:2] + + if self.transform is not None: + augmented = self.transform(image=image) + image = augmented['image'] + + if self.gts is not None: + return image, self.gts[idx], original_size, image_name + else: + return image, original_size, image_name + + def __len__(self): + return len(self.images) + + +def get_loader(img_folder, gt_folder, edge_folder, phase: str, batch_size, shuffle, + num_workers, transform, seed=None): + if phase == 'test': + dataset = Test_DatasetGenerate(img_folder, gt_folder, transform) + data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers) + else: + dataset = DatasetGenerate(img_folder, gt_folder, edge_folder, phase, transform, seed) + data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, + drop_last=True) + + print(f'{phase} length : {len(dataset)}') + + return data_loader + + +def get_train_augmentation(img_size, ver): + if ver == 1: + transforms = albu.Compose([ + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + if ver == 2: + transforms = albu.Compose([ + albu.OneOf([ + albu.HorizontalFlip(), + albu.VerticalFlip(), + albu.RandomRotate90() + ], p=0.5), + albu.OneOf([ + albu.RandomContrast(), + albu.RandomGamma(), + albu.RandomBrightness(), + ], p=0.5), + albu.OneOf([ + albu.MotionBlur(blur_limit=5), + albu.MedianBlur(blur_limit=5), + albu.GaussianBlur(blur_limit=5), + albu.GaussNoise(var_limit=(5.0, 20.0)), + ], p=0.5), + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + return transforms + + +def get_test_augmentation(img_size): + transforms = albu.Compose([ + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + return transforms + + +def gt_to_tensor(gt): + gt = cv2.imread(gt) + gt = cv2.cvtColor(gt, cv2.COLOR_BGR2GRAY) / 255.0 + gt = np.where(gt > 0.5, 1.0, 0.0) + gt = torch.tensor(gt, device='cuda', dtype=torch.float32) + gt = gt.unsqueeze(0).unsqueeze(1) + + return gt diff --git a/demo_run.sh b/demo_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..19444cbfa0b2cae0b7d622d86cf79cac96c21ec2 --- /dev/null +++ b/demo_run.sh @@ -0,0 +1,11 @@ +#TRACER +#├── data +#│ ├── custom_dataset +#│ │ ├── sample_image1.png +#│ │ ├── sample_image2.png +# . +# . +# . + +# For testing TRACER with pre-trained model (e.g.) +python main.py inference --dataset custom_dataset/ --arch 7 --img_size 640 --save_map True \ No newline at end of file diff --git a/edge_generator.py b/edge_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..f41340363e31e00ceb78454b8c2a4e81e30e1cba --- /dev/null +++ b/edge_generator.py @@ -0,0 +1,38 @@ +""" +Author: Min Seok Lee and Wooseok Shin +TRACER: Extreme Attention Guided Salient Object Tracing Network +git repo: https://github.com/Karel911/TRACER +""" +import os +import cv2 +import numpy as np +from tqdm import tqdm + +# Append custom datasets below list +dataset_list = ['DUTS', 'DUT-O', 'HKU-IS', 'ECSSD', 'PASCAL-S'] + + +def edge_generator(dataset): + if dataset == 'DUTS': + mask_path = os.path.join('data/', dataset, 'Train/masks/') + else: + mask_path = os.path.join('data/', dataset, 'Test/masks/') + save_path = os.path.join('data/', dataset, 'Train/edges/') + os.makedirs(save_path, exist_ok=True) + mask_list = os.listdir(mask_path) + + for i, img_name in tqdm(enumerate(mask_list)): + mask = cv2.imread(mask_path + img_name) + mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + mask = np.int64(mask > 128) + + [gy, gx] = np.gradient(mask) + tmp_edge = gy * gy + gx * gx + tmp_edge[tmp_edge != 0] = 1 + bound = np.uint8(tmp_edge * 255) + cv2.imwrite(os.path.join(save_path, f'{img_name}'), bound) + + +if __name__ == '__main__': + for dataset in dataset_list: + edge_generator(dataset) \ No newline at end of file diff --git a/img/Poster.png b/img/Poster.png new file mode 100644 index 0000000000000000000000000000000000000000..aba7bfaf617d97f2333afbb1ab52cad602f79d31 Binary files /dev/null and b/img/Poster.png differ diff --git a/inference.py b/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5bcdab644680b2506990f88be199a4c0b240fd --- /dev/null +++ b/inference.py @@ -0,0 +1,89 @@ +""" +author: Min Seok Lee and Wooseok Shin +""" +import os +import cv2 +import time +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.transforms import transforms +from tqdm import tqdm +from dataloader import get_test_augmentation, get_loader +from model.TRACER import TRACER +from util.utils import load_pretrained + + +class Inference(): + def __init__(self, args, save_path): + super(Inference, self).__init__() + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.test_transform = get_test_augmentation(img_size=args.img_size) + self.args = args + self.save_path = save_path + + # Network + self.model = TRACER(args).to(self.device) + if args.multi_gpu: + self.model = nn.DataParallel(self.model).to(self.device) + + path = load_pretrained(f'TE-{args.arch}') + self.model.load_state_dict(path) + print('###### pre-trained Model restored #####') + + te_img_folder = os.path.join(args.data_path, args.dataset) + te_gt_folder = None + + self.test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, phase='test', + batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, transform=self.test_transform) + + if args.save_map is not None: + os.makedirs(os.path.join('mask', self.args.dataset), exist_ok=True) + os.makedirs(os.path.join('object', self.args.dataset), exist_ok=True) + + def test(self): + self.model.eval() + t = time.time() + + with torch.no_grad(): + for i, (images, original_size, image_name) in enumerate(tqdm(self.test_loader)): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + + outputs, edge_mask, ds_map = self.model(images) + H, W = original_size + + for i in range(images.size(0)): + h, w = H[i].item(), W[i].item() + output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear') + + # Save prediction map + if self.args.save_map is not None: + output = (output.squeeze().detach().cpu().numpy() * 255.0).astype(np.uint8) + + salient_object = self.post_processing(images[i], output, h, w) + cv2.imwrite(os.path.join('mask', self.args.dataset, image_name[i] + '.png'), output) + cv2.imwrite(os.path.join('object', self.args.dataset, image_name[i] + '.png'), salient_object) + + print(f'time: {time.time() - t:.3f}s') + + def post_processing(self, original_image, output_image, height, width, threshold=200): + invTrans = transforms.Compose([transforms.Normalize(mean=[0., 0., 0.], + std=[1 / 0.229, 1 / 0.224, 1 / 0.225]), + transforms.Normalize(mean=[-0.485, -0.456, -0.406], + std=[1., 1., 1.]), + ]) + original_image = invTrans(original_image) + + original_image = F.interpolate(original_image.unsqueeze(0), size=(height, width), mode='bilinear') + original_image = (original_image.squeeze().permute(1, 2, 0).detach().cpu().numpy() * 255.0).astype(np.uint8) + + rgba_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2BGRA) + output_rbga_image = cv2.cvtColor(output_image, cv2.COLOR_BGR2BGRA) + + output_rbga_image[:, :, 3] = output_image # Extract edges + edge_y, edge_x, _ = np.where(output_rbga_image <= threshold) # Edge coordinates + + rgba_image[edge_y, edge_x, 3] = 0 + return cv2.cvtColor(rgba_image, cv2.COLOR_RGBA2BGRA) diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..6c3b6d26c5caba7e7492da7403dfd0a3175841d9 --- /dev/null +++ b/main.py @@ -0,0 +1,55 @@ +import os +import pprint +import random +import warnings +import torch +import numpy as np +from trainer import Trainer, Tester +from inference import Inference + +from config import getConfig +warnings.filterwarnings('ignore') +args = getConfig() + + +def main(args): + print('<---- Training Params ---->') + pprint.pprint(args) + + # Random Seed + seed = args.seed + os.environ['PYTHONHASHSEED'] = str(seed) + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + torch.cuda.manual_seed_all(seed) # if use multi-GPU + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + if args.action == 'train': + save_path = os.path.join(args.model_path, args.dataset, f'TE{args.arch}_{str(args.exp_num)}') + + # Create model directory + os.makedirs(save_path, exist_ok=True) + Trainer(args, save_path) + + elif args.action == 'test': + save_path = os.path.join(args.model_path, args.dataset, f'TE{args.arch}_{str(args.exp_num)}') + datasets = ['DUTS', 'DUT-O', 'HKU-IS', 'ECSSD', 'PASCAL-S'] + + for dataset in datasets: + args.dataset = dataset + test_loss, test_mae, test_maxf, test_avgf, test_s_m = Tester(args, save_path).test() + + print(f'Test Loss:{test_loss:.3f} | MAX_F:{test_maxf:.4f} ' + f'| AVG_F:{test_avgf:.4f} | MAE:{test_mae:.4f} | S_Measure:{test_s_m:.4f}') + else: + save_path = os.path.join(args.model_path, args.dataset, f'TE{args.arch}_{str(args.exp_num)}') + + print('<----- Initializing inference mode ----->') + Inference(args, save_path).test() + + +if __name__ == '__main__': + main(args) \ No newline at end of file diff --git a/mask/custom_dataset/110000026240767.png b/mask/custom_dataset/110000026240767.png new file mode 100644 index 0000000000000000000000000000000000000000..2ab6f057f826406f5c8d4d398d6a16d0a54e3370 Binary files /dev/null and b/mask/custom_dataset/110000026240767.png differ diff --git a/mask/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png b/mask/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png new file mode 100644 index 0000000000000000000000000000000000000000..cf7f2057b70a6455bceb453058af9650f627b9ca Binary files /dev/null and b/mask/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png differ diff --git a/mask/custom_dataset/TOMBUL.png b/mask/custom_dataset/TOMBUL.png new file mode 100644 index 0000000000000000000000000000000000000000..cfe227accc534e25df02715f9618ef6ca5052707 Binary files /dev/null and b/mask/custom_dataset/TOMBUL.png differ diff --git a/mask/custom_dataset/images (1).png b/mask/custom_dataset/images (1).png new file mode 100644 index 0000000000000000000000000000000000000000..29503970872e3c63fa18534e593406b7fb43487c Binary files /dev/null and b/mask/custom_dataset/images (1).png differ diff --git a/mask/custom_dataset/images.png b/mask/custom_dataset/images.png new file mode 100644 index 0000000000000000000000000000000000000000..3ebd46c367401dd35d76ab8a37b39545aa5b945a Binary files /dev/null and b/mask/custom_dataset/images.png differ diff --git a/mask/custom_dataset/indir (1).png b/mask/custom_dataset/indir (1).png new file mode 100644 index 0000000000000000000000000000000000000000..360ead12d62539fa67eae52dd5440686f7a90d48 Binary files /dev/null and b/mask/custom_dataset/indir (1).png differ diff --git a/mask/custom_dataset/indir.png b/mask/custom_dataset/indir.png new file mode 100644 index 0000000000000000000000000000000000000000..0db8c20628d8556636c3ebfa5861db90552a1cbd Binary files /dev/null and b/mask/custom_dataset/indir.png differ diff --git a/mask/custom_dataset/photo-1541643600914-78b084683601.png b/mask/custom_dataset/photo-1541643600914-78b084683601.png new file mode 100644 index 0000000000000000000000000000000000000000..9a28cd0e580de016b99d5f02ac33251741e0eaa2 Binary files /dev/null and b/mask/custom_dataset/photo-1541643600914-78b084683601.png differ diff --git a/model/EfficientNet.py b/model/EfficientNet.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3416b5ee1cbfeb79ae05155949623b0ae161d4 --- /dev/null +++ b/model/EfficientNet.py @@ -0,0 +1,356 @@ +""" +Original author: lukemelas (github username) +Github repo: https://github.com/lukemelas/EfficientNet-PyTorch +With adjustments and added comments by workingcoder (github username). + +Reimplemented: Min Seok Lee and Wooseok Shin +""" + + + +import torch +from torch import nn +from torch.nn import functional as F +from util.effi_utils import ( + get_model_shape, + round_filters, + round_repeats, + drop_connect, + get_same_padding_conv2d, + get_model_params, + efficientnet_params, + load_pretrained_weights, + Swish, + MemoryEfficientSwish, + calculate_output_image_size +) +from modules.att_modules import Frequency_Edge_Module +from config import getConfig + +cfg = getConfig() + +VALID_MODELS = ( + 'efficientnet-b0', 'efficientnet-b1', 'efficientnet-b2', 'efficientnet-b3', + 'efficientnet-b4', 'efficientnet-b5', 'efficientnet-b6', 'efficientnet-b7', + 'efficientnet-b8', + + # Support the construction of 'efficientnet-l2' without pretrained weights + 'efficientnet-l2' +) + + +class MBConvBlock(nn.Module): + """Mobile Inverted Residual Bottleneck Block. + + Args: + block_args (namedtuple): BlockArgs, defined in utils.py. + global_params (namedtuple): GlobalParam, defined in utils.py. + image_size (tuple or list): [image_height, image_width]. + + References: + [1] https://arxiv.org/abs/1704.04861 (MobileNet v1) + [2] https://arxiv.org/abs/1801.04381 (MobileNet v2) + [3] https://arxiv.org/abs/1905.02244 (MobileNet v3) + """ + + def __init__(self, block_args, global_params, image_size=None): + super().__init__() + self._block_args = block_args + self._bn_mom = 1 - global_params.batch_norm_momentum # pytorch's difference from tensorflow + self._bn_eps = global_params.batch_norm_epsilon + self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1) + self.id_skip = block_args.id_skip # whether to use skip connection and drop connect + + # Expansion phase (Inverted Bottleneck) + inp = self._block_args.input_filters # number of input channels + oup = self._block_args.input_filters * self._block_args.expand_ratio # number of output channels + if self._block_args.expand_ratio != 1: + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._expand_conv = Conv2d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False) + self._bn0 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps) + # image_size = calculate_output_image_size(image_size, 1) <-- this wouldn't modify image_size + + # Depthwise convolution phase + k = self._block_args.kernel_size + s = self._block_args.stride + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._depthwise_conv = Conv2d( + in_channels=oup, out_channels=oup, groups=oup, # groups makes it depthwise + kernel_size=k, stride=s, bias=False) + self._bn1 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps) + image_size = calculate_output_image_size(image_size, s) + + # Squeeze and Excitation layer, if desired + if self.has_se: + Conv2d = get_same_padding_conv2d(image_size=(1, 1)) + num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio)) + self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1) + self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1) + + # Pointwise convolution phase + final_oup = self._block_args.output_filters + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._project_conv = Conv2d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False) + self._bn2 = nn.BatchNorm2d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps) + self._swish = MemoryEfficientSwish() + + def forward(self, inputs, drop_connect_rate=None): + """MBConvBlock's forward function. + + Args: + inputs (tensor): Input tensor. + drop_connect_rate (bool): Drop connect rate (float, between 0 and 1). + + Returns: + Output of this block after processing. + """ + + # Expansion and Depthwise Convolution + x = inputs + if self._block_args.expand_ratio != 1: + x = self._expand_conv(inputs) + x = self._bn0(x) + x = self._swish(x) + + x = self._depthwise_conv(x) + x = self._bn1(x) + x = self._swish(x) + + # Squeeze and Excitation + if self.has_se: + x_squeezed = F.adaptive_avg_pool2d(x, 1) + x_squeezed = self._se_reduce(x_squeezed) + x_squeezed = self._swish(x_squeezed) + x_squeezed = self._se_expand(x_squeezed) + x = torch.sigmoid(x_squeezed) * x + + # Pointwise Convolution + x = self._project_conv(x) + x = self._bn2(x) + + # Skip connection and drop connect + input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters + if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters: + # The combination of skip connection and drop connect brings about stochastic depth. + if drop_connect_rate: + x = drop_connect(x, p=drop_connect_rate, training=self.training) + x = x + inputs # skip connection + return x + + def set_swish(self, memory_efficient=True): + """Sets swish function as memory efficient (for training) or standard (for export). + + Args: + memory_efficient (bool): Whether to use memory-efficient version of swish. + """ + self._swish = MemoryEfficientSwish() if memory_efficient else Swish() + + +class EfficientNet(nn.Module): + def __init__(self, blocks_args=None, global_params=None): + super().__init__() + assert isinstance(blocks_args, list), 'blocks_args should be a list' + assert len(blocks_args) > 0, 'block args must be greater than 0' + self._global_params = global_params + self._blocks_args = blocks_args + self.block_idx, self.channels = get_model_shape() + self.Frequency_Edge_Module1 = Frequency_Edge_Module(radius=cfg.frequency_radius, + channel=self.channels[0]) + # Batch norm parameters + bn_mom = 1 - self._global_params.batch_norm_momentum + bn_eps = self._global_params.batch_norm_epsilon + + # Get stem static or dynamic convolution depending on image size + image_size = global_params.image_size + Conv2d = get_same_padding_conv2d(image_size=image_size) + + # Stem + in_channels = 3 # rgb + out_channels = round_filters(32, self._global_params) # number of output channels + self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False) + self._bn0 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps) + image_size = calculate_output_image_size(image_size, 2) + + # Build blocks + self._blocks = nn.ModuleList([]) + for block_args in self._blocks_args: + + # Update block input and output filters based on depth multiplier. + block_args = block_args._replace( + input_filters=round_filters(block_args.input_filters, self._global_params), + output_filters=round_filters(block_args.output_filters, self._global_params), + num_repeat=round_repeats(block_args.num_repeat, self._global_params) + ) + + # The first block needs to take care of stride and filter size increase. + self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size)) + image_size = calculate_output_image_size(image_size, block_args.stride) + if block_args.num_repeat > 1: # modify block_args to keep same output size + block_args = block_args._replace(input_filters=block_args.output_filters, stride=1) + for _ in range(block_args.num_repeat - 1): + self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size)) + # image_size = calculate_output_image_size(image_size, block_args.stride) # stride = 1 + + self._swish = MemoryEfficientSwish() + + def set_swish(self, memory_efficient=True): + """Sets swish function as memory efficient (for training) or standard (for export). + + Args: + memory_efficient (bool): Whether to use memory-efficient version of swish. + + """ + self._swish = MemoryEfficientSwish() if memory_efficient else Swish() + for block in self._blocks: + block.set_swish(memory_efficient) + + def extract_endpoints(self, inputs): + endpoints = dict() + + # Stem + x = self._swish(self._bn0(self._conv_stem(inputs))) + prev_x = x + + # Blocks + for idx, block in enumerate(self._blocks): + drop_connect_rate = self._global_params.drop_connect_rate + if drop_connect_rate: + drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate + x = block(x, drop_connect_rate=drop_connect_rate) + if prev_x.size(2) > x.size(2): + endpoints['reduction_{}'.format(len(endpoints) + 1)] = prev_x + prev_x = x + + # Head + x = self._swish(self._bn1(self._conv_head(x))) + endpoints['reduction_{}'.format(len(endpoints) + 1)] = x + + return endpoints + + + def initial_conv(self, inputs): + # Stem + x = self._swish(self._bn0(self._conv_stem(inputs))) + + return x + + + def get_blocks(self, x, H, W): + # Blocks + for idx, block in enumerate(self._blocks): + drop_connect_rate = self._global_params.drop_connect_rate + if drop_connect_rate: + drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate + + x = block(x, drop_connect_rate=drop_connect_rate) + + if idx == self.block_idx[0]: + x, edge = self.Frequency_Edge_Module1(x) + edge = F.interpolate(edge, size=(H, W), mode='bilinear') + x1 = x.clone() + if idx == self.block_idx[1]: + x2 = x.clone() + if idx == self.block_idx[2]: + x3 = x.clone() + if idx == self.block_idx[3]: + x4 = x.clone() + + return (x1, x2, x3, x4), edge + + + @classmethod + def from_name(cls, model_name, in_channels=3, **override_params): + """create an efficientnet model according to name. + + Args: + model_name (str): Name for efficientnet. + in_channels (int): Input data's channel number. + override_params (other key word params): + Params to override model's global_params. + Optional key: + 'width_coefficient', 'depth_coefficient', + 'image_size', 'dropout_rate', + 'num_classes', 'batch_norm_momentum', + 'batch_norm_epsilon', 'drop_connect_rate', + 'depth_divisor', 'min_depth' + + Returns: + An efficientnet model. + """ + cls._check_model_name_is_valid(model_name) + blocks_args, global_params = get_model_params(model_name, override_params) + model = cls(blocks_args, global_params) + model._change_in_channels(in_channels) + return model + + @classmethod + def from_pretrained(cls, model_name, weights_path=None, advprop=False, + in_channels=3, num_classes=1000, **override_params): + """create an efficientnet model according to name. + + Args: + model_name (str): Name for efficientnet. + weights_path (None or str): + str: path to pretrained weights file on the local disk. + None: use pretrained weights downloaded from the Internet. + advprop (bool): + Whether to load pretrained weights + trained with advprop (valid when weights_path is None). + in_channels (int): Input data's channel number. + num_classes (int): + Number of categories for classification. + It controls the output size for final linear layer. + override_params (other key word params): + Params to override model's global_params. + Optional key: + 'width_coefficient', 'depth_coefficient', + 'image_size', 'dropout_rate', + 'batch_norm_momentum', + 'batch_norm_epsilon', 'drop_connect_rate', + 'depth_divisor', 'min_depth' + + Returns: + A pretrained TRACER-EfficientNet model. + """ + model = cls.from_name(model_name, num_classes=num_classes, **override_params) + load_pretrained_weights(model, model_name, weights_path=weights_path, advprop=advprop) + model._change_in_channels(in_channels) + return model + + @classmethod + def get_image_size(cls, model_name): + """Get the input image size for a given efficientnet model. + + Args: + model_name (str): Name for efficientnet. + + Returns: + Input image size (resolution). + """ + cls._check_model_name_is_valid(model_name) + _, _, res, _ = efficientnet_params(model_name) + return res + + @classmethod + def _check_model_name_is_valid(cls, model_name): + """Validates model name. + + Args: + model_name (str): Name for efficientnet. + + Returns: + bool: Is a valid name or not. + """ + if model_name not in VALID_MODELS: + raise ValueError('model_name should be one of: ' + ', '.join(VALID_MODELS)) + + def _change_in_channels(self, in_channels): + """Adjust model's first convolution layer to in_channels, if in_channels not equals 3. + + Args: + in_channels (int): Input data's channel number. + """ + if in_channels != 3: + Conv2d = get_same_padding_conv2d(image_size=self._global_params.image_size) + out_channels = round_filters(32, self._global_params) + self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False) diff --git a/model/TRACER.py b/model/TRACER.py new file mode 100644 index 0000000000000000000000000000000000000000..e0345f70fe09c90fd679111570f8dcea354b9fc5 --- /dev/null +++ b/model/TRACER.py @@ -0,0 +1,58 @@ +""" +author: Min Seok Lee and Wooseok Shin +Github repo: https://github.com/Karel911/TRACER +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from model.EfficientNet import EfficientNet +from util.effi_utils import get_model_shape +from modules.att_modules import RFB_Block, aggregation, ObjectAttention + + +class TRACER(nn.Module): + def __init__(self, cfg): + super().__init__() + self.model = EfficientNet.from_pretrained(f'efficientnet-b{cfg.arch}', advprop=True) + self.block_idx, self.channels = get_model_shape() + + # Receptive Field Blocks + channels = [int(arg_c) for arg_c in cfg.RFB_aggregated_channel] + self.rfb2 = RFB_Block(self.channels[1], channels[0]) + self.rfb3 = RFB_Block(self.channels[2], channels[1]) + self.rfb4 = RFB_Block(self.channels[3], channels[2]) + + # Multi-level aggregation + self.agg = aggregation(channels) + + # Object Attention + self.ObjectAttention2 = ObjectAttention(channel=self.channels[1], kernel_size=3) + self.ObjectAttention1 = ObjectAttention(channel=self.channels[0], kernel_size=3) + + def forward(self, inputs): + B, C, H, W = inputs.size() + + # EfficientNet backbone Encoder + x = self.model.initial_conv(inputs) + features, edge = self.model.get_blocks(x, H, W) + + x3_rfb = self.rfb2(features[1]) + x4_rfb = self.rfb3(features[2]) + x5_rfb = self.rfb4(features[3]) + + D_0 = self.agg(x5_rfb, x4_rfb, x3_rfb) + + ds_map0 = F.interpolate(D_0, scale_factor=8, mode='bilinear') + + D_1 = self.ObjectAttention2(D_0, features[1]) + ds_map1 = F.interpolate(D_1, scale_factor=8, mode='bilinear') + + ds_map = F.interpolate(D_1, scale_factor=2, mode='bilinear') + D_2 = self.ObjectAttention1(ds_map, features[0]) + ds_map2 = F.interpolate(D_2, scale_factor=4, mode='bilinear') + + final_map = (ds_map2 + ds_map1 + ds_map0) / 3 + + return torch.sigmoid(final_map), torch.sigmoid(edge), \ + (torch.sigmoid(ds_map0), torch.sigmoid(ds_map1), torch.sigmoid(ds_map2)) \ No newline at end of file diff --git a/model/__pycache__/EfficientNet.cpython-39.pyc b/model/__pycache__/EfficientNet.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e4abf662f895c0a667471a857c7027db9692e92 Binary files /dev/null and b/model/__pycache__/EfficientNet.cpython-39.pyc differ diff --git a/model/__pycache__/TRACER.cpython-39.pyc b/model/__pycache__/TRACER.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f978155bd8455f458a9b5c60956dafd55624d35 Binary files /dev/null and b/model/__pycache__/TRACER.cpython-39.pyc differ diff --git a/modules/__pycache__/att_modules.cpython-39.pyc b/modules/__pycache__/att_modules.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf99ae8c3df2dfe6d00937c4f1cc8a9be69e59ac Binary files /dev/null and b/modules/__pycache__/att_modules.cpython-39.pyc differ diff --git a/modules/__pycache__/conv_modules.cpython-39.pyc b/modules/__pycache__/conv_modules.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5ecb171343f86ef02a3c5365f60dbb43f27f046 Binary files /dev/null and b/modules/__pycache__/conv_modules.cpython-39.pyc differ diff --git a/modules/att_modules.py b/modules/att_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..83fe2a3abf29d7b05f27a5ed85e0b3c7eecec0ee --- /dev/null +++ b/modules/att_modules.py @@ -0,0 +1,297 @@ +""" +author: Min Seok Lee and Wooseok Shin +""" +import numpy as np +import torch.nn as nn +from torch.fft import fft2, fftshift, ifft2, ifftshift +from util.utils import * +import torch.nn.functional as F +from config import getConfig +from modules.conv_modules import BasicConv2d, DWConv, DWSConv + +cfg = getConfig() + + +class Frequency_Edge_Module(nn.Module): + def __init__(self, radius, channel): + super(Frequency_Edge_Module, self).__init__() + self.radius = radius + self.UAM = UnionAttentionModule(channel, only_channel_tracing=True) + + # DWS + DWConv + self.DWSConv = DWSConv(channel, channel, kernel=3, padding=1, kernels_per_layer=1) + self.DWConv1 = nn.Sequential( + DWConv(channel, channel, kernel=1, padding=0, dilation=1), + BasicConv2d(channel, channel // 4, 1), + ) + self.DWConv2 = nn.Sequential( + DWConv(channel, channel, kernel=3, padding=1, dilation=1), + BasicConv2d(channel, channel // 4, 1), + ) + self.DWConv3 = nn.Sequential( + DWConv(channel, channel, kernel=3, padding=3, dilation=3), + BasicConv2d(channel, channel // 4, 1), + ) + self.DWConv4 = nn.Sequential( + DWConv(channel, channel, kernel=3, padding=5, dilation=5), + BasicConv2d(channel, channel // 4, 1), + ) + self.conv = BasicConv2d(channel, 1, 1) + + def distance(self, i, j, imageSize, r): + dis = np.sqrt((i - imageSize / 2) ** 2 + (j - imageSize / 2) ** 2) + if dis < r: + return 1.0 + else: + return 0 + + def mask_radial(self, img, r): + batch, channels, rows, cols = img.shape + mask = torch.zeros((rows, cols), dtype=torch.float32) + for i in range(rows): + for j in range(cols): + mask[i, j] = self.distance(i, j, imageSize=rows, r=r) + return mask + + def forward(self, x): + """ + Input: + The first encoder block representation: (B, C, H, W) + Returns: + Edge refined representation: X + edge (B, C, H, W) + """ + x_fft = fft2(x, dim=(-2, -1)) + x_fft = fftshift(x_fft) + + # Mask -> low, high separate + mask = self.mask_radial(img=x, r=self.radius).cuda() + high_frequency = x_fft * (1 - mask) + x_fft = ifftshift(high_frequency) + x_fft = ifft2(x_fft, dim=(-2, -1)) + x_H = torch.abs(x_fft) + + x_H, _ = self.UAM.Channel_Tracer(x_H) + edge_maks = self.DWSConv(x_H) + skip = edge_maks.clone() + + edge_maks = torch.cat([self.DWConv1(edge_maks), self.DWConv2(edge_maks), + self.DWConv3(edge_maks), self.DWConv4(edge_maks)], dim=1) + skip + edge = torch.relu(self.conv(edge_maks)) + + x = x + edge # Feature + Masked Edge information + + return x, edge + + +class RFB_Block(nn.Module): + def __init__(self, in_channel, out_channel): + super(RFB_Block, self).__init__() + self.relu = nn.ReLU(True) + self.branch0 = nn.Sequential( + BasicConv2d(in_channel, out_channel, 1), + ) + self.branch1 = nn.Sequential( + BasicConv2d(in_channel, out_channel, 1), + BasicConv2d(out_channel, out_channel, kernel_size=(1, 3), padding=(0, 1)), + BasicConv2d(out_channel, out_channel, kernel_size=(3, 1), padding=(1, 0)), + BasicConv2d(out_channel, out_channel, 3, padding=3, dilation=3) + ) + self.branch2 = nn.Sequential( + BasicConv2d(in_channel, out_channel, 1), + BasicConv2d(out_channel, out_channel, kernel_size=(1, 5), padding=(0, 2)), + BasicConv2d(out_channel, out_channel, kernel_size=(5, 1), padding=(2, 0)), + BasicConv2d(out_channel, out_channel, 3, padding=5, dilation=5) + ) + self.branch3 = nn.Sequential( + BasicConv2d(in_channel, out_channel, 1), + BasicConv2d(out_channel, out_channel, kernel_size=(1, 7), padding=(0, 3)), + BasicConv2d(out_channel, out_channel, kernel_size=(7, 1), padding=(3, 0)), + BasicConv2d(out_channel, out_channel, 3, padding=7, dilation=7) + ) + self.conv_cat = BasicConv2d(4 * out_channel, out_channel, 3, padding=1) + self.conv_res = BasicConv2d(in_channel, out_channel, 1) + + def forward(self, x): + x0 = self.branch0(x) + x1 = self.branch1(x) + x2 = self.branch2(x) + x3 = self.branch3(x) + x_cat = torch.cat((x0, x1, x2, x3), 1) + x_cat = self.conv_cat(x_cat) + + x = self.relu(x_cat + self.conv_res(x)) + return x + + +class GlobalAvgPool(nn.Module): + def __init__(self, flatten=False): + super(GlobalAvgPool, self).__init__() + self.flatten = flatten + + def forward(self, x): + if self.flatten: + in_size = x.size() + return x.view((in_size[0], in_size[1], -1)).mean(dim=2) + else: + return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) + + +class UnionAttentionModule(nn.Module): + def __init__(self, n_channels, only_channel_tracing=False): + super(UnionAttentionModule, self).__init__() + self.GAP = GlobalAvgPool() + self.confidence_ratio = cfg.gamma + self.bn = nn.BatchNorm2d(n_channels) + self.norm = nn.Sequential( + nn.BatchNorm2d(n_channels), + nn.Dropout3d(self.confidence_ratio) + ) + self.channel_q = nn.Conv2d(in_channels=n_channels, out_channels=n_channels, kernel_size=1, stride=1, + padding=0, bias=False) + self.channel_k = nn.Conv2d(in_channels=n_channels, out_channels=n_channels, kernel_size=1, stride=1, + padding=0, bias=False) + self.channel_v = nn.Conv2d(in_channels=n_channels, out_channels=n_channels, kernel_size=1, stride=1, + padding=0, bias=False) + + self.fc = nn.Conv2d(in_channels=n_channels, out_channels=n_channels, kernel_size=1, stride=1, + padding=0, bias=False) + + if only_channel_tracing == False: + self.spatial_q = nn.Conv2d(in_channels=n_channels, out_channels=1, kernel_size=1, stride=1, + padding=0, bias=False) + self.spatial_k = nn.Conv2d(in_channels=n_channels, out_channels=1, kernel_size=1, stride=1, + padding=0, bias=False) + self.spatial_v = nn.Conv2d(in_channels=n_channels, out_channels=1, kernel_size=1, stride=1, + padding=0, bias=False) + self.sigmoid = nn.Sigmoid() + + def masking(self, x, mask): + mask = mask.squeeze(3).squeeze(2) + threshold = torch.quantile(mask, self.confidence_ratio, dim=-1, keepdim=True) + mask[mask <= threshold] = 0.0 + mask = mask.unsqueeze(2).unsqueeze(3) + mask = mask.expand(-1, x.shape[1], x.shape[2], x.shape[3]).contiguous() + masked_x = x * mask + + return masked_x + + def Channel_Tracer(self, x): + avg_pool = self.GAP(x) + x_norm = self.norm(avg_pool) + + q = self.channel_q(x_norm).squeeze(-1) + k = self.channel_k(x_norm).squeeze(-1) + v = self.channel_v(x_norm).squeeze(-1) + + # softmax(Q*K^T) + QK_T = torch.matmul(q, k.transpose(1, 2)) + alpha = F.softmax(QK_T, dim=-1) + + # a*v + att = torch.matmul(alpha, v).unsqueeze(-1) + att = self.fc(att) + att = self.sigmoid(att) + + output = (x * att) + x + alpha_mask = att.clone() + + return output, alpha_mask + + def forward(self, x): + X_c, alpha_mask = self.Channel_Tracer(x) + X_c = self.bn(X_c) + x_drop = self.masking(X_c, alpha_mask) + + q = self.spatial_q(x_drop).squeeze(1) + k = self.spatial_k(x_drop).squeeze(1) + v = self.spatial_v(x_drop).squeeze(1) + + # softmax(Q*K^T) + QK_T = torch.matmul(q, k.transpose(1, 2)) + alpha = F.softmax(QK_T, dim=-1) + + output = torch.matmul(alpha, v).unsqueeze(1) + v.unsqueeze(1) + + return output + + +class aggregation(nn.Module): + def __init__(self, channel): + super(aggregation, self).__init__() + self.relu = nn.ReLU(True) + + self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) + self.conv_upsample1 = BasicConv2d(channel[2], channel[1], 3, padding=1) + self.conv_upsample2 = BasicConv2d(channel[2], channel[0], 3, padding=1) + self.conv_upsample3 = BasicConv2d(channel[1], channel[0], 3, padding=1) + self.conv_upsample4 = BasicConv2d(channel[2], channel[2], 3, padding=1) + self.conv_upsample5 = BasicConv2d(channel[2] + channel[1], channel[2] + channel[1], 3, padding=1) + + self.conv_concat2 = BasicConv2d((channel[2] + channel[1]), (channel[2] + channel[1]), 3, padding=1) + self.conv_concat3 = BasicConv2d((channel[0] + channel[1] + channel[2]), + (channel[0] + channel[1] + channel[2]), 3, padding=1) + + self.UAM = UnionAttentionModule(channel[0] + channel[1] + channel[2]) + + def forward(self, e4, e3, e2): + e4_1 = e4 + e3_1 = self.conv_upsample1(self.upsample(e4)) * e3 + e2_1 = self.conv_upsample2(self.upsample(self.upsample(e4))) \ + * self.conv_upsample3(self.upsample(e3)) * e2 + + e3_2 = torch.cat((e3_1, self.conv_upsample4(self.upsample(e4_1))), 1) + e3_2 = self.conv_concat2(e3_2) + + e2_2 = torch.cat((e2_1, self.conv_upsample5(self.upsample(e3_2))), 1) + x = self.conv_concat3(e2_2) + + output = self.UAM(x) + + return output + + +class ObjectAttention(nn.Module): + def __init__(self, channel, kernel_size): + super(ObjectAttention, self).__init__() + self.channel = channel + self.DWSConv = DWSConv(channel, channel // 2, kernel=kernel_size, padding=1, kernels_per_layer=1) + self.DWConv1 = nn.Sequential( + DWConv(channel // 2, channel // 2, kernel=1, padding=0, dilation=1), + BasicConv2d(channel // 2, channel // 8, 1), + ) + self.DWConv2 = nn.Sequential( + DWConv(channel // 2, channel // 2, kernel=3, padding=1, dilation=1), + BasicConv2d(channel // 2, channel // 8, 1), + ) + self.DWConv3 = nn.Sequential( + DWConv(channel // 2, channel // 2, kernel=3, padding=3, dilation=3), + BasicConv2d(channel // 2, channel // 8, 1), + ) + self.DWConv4 = nn.Sequential( + DWConv(channel // 2, channel // 2, kernel=3, padding=5, dilation=5), + BasicConv2d(channel // 2, channel // 8, 1), + ) + self.conv1 = BasicConv2d(channel // 2, 1, 1) + + def forward(self, decoder_map, encoder_map): + """ + Args: + decoder_map: decoder representation (B, 1, H, W). + encoder_map: encoder block output (B, C, H, W). + Returns: + decoder representation: (B, 1, H, W) + """ + mask_bg = -1 * torch.sigmoid(decoder_map) + 1 # Sigmoid & Reverse + mask_ob = torch.sigmoid(decoder_map) # object attention + x = mask_ob.expand(-1, self.channel, -1, -1).mul(encoder_map) + + edge = mask_bg.clone() + edge[edge > cfg.denoise] = 0 + x = x + (edge * encoder_map) + + x = self.DWSConv(x) + skip = x.clone() + x = torch.cat([self.DWConv1(x), self.DWConv2(x), self.DWConv3(x), self.DWConv4(x)], dim=1) + skip + x = torch.relu(self.conv1(x)) + + return x + decoder_map \ No newline at end of file diff --git a/modules/conv_modules.py b/modules/conv_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..bad641b85ae8b603ca9829b5c9dffaf55282bf0e --- /dev/null +++ b/modules/conv_modules.py @@ -0,0 +1,56 @@ +""" +author: Min Seok Lee and Wooseok Shin +""" +import torch.nn as nn + + +class BasicConv2d(nn.Module): + def __init__(self, in_channel, out_channel, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1)): + super(BasicConv2d, self).__init__() + self.conv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel_size, stride=stride, padding=padding, + dilation=dilation, bias=False) + self.bn = nn.BatchNorm2d(out_channel) + self.selu = nn.SELU() + + def forward(self, x): + x = self.conv(x) + x = self.bn(x) + x = self.selu(x) + + return x + + +class DWConv(nn.Module): + def __init__(self, in_channel, out_channel, kernel, dilation, padding): + super(DWConv, self).__init__() + self.out_channel = out_channel + self.DWConv = nn.Conv2d(in_channel, out_channel, kernel_size=kernel, padding=padding, groups=in_channel, + dilation=dilation, bias=False) + self.bn = nn.BatchNorm2d(out_channel) + self.selu = nn.SELU() + + def forward(self, x): + x = self.DWConv(x) + out = self.selu(self.bn(x)) + + return out + + +class DWSConv(nn.Module): + def __init__(self, in_channel, out_channel, kernel, padding, kernels_per_layer): + super(DWSConv, self).__init__() + self.out_channel = out_channel + self.DWConv = nn.Conv2d(in_channel, in_channel * kernels_per_layer, kernel_size=kernel, padding=padding, + groups=in_channel, bias=False) + self.bn = nn.BatchNorm2d(in_channel * kernels_per_layer) + self.selu = nn.SELU() + self.PWConv = nn.Conv2d(in_channel * kernels_per_layer, out_channel, kernel_size=1, bias=False) + self.bn2 = nn.BatchNorm2d(out_channel) + + def forward(self, x): + x = self.DWConv(x) + x = self.selu(self.bn(x)) + out = self.PWConv(x) + out = self.selu(self.bn2(out)) + + return out \ No newline at end of file diff --git a/object/custom_dataset/110000026240767.png b/object/custom_dataset/110000026240767.png new file mode 100644 index 0000000000000000000000000000000000000000..6116a5da5ba674cb61eddabf6f60bdd7cc649434 Binary files /dev/null and b/object/custom_dataset/110000026240767.png differ diff --git a/object/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png b/object/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png new file mode 100644 index 0000000000000000000000000000000000000000..3e5f77450f2fc75ea06d4d657b33aff13197b88e Binary files /dev/null and b/object/custom_dataset/200630_colekt_pack0937__la_chambre__bottle_50ml__final__16x9-copy-scaled.png differ diff --git a/object/custom_dataset/43a71f50-b839-4ab8-8be8-5be346ffe8be.png b/object/custom_dataset/43a71f50-b839-4ab8-8be8-5be346ffe8be.png new file mode 100644 index 0000000000000000000000000000000000000000..daf3748ddafed0ce09f2d2daa6c14f56ed2e1e7c Binary files /dev/null and b/object/custom_dataset/43a71f50-b839-4ab8-8be8-5be346ffe8be.png differ diff --git a/object/custom_dataset/TOMBUL.png b/object/custom_dataset/TOMBUL.png new file mode 100644 index 0000000000000000000000000000000000000000..e7c9469d8d36c39a672100a0f5a0fdee27c523f7 Binary files /dev/null and b/object/custom_dataset/TOMBUL.png differ diff --git a/object/custom_dataset/images (1).png b/object/custom_dataset/images (1).png new file mode 100644 index 0000000000000000000000000000000000000000..fb3b33c353e566437bc9522c90387351f33460d1 Binary files /dev/null and b/object/custom_dataset/images (1).png differ diff --git a/object/custom_dataset/images.png b/object/custom_dataset/images.png new file mode 100644 index 0000000000000000000000000000000000000000..612232221edd7dcbcd5ec0920b38cd125c809cf1 Binary files /dev/null and b/object/custom_dataset/images.png differ diff --git a/object/custom_dataset/indir (1).png b/object/custom_dataset/indir (1).png new file mode 100644 index 0000000000000000000000000000000000000000..240365396933e964e2fb3d5e0a10eaba4bc429b8 Binary files /dev/null and b/object/custom_dataset/indir (1).png differ diff --git a/object/custom_dataset/indir (2).png b/object/custom_dataset/indir (2).png new file mode 100644 index 0000000000000000000000000000000000000000..85800115307d1b7162bb95f87566cb0f1f8f7995 Binary files /dev/null and b/object/custom_dataset/indir (2).png differ diff --git a/object/custom_dataset/indir.png b/object/custom_dataset/indir.png new file mode 100644 index 0000000000000000000000000000000000000000..2a0ba3696af23b283024d9866a2303bc1ae0f6df Binary files /dev/null and b/object/custom_dataset/indir.png differ diff --git a/object/custom_dataset/kabe-a-1912087.png b/object/custom_dataset/kabe-a-1912087.png new file mode 100644 index 0000000000000000000000000000000000000000..05cd358bb40f6a985dd8ecadb6c8a19cbd4f033a Binary files /dev/null and b/object/custom_dataset/kabe-a-1912087.png differ diff --git a/object/custom_dataset/photo-1541643600914-78b084683601.png b/object/custom_dataset/photo-1541643600914-78b084683601.png new file mode 100644 index 0000000000000000000000000000000000000000..3fa6e2023f2b3d8980078d2075f109aff2405804 Binary files /dev/null and b/object/custom_dataset/photo-1541643600914-78b084683601.png differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..36ef8c8809a5f7d8b9ab6dc2d60836dccbd8bea7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,28 @@ +albumentations==1.0.3 +certifi==2022.12.7 +colorama==0.4.4 +cycler==0.10.0 +imageio==2.9.0 +joblib==1.2.0 +kiwisolver==1.3.2 +matplotlib==3.4.3 +networkx==2.6.2 +opencv-python-headless==4.5.3.56 +Pillow +pyparsing==2.4.7 +python-dateutil==2.8.2 +PyWavelets==1.1.1 +PyYAML==5.4.1 +scikit-image==0.18.3 +scikit-learn==0.24.2 +scipy==1.7.1 +six==1.16.0 +sklearn==0.0 +threadpoolctl==2.2.0 +tifffile==2021.8.30 +torch +torchvision +tqdm +wincertstore==0.2 +transformers +streamlit diff --git a/trainer.py b/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..36d6e044419f6e4ea32f0ef9da87b5c044f2b9f7 --- /dev/null +++ b/trainer.py @@ -0,0 +1,293 @@ +""" +author: Min Seok Lee and Wooseok Shin +""" +import os +import cv2 +import time +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from tqdm import tqdm +from dataloader import get_train_augmentation, get_test_augmentation, get_loader, gt_to_tensor +from util.utils import AvgMeter +from util.metrics import Evaluation_metrics +from util.losses import Optimizer, Scheduler, Criterion +from model.TRACER import TRACER + + +class Trainer(): + def __init__(self, args, save_path): + super(Trainer, self).__init__() + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.size = args.img_size + + self.tr_img_folder = os.path.join(args.data_path, args.dataset, 'Train/images/') + self.tr_gt_folder = os.path.join(args.data_path, args.dataset, 'Train/masks/') + self.tr_edge_folder = os.path.join(args.data_path, args.dataset, 'Train/edges/') + + self.train_transform = get_train_augmentation(img_size=args.img_size, ver=args.aug_ver) + self.test_transform = get_test_augmentation(img_size=args.img_size) + + self.train_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, self.tr_edge_folder, phase='train', + batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, + transform=self.train_transform, seed=args.seed) + self.val_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, self.tr_edge_folder, phase='val', + batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, + transform=self.test_transform, seed=args.seed) + + # Network + self.model = TRACER(args).to(self.device) + + if args.multi_gpu: + self.model = nn.DataParallel(self.model).to(self.device) + + # Loss and Optimizer + self.criterion = Criterion(args) + self.optimizer = Optimizer(args, self.model) + self.scheduler = Scheduler(args, self.optimizer) + + # Train / Validate + min_loss = 1000 + early_stopping = 0 + t = time.time() + for epoch in range(1, args.epochs + 1): + self.epoch = epoch + train_loss, train_mae = self.training(args) + val_loss, val_mae = self.validate() + + if args.scheduler == 'Reduce': + self.scheduler.step(val_loss) + else: + self.scheduler.step() + + # Save models + if val_loss < min_loss: + early_stopping = 0 + best_epoch = epoch + best_mae = val_mae + min_loss = val_loss + torch.save(self.model.state_dict(), os.path.join(save_path, 'best_model.pth')) + print(f'-----------------SAVE:{best_epoch}epoch----------------') + else: + early_stopping += 1 + + if early_stopping == args.patience + 5: + break + + print(f'\nBest Val Epoch:{best_epoch} | Val Loss:{min_loss:.3f} | Val MAE:{best_mae:.3f} ' + f'time: {(time.time() - t) / 60:.3f}M') + + # Test time + datasets = ['DUTS', 'DUT-O', 'HKU-IS', 'ECSSD', 'PASCAL-S'] + for dataset in datasets: + args.dataset = dataset + test_loss, test_mae, test_maxf, test_avgf, test_s_m = self.test(args, os.path.join(save_path)) + + print( + f'Test Loss:{test_loss:.3f} | MAX_F:{test_maxf:.3f} | AVG_F:{test_avgf:.3f} | MAE:{test_mae:.3f} ' + f'| S_Measure:{test_s_m:.3f}, time: {time.time() - t:.3f}s') + + end = time.time() + print(f'Total Process time:{(end - t) / 60:.3f}Minute') + + def training(self, args): + self.model.train() + train_loss = AvgMeter() + train_mae = AvgMeter() + + for images, masks, edges in tqdm(self.train_loader): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + masks = torch.tensor(masks, device=self.device, dtype=torch.float32) + edges = torch.tensor(edges, device=self.device, dtype=torch.float32) + + self.optimizer.zero_grad() + outputs, edge_mask, ds_map = self.model(images) + loss1 = self.criterion(outputs, masks) + loss2 = self.criterion(ds_map[0], masks) + loss3 = self.criterion(ds_map[1], masks) + loss4 = self.criterion(ds_map[2], masks) + + loss_mask = self.criterion(edge_mask, edges) + loss = loss1 + loss2 + loss3 + loss4 + loss_mask + + loss.backward() + nn.utils.clip_grad_norm_(self.model.parameters(), args.clipping) + self.optimizer.step() + + # Metric + mae = torch.mean(torch.abs(outputs - masks)) + + # log + train_loss.update(loss.item(), n=images.size(0)) + train_mae.update(mae.item(), n=images.size(0)) + + print(f'Epoch:[{self.epoch:03d}/{args.epochs:03d}]') + print(f'Train Loss:{train_loss.avg:.3f} | MAE:{train_mae.avg:.3f}') + + return train_loss.avg, train_mae.avg + + def validate(self): + self.model.eval() + val_loss = AvgMeter() + val_mae = AvgMeter() + + with torch.no_grad(): + for images, masks, edges in tqdm(self.val_loader): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + masks = torch.tensor(masks, device=self.device, dtype=torch.float32) + edges = torch.tensor(edges, device=self.device, dtype=torch.float32) + + outputs, edge_mask, ds_map = self.model(images) + loss1 = self.criterion(outputs, masks) + loss2 = self.criterion(ds_map[0], masks) + loss3 = self.criterion(ds_map[1], masks) + loss4 = self.criterion(ds_map[2], masks) + + loss_mask = self.criterion(edge_mask, edges) + loss = loss1 + loss2 + loss3 + loss4 + loss_mask + + # Metric + mae = torch.mean(torch.abs(outputs - masks)) + + # log + val_loss.update(loss.item(), n=images.size(0)) + val_mae.update(mae.item(), n=images.size(0)) + + print(f'Valid Loss:{val_loss.avg:.3f} | MAE:{val_mae.avg:.3f}') + return val_loss.avg, val_mae.avg + + def test(self, args, save_path): + path = os.path.join(save_path, 'best_model.pth') + self.model.load_state_dict(torch.load(path)) + print('###### pre-trained Model restored #####') + + te_img_folder = os.path.join(args.data_path, args.dataset, 'Test/images/') + te_gt_folder = os.path.join(args.data_path, args.dataset, 'Test/masks/') + test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, phase='test', + batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, transform=self.test_transform) + + self.model.eval() + test_loss = AvgMeter() + test_mae = AvgMeter() + test_maxf = AvgMeter() + test_avgf = AvgMeter() + test_s_m = AvgMeter() + + Eval_tool = Evaluation_metrics(args.dataset, self.device) + + with torch.no_grad(): + for i, (images, masks, original_size, image_name) in enumerate(tqdm(test_loader)): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + + outputs, edge_mask, ds_map = self.model(images) + H, W = original_size + + for i in range(images.size(0)): + mask = gt_to_tensor(masks[i]) + + h, w = H[i].item(), W[i].item() + + output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear') + + loss = self.criterion(output, mask) + + # Metric + mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask) + + # log + test_loss.update(loss.item(), n=1) + test_mae.update(mae, n=1) + test_maxf.update(max_f, n=1) + test_avgf.update(avg_f, n=1) + test_s_m.update(s_score, n=1) + + test_loss = test_loss.avg + test_mae = test_mae.avg + test_maxf = test_maxf.avg + test_avgf = test_avgf.avg + test_s_m = test_s_m.avg + + return test_loss, test_mae, test_maxf, test_avgf, test_s_m + + +class Tester(): + def __init__(self, args, save_path): + super(Tester, self).__init__() + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.test_transform = get_test_augmentation(img_size=args.img_size) + self.args = args + self.save_path = save_path + + # Network + self.model = TRACER(args).to(self.device) + if args.multi_gpu: + self.model = nn.DataParallel(self.model).to(self.device) + + path = os.path.join(save_path, 'best_model.pth') + self.model.load_state_dict(torch.load(path)) + print('###### pre-trained Model restored #####') + + self.criterion = Criterion(args) + + te_img_folder = os.path.join(args.data_path, args.dataset, 'Test/images/') + te_gt_folder = os.path.join(args.data_path, args.dataset, 'Test/masks/') + + self.test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, phase='test', + batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, transform=self.test_transform) + + if args.save_map is not None: + os.makedirs(os.path.join('mask', 'exp'+str(self.args.exp_num), self.args.dataset), exist_ok=True) + + def test(self): + self.model.eval() + test_loss = AvgMeter() + test_mae = AvgMeter() + test_maxf = AvgMeter() + test_avgf = AvgMeter() + test_s_m = AvgMeter() + t = time.time() + + Eval_tool = Evaluation_metrics(self.args.dataset, self.device) + + with torch.no_grad(): + for i, (images, masks, original_size, image_name) in enumerate(tqdm(self.test_loader)): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + + outputs, edge_mask, ds_map = self.model(images) + H, W = original_size + + for i in range(images.size(0)): + mask = gt_to_tensor(masks[i]) + h, w = H[i].item(), W[i].item() + + output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear') + loss = self.criterion(output, mask) + + # Metric + mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask) + + # Save prediction map + if self.args.save_map is not None: + output = (output.squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type + cv2.imwrite(os.path.join('mask', 'exp'+str(self.args.exp_num), self.args.dataset, image_name[i]+'.png'), output) + + # log + test_loss.update(loss.item(), n=1) + test_mae.update(mae, n=1) + test_maxf.update(max_f, n=1) + test_avgf.update(avg_f, n=1) + test_s_m.update(s_score, n=1) + + test_loss = test_loss.avg + test_mae = test_mae.avg + test_maxf = test_maxf.avg + test_avgf = test_avgf.avg + test_s_m = test_s_m.avg + + print(f'Test Loss:{test_loss:.4f} | MAX_F:{test_maxf:.4f} | MAE:{test_mae:.4f} ' + f'| S_Measure:{test_s_m:.4f}, time: {time.time() - t:.3f}s') + + return test_loss, test_mae, test_maxf, test_avgf, test_s_m diff --git a/util/__pycache__/effi_utils.cpython-39.pyc b/util/__pycache__/effi_utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48765dc75b8e23f288ec6a5c5b336c2e258e12c1 Binary files /dev/null and b/util/__pycache__/effi_utils.cpython-39.pyc differ diff --git a/util/__pycache__/losses.cpython-39.pyc b/util/__pycache__/losses.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5e15dfcdffed4e423b7f56f3b376083644f7442 Binary files /dev/null and b/util/__pycache__/losses.cpython-39.pyc differ diff --git a/util/__pycache__/metrics.cpython-39.pyc b/util/__pycache__/metrics.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f90a64055bbec710e4a54aa4e9555da3cca9c97a Binary files /dev/null and b/util/__pycache__/metrics.cpython-39.pyc differ diff --git a/util/__pycache__/utils.cpython-39.pyc b/util/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eab59a77455e8f505ea19d5b6b5a4f31bbe29533 Binary files /dev/null and b/util/__pycache__/utils.cpython-39.pyc differ diff --git a/util/effi_utils.py b/util/effi_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2423b855588b47d79e74446744e53458d93dd17d --- /dev/null +++ b/util/effi_utils.py @@ -0,0 +1,637 @@ +""" +Original author: lukemelas (github username) +Github repo: https://github.com/lukemelas/EfficientNet-PyTorch +With adjustments and added comments by workingcoder (github username). + +Reimplemented: Min Seok Lee and Wooseok Shin +""" + +import re +import math +import collections +from functools import partial +import torch +from torch import nn +from torch.nn import functional as F +from torch.utils import model_zoo +from config import getConfig + +cfg = getConfig() + +def get_model_shape(): + if cfg.arch == '0': + block_idx = [2, 4, 10, 15] + channels = [24, 40, 112, 320] + elif cfg.arch == '1': + block_idx = [4, 7, 15, 22] + channels = [24, 40, 112, 320] + elif cfg.arch == '2': + block_idx = [4, 7, 15, 22] + channels = [24, 48, 120, 352] + elif cfg.arch == '3': + block_idx = [4, 7, 17, 25] + channels = [32, 48, 136, 384] + elif cfg.arch == '4': + block_idx = [5, 9, 21, 31] + channels = [32, 56, 160, 448] + elif cfg.arch == '5': + block_idx = [7, 12, 26, 38] + channels = [40, 64, 176, 512] + elif cfg.arch == '6': + block_idx = [8, 14, 30, 44] + channels = [40, 72, 200, 576] + elif cfg.arch == '7': + block_idx = [10, 17, 37, 54] + channels = [48, 80, 224, 640] + + return block_idx, channels + +################################################################################ +### Help functions for model architecture +################################################################################ + +# GlobalParams and BlockArgs: Two namedtuples +# Swish and MemoryEfficientSwish: Two implementations of the method +# round_filters and round_repeats: +# Functions to calculate params for scaling model width and depth ! ! ! +# get_width_and_height_from_size and calculate_output_image_size +# drop_connect: A structural design +# get_same_padding_conv2d: +# Conv2dDynamicSamePadding +# Conv2dStaticSamePadding +# get_same_padding_maxPool2d: +# MaxPool2dDynamicSamePadding +# MaxPool2dStaticSamePadding +# It's an additional function, not used in EfficientNet, +# but can be used in other model (such as EfficientDet). + +# Parameters for the entire model (stem, all blocks, and head) +GlobalParams = collections.namedtuple('GlobalParams', [ + 'width_coefficient', 'depth_coefficient', 'image_size', 'dropout_rate', + 'num_classes', 'batch_norm_momentum', 'batch_norm_epsilon', + 'drop_connect_rate', 'depth_divisor', 'min_depth', 'include_top']) + +# Parameters for an individual model block +BlockArgs = collections.namedtuple('BlockArgs', [ + 'num_repeat', 'kernel_size', 'stride', 'expand_ratio', + 'input_filters', 'output_filters', 'se_ratio', 'id_skip']) + +# Set GlobalParams and BlockArgs's defaults +GlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields) +BlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields) + + +# An ordinary implementation of Swish function +class Swish(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + + +# A memory-efficient implementation of Swish function +class SwishImplementation(torch.autograd.Function): + @staticmethod + def forward(ctx, i): + result = i * torch.sigmoid(i) + ctx.save_for_backward(i) + return result + + @staticmethod + def backward(ctx, grad_output): + i = ctx.saved_tensors[0] + sigmoid_i = torch.sigmoid(i) + return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i))) + +class MemoryEfficientSwish(nn.Module): + def forward(self, x): + return SwishImplementation.apply(x) + + +def round_filters(filters, global_params): + """Calculate and round number of filters based on width multiplier. + Use width_coefficient, depth_divisor and min_depth of global_params. + + Args: + filters (int): Filters number to be calculated. + global_params (namedtuple): Global params of the model. + + Returns: + new_filters: New filters number after calculating. + """ + multiplier = global_params.width_coefficient + if not multiplier: + return filters + # TODO: modify the params names. + # maybe the names (width_divisor,min_width) + # are more suitable than (depth_divisor,min_depth). + divisor = global_params.depth_divisor + min_depth = global_params.min_depth + filters *= multiplier + min_depth = min_depth or divisor # pay attention to this line when using min_depth + # follow the formula transferred from official TensorFlow implementation + new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor) + if new_filters < 0.9 * filters: # prevent rounding by more than 10% + new_filters += divisor + return int(new_filters) + + +def round_repeats(repeats, global_params): + """Calculate module's repeat number of a block based on depth multiplier. + Use depth_coefficient of global_params. + + Args: + repeats (int): num_repeat to be calculated. + global_params (namedtuple): Global params of the model. + + Returns: + new repeat: New repeat number after calculating. + """ + multiplier = global_params.depth_coefficient + if not multiplier: + return repeats + # follow the formula transferred from official TensorFlow implementation + return int(math.ceil(multiplier * repeats)) + + +def drop_connect(inputs, p, training): + """Drop connect. + + Args: + input (tensor: BCWH): Input of this structure. + p (float: 0.0~1.0): Probability of drop connection. + training (bool): The running mode. + + Returns: + output: Output after drop connection. + """ + assert 0 <= p <= 1, 'p must be in range of [0,1]' + + if not training: + return inputs + + batch_size = inputs.shape[0] + keep_prob = 1 - p + + # generate binary_tensor mask according to probability (p for 0, 1-p for 1) + random_tensor = keep_prob + random_tensor += torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device) + binary_tensor = torch.floor(random_tensor) + + output = inputs / keep_prob * binary_tensor + return output + + +def get_width_and_height_from_size(x): + """Obtain height and width from x. + + Args: + x (int, tuple or list): Data size. + + Returns: + size: A tuple or list (H,W). + """ + if isinstance(x, int): + return x, x + if isinstance(x, list) or isinstance(x, tuple): + return x + else: + raise TypeError() + + +def calculate_output_image_size(input_image_size, stride): + """Calculates the output image size when using Conv2dSamePadding with a stride. + Necessary for static padding. Thanks to mannatsingh for pointing this out. + + Args: + input_image_size (int, tuple or list): Size of input image. + stride (int, tuple or list): Conv2d operation's stride. + + Returns: + output_image_size: A list [H,W]. + """ + if input_image_size is None: + return None + image_height, image_width = get_width_and_height_from_size(input_image_size) + stride = stride if isinstance(stride, int) else stride[0] + image_height = int(math.ceil(image_height / stride)) + image_width = int(math.ceil(image_width / stride)) + return [image_height, image_width] + + +# Note: +# The following 'SamePadding' functions make output size equal ceil(input size/stride). +# Only when stride equals 1, can the output size be the same as input size. +# Don't be confused by their function names ! ! ! + +def get_same_padding_conv2d(image_size=None): + """Chooses static padding if you have specified an image size, and dynamic padding otherwise. + Static padding is necessary for ONNX exporting of models. + + Args: + image_size (int or tuple): Size of the image. + + Returns: + Conv2dDynamicSamePadding or Conv2dStaticSamePadding. + """ + if image_size is None: + return Conv2dDynamicSamePadding + else: + return partial(Conv2dStaticSamePadding, image_size=image_size) + + +class Conv2dDynamicSamePadding(nn.Conv2d): + """2D Convolutions like TensorFlow, for a dynamic image size. + The padding is operated in forward function by calculating dynamically. + """ + + # Tips for 'SAME' mode padding. + # Given the following: + # i: width or height + # s: stride + # k: kernel size + # d: dilation + # p: padding + # Output after Conv2d: + # o = floor((i+p-((k-1)*d+1))/s+1) + # If o equals i, i = floor((i+p-((k-1)*d+1))/s+1), + # => p = (i-1)*s+((k-1)*d+1)-i + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True): + super().__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias) + self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]] * 2 + + def forward(self, x): + ih, iw = x.size()[-2:] + kh, kw = self.weight.size()[-2:] + sh, sw = self.stride + oh, ow = math.ceil(ih / sh), math.ceil(iw / sw) # change the output size according to stride ! ! ! + pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0) + pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0) + if pad_h > 0 or pad_w > 0: + x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2]) + return F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups) + + +class Conv2dStaticSamePadding(nn.Conv2d): + """2D Convolutions like TensorFlow's 'SAME' mode, with the given input image size. + The padding mudule is calculated in construction function, then used in forward. + """ + + # With the same calculation as Conv2dDynamicSamePadding + + def __init__(self, in_channels, out_channels, kernel_size, stride=1, image_size=None, **kwargs): + super().__init__(in_channels, out_channels, kernel_size, stride, **kwargs) + self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]] * 2 + + # Calculate padding based on image size and save it + assert image_size is not None + ih, iw = (image_size, image_size) if isinstance(image_size, int) else image_size + kh, kw = self.weight.size()[-2:] + sh, sw = self.stride + oh, ow = math.ceil(ih / sh), math.ceil(iw / sw) + pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0) + pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0) + if pad_h > 0 or pad_w > 0: + self.static_padding = nn.ZeroPad2d((pad_w // 2, pad_w - pad_w // 2, + pad_h // 2, pad_h - pad_h // 2)) + else: + self.static_padding = nn.Identity() + + def forward(self, x): + x = self.static_padding(x) + x = F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups) + return x + + +def get_same_padding_maxPool2d(image_size=None): + """Chooses static padding if you have specified an image size, and dynamic padding otherwise. + Static padding is necessary for ONNX exporting of models. + + Args: + image_size (int or tuple): Size of the image. + + Returns: + MaxPool2dDynamicSamePadding or MaxPool2dStaticSamePadding. + """ + if image_size is None: + return MaxPool2dDynamicSamePadding + else: + return partial(MaxPool2dStaticSamePadding, image_size=image_size) + + +class MaxPool2dDynamicSamePadding(nn.MaxPool2d): + """2D MaxPooling like TensorFlow's 'SAME' mode, with a dynamic image size. + The padding is operated in forward function by calculating dynamically. + """ + + def __init__(self, kernel_size, stride, padding=0, dilation=1, return_indices=False, ceil_mode=False): + super().__init__(kernel_size, stride, padding, dilation, return_indices, ceil_mode) + self.stride = [self.stride] * 2 if isinstance(self.stride, int) else self.stride + self.kernel_size = [self.kernel_size] * 2 if isinstance(self.kernel_size, int) else self.kernel_size + self.dilation = [self.dilation] * 2 if isinstance(self.dilation, int) else self.dilation + + def forward(self, x): + ih, iw = x.size()[-2:] + kh, kw = self.kernel_size + sh, sw = self.stride + oh, ow = math.ceil(ih / sh), math.ceil(iw / sw) + pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0) + pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0) + if pad_h > 0 or pad_w > 0: + x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2]) + return F.max_pool2d(x, self.kernel_size, self.stride, self.padding, + self.dilation, self.ceil_mode, self.return_indices) + +class MaxPool2dStaticSamePadding(nn.MaxPool2d): + """2D MaxPooling like TensorFlow's 'SAME' mode, with the given input image size. + The padding mudule is calculated in construction function, then used in forward. + """ + + def __init__(self, kernel_size, stride, image_size=None, **kwargs): + super().__init__(kernel_size, stride, **kwargs) + self.stride = [self.stride] * 2 if isinstance(self.stride, int) else self.stride + self.kernel_size = [self.kernel_size] * 2 if isinstance(self.kernel_size, int) else self.kernel_size + self.dilation = [self.dilation] * 2 if isinstance(self.dilation, int) else self.dilation + + # Calculate padding based on image size and save it + assert image_size is not None + ih, iw = (image_size, image_size) if isinstance(image_size, int) else image_size + kh, kw = self.kernel_size + sh, sw = self.stride + oh, ow = math.ceil(ih / sh), math.ceil(iw / sw) + pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0) + pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0) + if pad_h > 0 or pad_w > 0: + self.static_padding = nn.ZeroPad2d((pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2)) + else: + self.static_padding = nn.Identity() + + def forward(self, x): + x = self.static_padding(x) + x = F.max_pool2d(x, self.kernel_size, self.stride, self.padding, + self.dilation, self.ceil_mode, self.return_indices) + return x + + +################################################################################ +### Helper functions for loading model params +################################################################################ + +# BlockDecoder: A Class for encoding and decoding BlockArgs +# efficientnet_params: A function to query compound coefficient +# get_model_params and efficientnet: +# Functions to get BlockArgs and GlobalParams for efficientnet +# url_map and url_map_advprop: Dicts of url_map for pretrained weights +# load_pretrained_weights: A function to load pretrained weights + +class BlockDecoder(object): + """Block Decoder for readability, + straight from the official TensorFlow repository. + """ + + @staticmethod + def _decode_block_string(block_string): + """Get a block through a string notation of arguments. + + Args: + block_string (str): A string notation of arguments. + Examples: 'r1_k3_s11_e1_i32_o16_se0.25_noskip'. + + Returns: + BlockArgs: The namedtuple defined at the top of this file. + """ + assert isinstance(block_string, str) + + ops = block_string.split('_') + options = {} + for op in ops: + splits = re.split(r'(\d.*)', op) + if len(splits) >= 2: + key, value = splits[:2] + options[key] = value + + # Check stride + assert (('s' in options and len(options['s']) == 1) or + (len(options['s']) == 2 and options['s'][0] == options['s'][1])) + + return BlockArgs( + num_repeat=int(options['r']), + kernel_size=int(options['k']), + stride=[int(options['s'][0])], + expand_ratio=int(options['e']), + input_filters=int(options['i']), + output_filters=int(options['o']), + se_ratio=float(options['se']) if 'se' in options else None, + id_skip=('noskip' not in block_string)) + + @staticmethod + def _encode_block_string(block): + """Encode a block to a string. + + Args: + block (namedtuple): A BlockArgs type argument. + + Returns: + block_string: A String form of BlockArgs. + """ + args = [ + 'r%d' % block.num_repeat, + 'k%d' % block.kernel_size, + 's%d%d' % (block.strides[0], block.strides[1]), + 'e%s' % block.expand_ratio, + 'i%d' % block.input_filters, + 'o%d' % block.output_filters + ] + if 0 < block.se_ratio <= 1: + args.append('se%s' % block.se_ratio) + if block.id_skip is False: + args.append('noskip') + return '_'.join(args) + + @staticmethod + def decode(string_list): + """Decode a list of string notations to specify blocks inside the network. + + Args: + string_list (list[str]): A list of strings, each string is a notation of block. + + Returns: + blocks_args: A list of BlockArgs namedtuples of block args. + """ + assert isinstance(string_list, list) + blocks_args = [] + for block_string in string_list: + blocks_args.append(BlockDecoder._decode_block_string(block_string)) + return blocks_args + + @staticmethod + def encode(blocks_args): + """Encode a list of BlockArgs to a list of strings. + + Args: + blocks_args (list[namedtuples]): A list of BlockArgs namedtuples of block args. + + Returns: + block_strings: A list of strings, each string is a notation of block. + """ + block_strings = [] + for block in blocks_args: + block_strings.append(BlockDecoder._encode_block_string(block)) + return block_strings + + +def efficientnet_params(model_name): + """Map EfficientNet model name to parameter coefficients. + + Args: + model_name (str): Model name to be queried. + + Returns: + params_dict[model_name]: A (width,depth,res,dropout) tuple. + """ + params_dict = { + # Coefficients: width,depth,res,dropout + 'efficientnet-b0': (1.0, 1.0, 224, 0.2), + 'efficientnet-b1': (1.0, 1.1, 240, 0.2), + 'efficientnet-b2': (1.1, 1.2, 260, 0.3), + 'efficientnet-b3': (1.2, 1.4, 300, 0.3), + 'efficientnet-b4': (1.4, 1.8, 380, 0.4), + 'efficientnet-b5': (1.6, 2.2, 456, 0.4), + 'efficientnet-b6': (1.8, 2.6, 528, 0.5), + 'efficientnet-b7': (2.0, 3.1, 600, 0.5), + 'efficientnet-b8': (2.2, 3.6, 672, 0.5), + 'efficientnet-l2': (4.3, 5.3, 800, 0.5), + } + return params_dict[model_name] + + +def efficientnet(width_coefficient=None, depth_coefficient=None, image_size=None, + dropout_rate=0.2, drop_connect_rate=0.2, num_classes=1000, include_top=True): + """Create BlockArgs and GlobalParams for efficientnet model. + + Args: + width_coefficient (float) + depth_coefficient (float) + image_size (int) + dropout_rate (float) + drop_connect_rate (float) + num_classes (int) + + Meaning as the name suggests. + + Returns: + blocks_args, global_params. + """ + + # Blocks args for the whole model(efficientnet-b0 by default) + # It will be modified in the construction of EfficientNet Class according to model + blocks_args = [ + 'r1_k3_s11_e1_i32_o16_se0.25', + 'r2_k3_s22_e6_i16_o24_se0.25', + 'r2_k5_s22_e6_i24_o40_se0.25', + 'r3_k3_s22_e6_i40_o80_se0.25', + 'r3_k5_s11_e6_i80_o112_se0.25', + 'r4_k5_s22_e6_i112_o192_se0.25', + 'r1_k3_s11_e6_i192_o320_se0.25', + ] + blocks_args = BlockDecoder.decode(blocks_args) + + global_params = GlobalParams( + width_coefficient=width_coefficient, + depth_coefficient=depth_coefficient, + image_size=image_size, + dropout_rate=dropout_rate, + + num_classes=num_classes, + batch_norm_momentum=0.99, + batch_norm_epsilon=1e-3, + drop_connect_rate=drop_connect_rate, + depth_divisor=8, + min_depth=None, + include_top=include_top, + ) + + return blocks_args, global_params + + +def get_model_params(model_name, override_params): + """Get the block args and global params for a given model name. + + Args: + model_name (str): Model's name. + override_params (dict): A dict to modify global_params. + + Returns: + blocks_args, global_params + """ + if model_name.startswith('efficientnet'): + w, d, s, p = efficientnet_params(model_name) + # note: all models have drop connect rate = 0.2 + blocks_args, global_params = efficientnet( + width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s) + else: + raise NotImplementedError('model name is not pre-defined: {}'.format(model_name)) + if override_params: + # ValueError will be raised here if override_params has fields not included in global_params. + global_params = global_params._replace(**override_params) + return blocks_args, global_params + + +# train with Standard methods +# check more details in paper(EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks) +url_map = { + 'efficientnet-b0': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth', + 'efficientnet-b1': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b1-f1951068.pth', + 'efficientnet-b2': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b2-8bb594d6.pth', + 'efficientnet-b3': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b3-5fb5a3c3.pth', + 'efficientnet-b4': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b4-6ed6700e.pth', + 'efficientnet-b5': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b5-b6417697.pth', + 'efficientnet-b6': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b6-c76e70fd.pth', + 'efficientnet-b7': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b7-dcc49843.pth', +} + +# train with Adversarial Examples(AdvProp) +# check more details in paper(Adversarial Examples Improve Image Recognition) +url_map_advprop = { + 'efficientnet-b0': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b0-b64d5a18.pth', + 'efficientnet-b1': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b1-0f3ce85a.pth', + 'efficientnet-b2': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b2-6e9d97e5.pth', + 'efficientnet-b3': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b3-cdd7c0f4.pth', + 'efficientnet-b4': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b4-44fb3a87.pth', + 'efficientnet-b5': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b5-86493f6b.pth', + 'efficientnet-b6': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b6-ac80338e.pth', + 'efficientnet-b7': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b7-4652b6dd.pth', + 'efficientnet-b8': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b8-22a8fe65.pth', +} + +def load_pretrained_weights(model, model_name, weights_path=None, load_fc=True, advprop=False): + """Loads pretrained weights from weights path or download using url. + + Args: + model (Module): The whole model of efficientnet. + model_name (str): Model name of efficientnet. + weights_path (None or str): + str: path to pretrained weights file on the local disk. + None: use pretrained weights downloaded from the Internet. + load_fc (bool): Whether to load pretrained weights for fc layer at the end of the model. + advprop (bool): Whether to load pretrained weights + trained with advprop (valid when weights_path is None). + """ + if isinstance(weights_path, str): + state_dict = torch.load(weights_path, strict=False) + else: + # AutoAugment or Advprop (different preprocessing) + url_map_ = url_map_advprop if advprop else url_map + state_dict = model_zoo.load_url(url_map_[model_name]) + + if load_fc: + ret = model.load_state_dict(state_dict, strict=False) + # assert not ret.missing_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys) + else: + state_dict.pop('_fc.weight') + state_dict.pop('_fc.bias') + ret = model.load_state_dict(state_dict, strict=False) + # assert set(ret.missing_keys) == set( + # ['_fc.weight', '_fc.bias']), 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys) + # assert not ret.unexpected_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.unexpected_keys) + + print('Loaded pretrained weights for {}'.format(model_name)) diff --git a/util/losses.py b/util/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..921d8a3d0bed883c3c63064e03fe3468560d8f22 --- /dev/null +++ b/util/losses.py @@ -0,0 +1,51 @@ +""" +author: Min Seok Lee and Wooseok Shin +""" +import torch +import torch.nn.functional as F + + +def Optimizer(args, model): + if args.optimizer == 'Adam': + optimizer = torch.optim.Adam(params=model.parameters(), lr=args.lr, weight_decay=args.weight_decay) + elif args.optimizer == 'SGD': + optimizer = torch.optim.SGD(params=model.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4) + return optimizer + + +def Scheduler(args, optimizer): + if args.scheduler == 'Reduce': + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, mode='min', factor=args.lr_factor, patience=args.patience) + elif args.scheduler == 'Step': + scheduler = torch.optim.lr_scheduler.StepLR( + optimizer, step_size=2, gamma=0.9) + return scheduler + + +def Criterion(args): + if args.criterion == 'API': + criterion = adaptive_pixel_intensity_loss + elif args.criterion == 'bce': + criterion = torch.nn.BCELoss() + return criterion + + +def adaptive_pixel_intensity_loss(pred, mask): + w1 = torch.abs(F.avg_pool2d(mask, kernel_size=3, stride=1, padding=1) - mask) + w2 = torch.abs(F.avg_pool2d(mask, kernel_size=15, stride=1, padding=7) - mask) + w3 = torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask) + + omega = 1 + 0.5 * (w1 + w2 + w3) * mask + + bce = F.binary_cross_entropy(pred, mask, reduce=None) + abce = (omega * bce).sum(dim=(2, 3)) / (omega + 0.5).sum(dim=(2, 3)) + + inter = ((pred * mask) * omega).sum(dim=(2, 3)) + union = ((pred + mask) * omega).sum(dim=(2, 3)) + aiou = 1 - (inter + 1) / (union - inter + 1) + + mae = F.l1_loss(pred, mask, reduce=None) + amae = (omega * mae).sum(dim=(2, 3)) / (omega - 1).sum(dim=(2, 3)) + + return (0.7 * abce + 0.7 * aiou + 0.7 * amae).mean() \ No newline at end of file diff --git a/util/metrics.py b/util/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..4c667ddea2b5fc5fb1465929a4657e9c599c0871 --- /dev/null +++ b/util/metrics.py @@ -0,0 +1,150 @@ +import torch +import numpy as np + + +class Evaluation_metrics(): + def __init__(self, dataset, device): + self.dataset = dataset + self.device = device + + print(f'Dataset:{self.dataset}') + + def cal_total_metrics(self, pred, mask): + # MAE + mae = torch.mean(torch.abs(pred - mask)).item() + # MaxF measure + beta2 = 0.3 + prec, recall = self._eval_pr(pred, mask, 255) + f_score = (1 + beta2) * prec * recall / (beta2 * prec + recall) + f_score[f_score != f_score] = 0 # for Nan + max_f = f_score.max().item() + # AvgF measure + avg_f = f_score.mean().item() + # S measure + alpha = 0.5 + y = mask.mean() + if y == 0: + x = pred.mean() + Q = 1.0 - x + elif y == 1: + x = pred.mean() + Q = x + else: + mask[mask >= 0.5] = 1 + mask[mask < 0.5] = 0 + Q = alpha * self._S_object(pred, mask) + (1 - alpha) * self._S_region(pred, mask) + if Q.item() < 0: + Q = torch.FloatTensor([0.0]) + s_score = Q.item() + + return mae, max_f, avg_f, s_score + + def _eval_pr(self, y_pred, y, num): + if self.device: + prec, recall = torch.zeros(num).to(self.device), torch.zeros(num).to(self.device) + thlist = torch.linspace(0, 1 - 1e-10, num).to(self.device) + else: + prec, recall = torch.zeros(num), torch.zeros(num) + thlist = torch.linspace(0, 1 - 1e-10, num) + for i in range(num): + y_temp = (y_pred >= thlist[i]).float() + tp = (y_temp * y).sum() + prec[i], recall[i] = tp / (y_temp.sum() + 1e-20), tp / (y.sum() + 1e-20) + return prec, recall + + def _S_object(self, pred, mask): + fg = torch.where(mask == 0, torch.zeros_like(pred), pred) + bg = torch.where(mask == 1, torch.zeros_like(pred), 1 - pred) + o_fg = self._object(fg, mask) + o_bg = self._object(bg, 1 - mask) + u = mask.mean() + Q = u * o_fg + (1 - u) * o_bg + return Q + + def _object(self, pred, mask): + temp = pred[mask == 1] + x = temp.mean() + sigma_x = temp.std() + score = 2.0 * x / (x * x + 1.0 + sigma_x + 1e-20) + + return score + + def _S_region(self, pred, mask): + X, Y = self._centroid(mask) + mask1, mask2, mask3, mask4, w1, w2, w3, w4 = self._divideGT(mask, X, Y) + p1, p2, p3, p4 = self._dividePrediction(pred, X, Y) + Q1 = self._ssim(p1, mask1) + Q2 = self._ssim(p2, mask2) + Q3 = self._ssim(p3, mask3) + Q4 = self._ssim(p4, mask4) + Q = w1 * Q1 + w2 * Q2 + w3 * Q3 + w4 * Q4 + # print(Q) + return Q + + def _centroid(self, mask): + rows, cols = mask.size()[-2:] + mask = mask.view(rows, cols) + if mask.sum() == 0: + if self.device: + X = torch.eye(1).to(self.device) * round(cols / 2) + Y = torch.eye(1).to(self.device) * round(rows / 2) + else: + X = torch.eye(1) * round(cols / 2) + Y = torch.eye(1) * round(rows / 2) + else: + total = mask.sum() + if self.device: + i = torch.from_numpy(np.arange(0, cols)).to(self.device).float() + j = torch.from_numpy(np.arange(0, rows)).to(self.device).float() + else: + i = torch.from_numpy(np.arange(0, cols)).float() + j = torch.from_numpy(np.arange(0, rows)).float() + X = torch.round((mask.sum(dim=0) * i).sum() / total) + Y = torch.round((mask.sum(dim=1) * j).sum() / total) + return X.long(), Y.long() + + def _divideGT(self, mask, X, Y): + h, w = mask.size()[-2:] + area = h * w + mask = mask.view(h, w) + LT = mask[:Y, :X] + RT = mask[:Y, X:w] + LB = mask[Y:h, :X] + RB = mask[Y:h, X:w] + X = X.float() + Y = Y.float() + w1 = X * Y / area + w2 = (w - X) * Y / area + w3 = X * (h - Y) / area + w4 = 1 - w1 - w2 - w3 + return LT, RT, LB, RB, w1, w2, w3, w4 + + def _dividePrediction(self, pred, X, Y): + h, w = pred.size()[-2:] + pred = pred.view(h, w) + LT = pred[:Y, :X] + RT = pred[:Y, X:w] + LB = pred[Y:h, :X] + RB = pred[Y:h, X:w] + return LT, RT, LB, RB + + def _ssim(self, pred, mask): + mask = mask.float() + h, w = pred.size()[-2:] + N = h * w + x = pred.mean() + y = mask.mean() + sigma_x2 = ((pred - x) * (pred - x)).sum() / (N - 1 + 1e-20) + sigma_y2 = ((mask - y) * (mask - y)).sum() / (N - 1 + 1e-20) + sigma_xy = ((pred - x) * (mask - y)).sum() / (N - 1 + 1e-20) + + aplha = 4 * x * y * sigma_xy + beta = (x * x + y * y) * (sigma_x2 + sigma_y2) + + if aplha != 0: + Q = aplha / (beta + 1e-20) + elif aplha == 0 and beta == 0: + Q = 1.0 + else: + Q = 0 + return Q diff --git a/util/utils.py b/util/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bcef0fb86bdba890435162680d2268eea39bc36c --- /dev/null +++ b/util/utils.py @@ -0,0 +1,49 @@ +import torch +from torch.utils import model_zoo + +def to_array(feature_map): + if feature_map.shape[0] == 1: + feature_map = feature_map.squeeze(0).permute(1, 2, 0).detach().cpu().numpy() + else: + feature_map = feature_map.permute(0, 2, 3, 1).detach().cpu().numpy() + return feature_map + +def to_tensor(feature_map): + return torch.as_tensor(feature_map.transpose(0, 3, 1, 2), dtype=torch.float32) + +class AvgMeter(object): + def __init__(self, num=40): + self.num = num + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + self.losses = [] + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + self.losses.append(val) + + +url_TRACER = { + 'TE-0': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-0.pth', + 'TE-1': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-1.pth', + 'TE-2': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-2.pth', + 'TE-3': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-3.pth', + 'TE-4': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-4.pth', + 'TE-5': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-5.pth', + 'TE-6': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-6.pth', + 'TE-7': 'https://github.com/Karel911/TRACER/releases/download/v1.0/TRACER-Efficient-7.pth', +} + + +def load_pretrained(model_name): + state_dict = model_zoo.load_url(url_TRACER[model_name]) + + return state_dict diff --git a/w.o_edges/EfficientNet.py b/w.o_edges/EfficientNet.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6ba7adac7bfaa1055d0bbc8d2b39596f8e3b1d --- /dev/null +++ b/w.o_edges/EfficientNet.py @@ -0,0 +1,353 @@ +""" +Original author: lukemelas (github username) +Github repo: https://github.com/lukemelas/EfficientNet-PyTorch +With adjustments and added comments by workingcoder (github username). + +Reimplemented: Min Seok Lee and Wooseok Shin +""" + + + +import torch +from torch import nn +from torch.nn import functional as F +from util.effi_utils import ( + get_model_shape, + round_filters, + round_repeats, + drop_connect, + get_same_padding_conv2d, + get_model_params, + efficientnet_params, + load_pretrained_weights, + Swish, + MemoryEfficientSwish, + calculate_output_image_size +) + +from config import getConfig + +cfg = getConfig() + +VALID_MODELS = ( + 'efficientnet-b0', 'efficientnet-b1', 'efficientnet-b2', 'efficientnet-b3', + 'efficientnet-b4', 'efficientnet-b5', 'efficientnet-b6', 'efficientnet-b7', + 'efficientnet-b8', + + # Support the construction of 'efficientnet-l2' without pretrained weights + 'efficientnet-l2' +) + + +class MBConvBlock(nn.Module): + """Mobile Inverted Residual Bottleneck Block. + + Args: + block_args (namedtuple): BlockArgs, defined in utils.py. + global_params (namedtuple): GlobalParam, defined in utils.py. + image_size (tuple or list): [image_height, image_width]. + + References: + [1] https://arxiv.org/abs/1704.04861 (MobileNet v1) + [2] https://arxiv.org/abs/1801.04381 (MobileNet v2) + [3] https://arxiv.org/abs/1905.02244 (MobileNet v3) + """ + + def __init__(self, block_args, global_params, image_size=None): + super().__init__() + self._block_args = block_args + self._bn_mom = 1 - global_params.batch_norm_momentum # pytorch's difference from tensorflow + self._bn_eps = global_params.batch_norm_epsilon + self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1) + self.id_skip = block_args.id_skip # whether to use skip connection and drop connect + + # Expansion phase (Inverted Bottleneck) + inp = self._block_args.input_filters # number of input channels + oup = self._block_args.input_filters * self._block_args.expand_ratio # number of output channels + if self._block_args.expand_ratio != 1: + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._expand_conv = Conv2d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False) + self._bn0 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps) + # image_size = calculate_output_image_size(image_size, 1) <-- this wouldn't modify image_size + + # Depthwise convolution phase + k = self._block_args.kernel_size + s = self._block_args.stride + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._depthwise_conv = Conv2d( + in_channels=oup, out_channels=oup, groups=oup, # groups makes it depthwise + kernel_size=k, stride=s, bias=False) + self._bn1 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps) + image_size = calculate_output_image_size(image_size, s) + + # Squeeze and Excitation layer, if desired + if self.has_se: + Conv2d = get_same_padding_conv2d(image_size=(1, 1)) + num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio)) + self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1) + self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1) + + # Pointwise convolution phase + final_oup = self._block_args.output_filters + Conv2d = get_same_padding_conv2d(image_size=image_size) + self._project_conv = Conv2d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False) + self._bn2 = nn.BatchNorm2d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps) + self._swish = MemoryEfficientSwish() + + def forward(self, inputs, drop_connect_rate=None): + """MBConvBlock's forward function. + + Args: + inputs (tensor): Input tensor. + drop_connect_rate (bool): Drop connect rate (float, between 0 and 1). + + Returns: + Output of this block after processing. + """ + + # Expansion and Depthwise Convolution + x = inputs + if self._block_args.expand_ratio != 1: + x = self._expand_conv(inputs) + x = self._bn0(x) + x = self._swish(x) + + x = self._depthwise_conv(x) + x = self._bn1(x) + x = self._swish(x) + + # Squeeze and Excitation + if self.has_se: + x_squeezed = F.adaptive_avg_pool2d(x, 1) + x_squeezed = self._se_reduce(x_squeezed) + x_squeezed = self._swish(x_squeezed) + x_squeezed = self._se_expand(x_squeezed) + x = torch.sigmoid(x_squeezed) * x + + # Pointwise Convolution + x = self._project_conv(x) + x = self._bn2(x) + + # Skip connection and drop connect + input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters + if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters: + # The combination of skip connection and drop connect brings about stochastic depth. + if drop_connect_rate: + x = drop_connect(x, p=drop_connect_rate, training=self.training) + x = x + inputs # skip connection + return x + + def set_swish(self, memory_efficient=True): + """Sets swish function as memory efficient (for training) or standard (for export). + + Args: + memory_efficient (bool): Whether to use memory-efficient version of swish. + """ + self._swish = MemoryEfficientSwish() if memory_efficient else Swish() + + +class EfficientNet(nn.Module): + def __init__(self, blocks_args=None, global_params=None): + super().__init__() + assert isinstance(blocks_args, list), 'blocks_args should be a list' + assert len(blocks_args) > 0, 'block args must be greater than 0' + self._global_params = global_params + self._blocks_args = blocks_args + self.block_idx, self.channels = get_model_shape() + + # Batch norm parameters + bn_mom = 1 - self._global_params.batch_norm_momentum + bn_eps = self._global_params.batch_norm_epsilon + + # Get stem static or dynamic convolution depending on image size + image_size = global_params.image_size + Conv2d = get_same_padding_conv2d(image_size=image_size) + + # Stem + in_channels = 3 # rgb + out_channels = round_filters(32, self._global_params) # number of output channels + self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False) + self._bn0 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps) + image_size = calculate_output_image_size(image_size, 2) + + # Build blocks + self._blocks = nn.ModuleList([]) + for block_args in self._blocks_args: + + # Update block input and output filters based on depth multiplier. + block_args = block_args._replace( + input_filters=round_filters(block_args.input_filters, self._global_params), + output_filters=round_filters(block_args.output_filters, self._global_params), + num_repeat=round_repeats(block_args.num_repeat, self._global_params) + ) + + # The first block needs to take care of stride and filter size increase. + self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size)) + image_size = calculate_output_image_size(image_size, block_args.stride) + if block_args.num_repeat > 1: # modify block_args to keep same output size + block_args = block_args._replace(input_filters=block_args.output_filters, stride=1) + for _ in range(block_args.num_repeat - 1): + self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size)) + # image_size = calculate_output_image_size(image_size, block_args.stride) # stride = 1 + + self._swish = MemoryEfficientSwish() + + def set_swish(self, memory_efficient=True): + """Sets swish function as memory efficient (for training) or standard (for export). + + Args: + memory_efficient (bool): Whether to use memory-efficient version of swish. + + """ + self._swish = MemoryEfficientSwish() if memory_efficient else Swish() + for block in self._blocks: + block.set_swish(memory_efficient) + + def extract_endpoints(self, inputs): + endpoints = dict() + + # Stem + x = self._swish(self._bn0(self._conv_stem(inputs))) + prev_x = x + + # Blocks + for idx, block in enumerate(self._blocks): + drop_connect_rate = self._global_params.drop_connect_rate + if drop_connect_rate: + drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate + x = block(x, drop_connect_rate=drop_connect_rate) + if prev_x.size(2) > x.size(2): + endpoints['reduction_{}'.format(len(endpoints) + 1)] = prev_x + prev_x = x + + # Head + x = self._swish(self._bn1(self._conv_head(x))) + endpoints['reduction_{}'.format(len(endpoints) + 1)] = x + + return endpoints + + + def initial_conv(self, inputs): + # Stem + x = self._swish(self._bn0(self._conv_stem(inputs))) + + return x + + + def get_blocks(self, x, H, W): + # Blocks + for idx, block in enumerate(self._blocks): + drop_connect_rate = self._global_params.drop_connect_rate + if drop_connect_rate: + drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate + + x = block(x, drop_connect_rate=drop_connect_rate) + + if idx == self.block_idx[0]: + x1 = x.clone() + if idx == self.block_idx[1]: + x2 = x.clone() + if idx == self.block_idx[2]: + x3 = x.clone() + if idx == self.block_idx[3]: + x4 = x.clone() + + return (x1, x2, x3, x4) + + + @classmethod + def from_name(cls, model_name, in_channels=3, **override_params): + """create an efficientnet model according to name. + + Args: + model_name (str): Name for efficientnet. + in_channels (int): Input data's channel number. + override_params (other key word params): + Params to override model's global_params. + Optional key: + 'width_coefficient', 'depth_coefficient', + 'image_size', 'dropout_rate', + 'num_classes', 'batch_norm_momentum', + 'batch_norm_epsilon', 'drop_connect_rate', + 'depth_divisor', 'min_depth' + + Returns: + An efficientnet model. + """ + cls._check_model_name_is_valid(model_name) + blocks_args, global_params = get_model_params(model_name, override_params) + model = cls(blocks_args, global_params) + model._change_in_channels(in_channels) + return model + + @classmethod + def from_pretrained(cls, model_name, weights_path=None, advprop=False, + in_channels=3, num_classes=1000, **override_params): + """create an efficientnet model according to name. + + Args: + model_name (str): Name for efficientnet. + weights_path (None or str): + str: path to pretrained weights file on the local disk. + None: use pretrained weights downloaded from the Internet. + advprop (bool): + Whether to load pretrained weights + trained with advprop (valid when weights_path is None). + in_channels (int): Input data's channel number. + num_classes (int): + Number of categories for classification. + It controls the output size for final linear layer. + override_params (other key word params): + Params to override model's global_params. + Optional key: + 'width_coefficient', 'depth_coefficient', + 'image_size', 'dropout_rate', + 'batch_norm_momentum', + 'batch_norm_epsilon', 'drop_connect_rate', + 'depth_divisor', 'min_depth' + + Returns: + A pretrained TRACER-EfficientNet model. + """ + model = cls.from_name(model_name, num_classes=num_classes, **override_params) + load_pretrained_weights(model, model_name, weights_path=weights_path, advprop=advprop) + model._change_in_channels(in_channels) + return model + + @classmethod + def get_image_size(cls, model_name): + """Get the input image size for a given efficientnet model. + + Args: + model_name (str): Name for efficientnet. + + Returns: + Input image size (resolution). + """ + cls._check_model_name_is_valid(model_name) + _, _, res, _ = efficientnet_params(model_name) + return res + + @classmethod + def _check_model_name_is_valid(cls, model_name): + """Validates model name. + + Args: + model_name (str): Name for efficientnet. + + Returns: + bool: Is a valid name or not. + """ + if model_name not in VALID_MODELS: + raise ValueError('model_name should be one of: ' + ', '.join(VALID_MODELS)) + + def _change_in_channels(self, in_channels): + """Adjust model's first convolution layer to in_channels, if in_channels not equals 3. + + Args: + in_channels (int): Input data's channel number. + """ + if in_channels != 3: + Conv2d = get_same_padding_conv2d(image_size=self._global_params.image_size) + out_channels = round_filters(32, self._global_params) + self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False) diff --git a/w.o_edges/TRACER.py b/w.o_edges/TRACER.py new file mode 100644 index 0000000000000000000000000000000000000000..f2b4a8b7aed4f9a90e6ac212ed367cb17f3977ae --- /dev/null +++ b/w.o_edges/TRACER.py @@ -0,0 +1,57 @@ +""" +author: Min Seok Lee and Wooseok Shin +Github repo: https://github.com/Karel911/TRACER +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from model.EfficientNet import EfficientNet +from util.effi_utils import get_model_shape +from modules.att_modules import RFB_Block, aggregation, ObjectAttention + + +class TRACER(nn.Module): + def __init__(self, cfg): + super().__init__() + self.model = EfficientNet.from_pretrained(f'efficientnet-b{cfg.arch}', advprop=True) + self.block_idx, self.channels = get_model_shape() + + # Receptive Field Blocks + channels = [int(arg_c) for arg_c in cfg.RFB_aggregated_channel] + self.rfb2 = RFB_Block(self.channels[1], channels[0]) + self.rfb3 = RFB_Block(self.channels[2], channels[1]) + self.rfb4 = RFB_Block(self.channels[3], channels[2]) + + # Multi-level aggregation + self.agg = aggregation(channels) + + # Object Attention + self.ObjectAttention2 = ObjectAttention(channel=self.channels[1], kernel_size=3) + self.ObjectAttention1 = ObjectAttention(channel=self.channels[0], kernel_size=3) + + def forward(self, inputs): + B, C, H, W = inputs.size() + + # EfficientNet backbone Encoder + x = self.model.initial_conv(inputs) + features = self.model.get_blocks(x, H, W) + + x3_rfb = self.rfb2(features[1]) + x4_rfb = self.rfb3(features[2]) + x5_rfb = self.rfb4(features[3]) + + D_0 = self.agg(x5_rfb, x4_rfb, x3_rfb) + + ds_map0 = F.interpolate(D_0, scale_factor=8, mode='bilinear') + + D_1 = self.ObjectAttention2(D_0, features[1]) + ds_map1 = F.interpolate(D_1, scale_factor=8, mode='bilinear') + + ds_map = F.interpolate(D_1, scale_factor=2, mode='bilinear') + D_2 = self.ObjectAttention1(ds_map, features[0]) + ds_map2 = F.interpolate(D_2, scale_factor=4, mode='bilinear') + + final_map = (ds_map2 + ds_map1 + ds_map0) / 3 + + return torch.sigmoid(final_map), (torch.sigmoid(ds_map0), torch.sigmoid(ds_map1), torch.sigmoid(ds_map2)) \ No newline at end of file diff --git a/w.o_edges/dataloader.py b/w.o_edges/dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..2041c084952370223290508f124868ab9b237447 --- /dev/null +++ b/w.o_edges/dataloader.py @@ -0,0 +1,140 @@ +""" +author: Min Seok Lee and Wooseok Shin +Github repo: https://github.com/Karel911/TRACER +""" + +import cv2 +import glob +import torch +import numpy as np +import albumentations as albu +from pathlib import Path +from albumentations.pytorch.transforms import ToTensorV2 +from torch.utils.data import Dataset, DataLoader +from sklearn.model_selection import train_test_split + + +class DatasetGenerate(Dataset): + def __init__(self, img_folder, gt_folder, phase: str = 'train', transform=None, seed=None): + self.images = sorted(glob.glob(img_folder + '/*')) + self.gts = sorted(glob.glob(gt_folder + '/*')) + self.transform = transform + + train_images, val_images, train_gts, val_gts = train_test_split(self.images, self.gts, test_size=0.05, + random_state=seed) + if phase == 'train': + self.images = train_images + self.gts = train_gts + elif phase == 'val': + self.images = val_images + self.gts = val_gts + else: # Testset + pass + + def __getitem__(self, idx): + image = cv2.imread(self.images[idx]) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + mask = cv2.imread(self.gts[idx]) + mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) + + if self.transform is not None: + augmented = self.transform(image=image, masks=[mask]) + image = augmented['image'] + mask = np.expand_dims(augmented['masks'][0], axis=0) # (1, H, W) + mask = mask / 255.0 + + return image, mask + + def __len__(self): + return len(self.images) + + +class Test_DatasetGenerate(Dataset): + def __init__(self, img_folder, gt_folder, transform=None): + self.images = sorted(glob.glob(img_folder + '/*')) + self.gts = sorted(glob.glob(gt_folder + '/*')) + self.transform = transform + + def __getitem__(self, idx): + image_name = Path(self.images[idx]).stem + image = cv2.imread(self.images[idx]) + image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + original_size = image.shape[:2] + + if self.transform is not None: + augmented = self.transform(image=image) + image = augmented['image'] + + return image, self.gts[idx], original_size, image_name + + def __len__(self): + return len(self.images) + + +def get_loader(img_folder, gt_folder, phase: str, batch_size, shuffle, + num_workers, transform, seed=None): + if phase == 'test': + dataset = Test_DatasetGenerate(img_folder, gt_folder, transform) + data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers) + else: + dataset = DatasetGenerate(img_folder, gt_folder, phase, transform, seed) + data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, + drop_last=True) + + print(f'{phase} length : {len(dataset)}') + + return data_loader + + +def get_train_augmentation(img_size, ver): + if ver == 1: + transforms = albu.Compose([ + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + if ver == 2: + transforms = albu.Compose([ + albu.OneOf([ + albu.HorizontalFlip(), + albu.VerticalFlip(), + albu.RandomRotate90() + ], p=0.5), + albu.OneOf([ + albu.RandomContrast(), + albu.RandomGamma(), + albu.RandomBrightness(), + ], p=0.5), + albu.OneOf([ + albu.MotionBlur(blur_limit=5), + albu.MedianBlur(blur_limit=5), + albu.GaussianBlur(blur_limit=5), + albu.GaussNoise(var_limit=(5.0, 20.0)), + ], p=0.5), + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + return transforms + + +def get_test_augmentation(img_size): + transforms = albu.Compose([ + albu.Resize(img_size, img_size, always_apply=True), + albu.Normalize([0.485, 0.456, 0.406], + [0.229, 0.224, 0.225]), + ToTensorV2(), + ]) + return transforms + + +def gt_to_tensor(gt): + gt = cv2.imread(gt) + gt = cv2.cvtColor(gt, cv2.COLOR_BGR2GRAY) / 255.0 + gt = np.where(gt > 0.5, 1.0, 0.0) + gt = torch.tensor(gt, device='cuda', dtype=torch.float32) + gt = gt.unsqueeze(0).unsqueeze(1) + + return gt diff --git a/w.o_edges/trainer.py b/w.o_edges/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..6513115bfecde18877627e0e8d550618c75a2b24 --- /dev/null +++ b/w.o_edges/trainer.py @@ -0,0 +1,289 @@ +""" +author: Min Seok Lee and Wooseok Shin +Github repo: https://github.com/Karel911/TRACER +""" + +import os +import cv2 +import time +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from tqdm import tqdm +from dataloader import get_train_augmentation, get_test_augmentation, get_loader, gt_to_tensor +from util.utils import AvgMeter +from util.metrics import Evaluation_metrics +from util.losses import Optimizer, Scheduler, Criterion +from model.TRACER import TRACER + + +class Trainer(): + def __init__(self, args, save_path): + super(Trainer, self).__init__() + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.size = args.img_size + + self.tr_img_folder = os.path.join(args.data_path, args.dataset, 'Train/images/') + self.tr_gt_folder = os.path.join(args.data_path, args.dataset, 'Train/masks/') + + self.train_transform = get_train_augmentation(img_size=args.img_size, ver=args.aug_ver) + self.test_transform = get_test_augmentation(img_size=args.img_size) + + self.train_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, phase='train', + batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, + transform=self.train_transform, seed=args.seed) + self.val_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, phase='val', + batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, + transform=self.test_transform, seed=args.seed) + + # Network + self.model = TRACER(args).to(self.device) + + if args.multi_gpu: + self.model = nn.DataParallel(self.model).to(self.device) + + # Loss and Optimizer + self.criterion = Criterion(args) + self.optimizer = Optimizer(args, self.model) + self.scheduler = Scheduler(args, self.optimizer) + + # Train / Validate + min_loss = 1000 + early_stopping = 0 + t = time.time() + for epoch in range(1, args.epochs + 1): + self.epoch = epoch + train_loss, train_mae = self.training(args) + val_loss, val_mae = self.validate() + + if args.scheduler == 'Reduce': + self.scheduler.step(val_loss) + else: + self.scheduler.step() + + # Save models + if val_loss < min_loss: + early_stopping = 0 + best_epoch = epoch + best_mae = val_mae + min_loss = val_loss + torch.save(self.model.state_dict(), os.path.join(save_path, 'best_model.pth')) + print(f'-----------------SAVE:{best_epoch}epoch----------------') + else: + early_stopping += 1 + + if early_stopping == args.patience + 5: + break + + print(f'\nBest Val Epoch:{best_epoch} | Val Loss:{min_loss:.3f} | Val MAE:{best_mae:.3f} ' + f'time: {(time.time() - t) / 60:.3f}M') + + # Test time + datasets = ['DUTS', 'DUT-O', 'HKU-IS', 'ECSSD', 'PASCAL-S'] + for dataset in datasets: + args.dataset = dataset + test_loss, test_mae, test_maxf, test_avgf, test_s_m = self.test(args, os.path.join(save_path)) + + print( + f'Test Loss:{test_loss:.3f} | MAX_F:{test_maxf:.3f} | AVG_F:{test_avgf:.3f} | MAE:{test_mae:.3f} ' + f'| S_Measure:{test_s_m:.3f}, time: {time.time() - t:.3f}s') + + end = time.time() + print(f'Total Process time:{(end - t) / 60:.3f}Minute') + + def training(self, args): + self.model.train() + train_loss = AvgMeter() + train_mae = AvgMeter() + + for images, masks in tqdm(self.train_loader): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + masks = torch.tensor(masks, device=self.device, dtype=torch.float32) + + self.optimizer.zero_grad() + outputs, ds_map = self.model(images) + loss1 = self.criterion(outputs, masks) + loss2 = self.criterion(ds_map[0], masks) + loss3 = self.criterion(ds_map[1], masks) + loss4 = self.criterion(ds_map[2], masks) + + loss = loss1 + loss2 + loss3 + loss4 + + loss.backward() + nn.utils.clip_grad_norm_(self.model.parameters(), args.clipping) + self.optimizer.step() + + # Metric + mae = torch.mean(torch.abs(outputs - masks)) + + # log + train_loss.update(loss.item(), n=images.size(0)) + train_mae.update(mae.item(), n=images.size(0)) + + print(f'Epoch:[{self.epoch:03d}/{args.epochs:03d}]') + print(f'Train Loss:{train_loss.avg:.3f} | MAE:{train_mae.avg:.3f}') + + return train_loss.avg, train_mae.avg + + def validate(self): + self.model.eval() + val_loss = AvgMeter() + val_mae = AvgMeter() + + with torch.no_grad(): + for images, masks in tqdm(self.val_loader): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + masks = torch.tensor(masks, device=self.device, dtype=torch.float32) + + outputs, ds_map = self.model(images) + loss1 = self.criterion(outputs, masks) + loss2 = self.criterion(ds_map[0], masks) + loss3 = self.criterion(ds_map[1], masks) + loss4 = self.criterion(ds_map[2], masks) + + loss = loss1 + loss2 + loss3 + loss4 + + # Metric + mae = torch.mean(torch.abs(outputs - masks)) + + # log + val_loss.update(loss.item(), n=images.size(0)) + val_mae.update(mae.item(), n=images.size(0)) + + print(f'Valid Loss:{val_loss.avg:.3f} | MAE:{val_mae.avg:.3f}') + return val_loss.avg, val_mae.avg + + def test(self, args, save_path): + path = os.path.join(save_path, 'best_model.pth') + self.model.load_state_dict(torch.load(path)) + print('###### pre-trained Model restored #####') + + te_img_folder = os.path.join(args.data_path, args.dataset, 'Test/images/') + te_gt_folder = os.path.join(args.data_path, args.dataset, 'Test/masks/') + test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, phase='test', + batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, transform=self.test_transform) + + self.model.eval() + test_loss = AvgMeter() + test_mae = AvgMeter() + test_maxf = AvgMeter() + test_avgf = AvgMeter() + test_s_m = AvgMeter() + + Eval_tool = Evaluation_metrics(args.dataset, self.device) + + with torch.no_grad(): + for i, (images, masks, original_size, image_name) in enumerate(tqdm(test_loader)): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + + outputs, ds_map = self.model(images) + H, W = original_size + + for i in range(images.size(0)): + mask = gt_to_tensor(masks[i]) + + h, w = H[i].item(), W[i].item() + + output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear') + + loss = self.criterion(output, mask) + + # Metric + mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask) + + # log + test_loss.update(loss.item(), n=1) + test_mae.update(mae, n=1) + test_maxf.update(max_f, n=1) + test_avgf.update(avg_f, n=1) + test_s_m.update(s_score, n=1) + + test_loss = test_loss.avg + test_mae = test_mae.avg + test_maxf = test_maxf.avg + test_avgf = test_avgf.avg + test_s_m = test_s_m.avg + + return test_loss, test_mae, test_maxf, test_avgf, test_s_m + + +class Tester(): + def __init__(self, args, save_path): + super(Tester, self).__init__() + self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + self.test_transform = get_test_augmentation(img_size=args.img_size) + self.args = args + self.save_path = save_path + + # Network + self.model = self.model = TRACER(args).to(self.device) + if args.multi_gpu: + self.model = nn.DataParallel(self.model).to(self.device) + + path = os.path.join(save_path, 'best_model.pth') + self.model.load_state_dict(torch.load(path)) + print('###### pre-trained Model restored #####') + + self.criterion = Criterion(args) + + te_img_folder = os.path.join(args.data_path, args.dataset, 'Test/images/') + te_gt_folder = os.path.join(args.data_path, args.dataset, 'Test/masks/') + self.test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, phase='test', + batch_size=args.batch_size, shuffle=False, + num_workers=args.num_workers, transform=self.test_transform) + + if args.save_map is not None: + os.makedirs(os.path.join('mask', 'exp'+str(self.args.exp_num), self.args.dataset), exist_ok=True) + + def test(self): + self.model.eval() + test_loss = AvgMeter() + test_mae = AvgMeter() + test_maxf = AvgMeter() + test_avgf = AvgMeter() + test_s_m = AvgMeter() + t = time.time() + + Eval_tool = Evaluation_metrics(self.args.dataset, self.device) + + with torch.no_grad(): + for i, (images, masks, original_size, image_name) in enumerate(tqdm(self.test_loader)): + images = torch.tensor(images, device=self.device, dtype=torch.float32) + + outputs, ds_map = self.model(images) + H, W = original_size + + for i in range(images.size(0)): + mask = gt_to_tensor(masks[i]) + h, w = H[i].item(), W[i].item() + + output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear') + loss = self.criterion(output, mask) + + # Metric + mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask) + + # Save prediction map + if self.args.save_map is not None: + output = (output.squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type + cv2.imwrite(os.path.join('mask', 'exp'+str(self.args.exp_num), self.args.dataset, image_name[i]+'.png'), output) + + # log + test_loss.update(loss.item(), n=1) + test_mae.update(mae, n=1) + test_maxf.update(max_f, n=1) + test_avgf.update(avg_f, n=1) + test_s_m.update(s_score, n=1) + + test_loss = test_loss.avg + test_mae = test_mae.avg + test_maxf = test_maxf.avg + test_avgf = test_avgf.avg + test_s_m = test_s_m.avg + + print(f'Test Loss:{test_loss:.4f} | MAX_F:{test_maxf:.4f} | MAE:{test_mae:.4f} ' + f'| S_Measure:{test_s_m:.4f}, time: {time.time() - t:.3f}s') + + return test_loss, test_mae, test_maxf, test_avgf, test_s_m