├── .gitignore ├── README.md ├── api.py ├── assets ├── background │ └── background.jpg ├── sample_image │ ├── female.jpeg │ └── male.jpeg └── sample_video │ └── sample.mp4 ├── bg_remove.py ├── inference.py ├── output ├── male.png ├── sample.gif ├── sample.mp4 └── web_view.png ├── pretrained └── README.md ├── requirements.txt ├── src └── models │ ├── backbones │ ├── __init__.py │ ├── mobilenetv2.py │ └── wrapper.py │ └── modnet.py ├── web_requirements.txt └── web_solution ├── static └── js │ └── detection.js └── template └── home.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | pretrained/*.ckpt 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MODNet Background Remover 2 | 3 | ## Application 4 | 5 | A deep learning approach to remove background and adding new background image 6 | 7 | - Remove background from **images,videos & live webcam** 8 | - Adding new background to those **images,videos & webcam footage** 9 | 10 | ### Demo 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Before removing the backgroundAfter replacing the background with new image
Male.jpgMale.png
Before removing the background from videoAfter replacing the background with new image in this video
Video
29 | 30 | ### Web View 31 |
32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 |
Before removing the backgroundAfter removing the background
Female.jpegFemale.png
41 | 42 | ## Installation 43 | 44 | ### Python Version 45 | 46 | - Python == 3.8 47 | 48 | ### Virtual Environment 49 | 50 | #### Windows 51 | 52 | - `python -m venv venv` 53 | - `.\venv\Scripts\activate` 54 | - If any problem for scripts activation 55 | - Execute following command in administration mode 56 | - `Set-ExecutionPolicy Unrestricted -Force` 57 | - Later you can revert the change 58 | - `Set-ExecutionPolicy restricted -Force` 59 | 60 | #### Linux 61 | 62 | - `python -m venv venv` 63 | - `source venv/bin/activate` 64 | 65 | ### Library Installation 66 | 67 | - Library Install 68 | - `pip install --upgrade pip` 69 | - `pip install --upgrade setuptools` 70 | - `pip install -r requirements.txt` 71 | - To run in **web interface** 72 | - `pip install -r web_requirements.txt` 73 | 74 | ### Pretrained Weights Download 75 | - [Weights Detail](pretrained/README.md) 76 | 77 | 78 | ## Inference 79 | 80 | ### Image 81 | 82 | #### Single image 83 | 84 | It will generate the output file in **output/** folder 85 | 86 | - `python inference.py --image image_path` **[Without background image]** 87 | - `python inference.py --image image_path --background True` **[With background image]** 88 | - Example: 89 | - `python inference.py --image assets/sample_image/female.jpeg` 90 | - `python inference.py --image assets/sample_image/male.jpeg --background True` 91 | 92 | #### Folder of images 93 | 94 | It will generate the output file in **output/** folder 95 | 96 | - `python inference.py --folder folder_path` **[Without background image]** 97 | - `python inference.py --folder folder_path --background True` **[With background image]** 98 | - Example: 99 | - `python inference.py --folder assets/sample_image/` 100 | - `python inference.py --folder assets/sample_image/ --background True` 101 | 102 | ### Video 103 | 104 | It will generate the output file in **output/** folder 105 | 106 | - `python inference.py --video video_path` **[Without background image]** 107 | - `python inference.py --video video_path --background True` **[With background image]** 108 | - Example: 109 | - `python inference.py --video assets/sample_video/sample.mp4` 110 | - `python inference.py --video assets/sample_video/sample.mp4 --background True` 111 | 112 | ### Webcam 113 | 114 | - `python inference.py --webcam True` **[Without background image]** 115 | - `python inference.py --webcam True --background True` **[With background image]** 116 | 117 | ### Webinterface 118 | 119 | - `python api.py` 120 | - Click on this [link/localhost](http://127.0.0.1:8000) 121 | - Upload the image and wait 122 | 123 | ## Reference 124 | 125 | - [A Trimap-Free Solution for Portrait Matting in Real Time under Changing Scenes](https://github.com/ZHKKKe/MODNet) 126 | - Sample Female photo by Michael Dam on Unsplash 127 | - Sample Male photo by Erik Lucatero on Unsplash 128 | -------------------------------------------------------------------------------- /api.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import glob 4 | import time 5 | 6 | from flask import Flask, request, render_template, jsonify 7 | from flask_cors import CORS 8 | 9 | from werkzeug.utils import secure_filename 10 | 11 | from bg_remove import BGRemove 12 | 13 | 14 | root = os.path.split(os.path.abspath(__file__))[0] 15 | ckpt_image = 'pretrained/modnet_photographic_portrait_matting.ckpt' 16 | bg_remover = BGRemove(ckpt_image) 17 | 18 | ALLOWED_EXTENSIONS = set(['jpg', 'png', 'jpeg']) 19 | 20 | TEMPLATE_FOLDER = os.path.join(root, 'web_solution', 'template') 21 | STATIC_FOLDER = os.path.join(root, 'web_solution', 'static') 22 | STATIC_IMAGE_PATH = os.path.join(root, 'web_solution', 'static', 'images') 23 | 24 | UPLOAD_FOLDER = os.path.join(STATIC_IMAGE_PATH, 'test_images') 25 | RESULT_IMAGE = os.path.join(STATIC_IMAGE_PATH, 'result_images') 26 | 27 | make_directory = [os.makedirs(path,exist_ok=True) for path in [UPLOAD_FOLDER, RESULT_IMAGE]] 28 | 29 | app = Flask(__name__, template_folder=TEMPLATE_FOLDER, 30 | static_folder=STATIC_FOLDER) 31 | cors = CORS(app) 32 | 33 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 34 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 35 | app.config['SECRET_KEY'] = 'PrinceAPI' 36 | 37 | 38 | HOMEPAGE = 'home.html' 39 | 40 | 41 | def allowed_file(filename): 42 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 43 | 44 | 45 | @app.route('/', methods=['GET', 'POST']) 46 | def upload_file(): 47 | if request.method == 'POST': 48 | # check if the post request has the file part 49 | if 'files[]' not in request.files: 50 | resp = jsonify({'message': 'No file part in the request'}) 51 | resp.status_code = 400 52 | 53 | files = request.files.getlist('files[]') 54 | errors = {} 55 | success = False 56 | file = files[0] 57 | filename = "" 58 | 59 | if file and allowed_file(file.filename): 60 | ts = time.time() 61 | filename = f"{str(ts)}-{file.filename}" 62 | filename = secure_filename(filename) 63 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 64 | success = True 65 | else: 66 | errors['message'] = 'File type is not allowed' 67 | 68 | if success and errors: 69 | resp = jsonify({"filepath": f"{app.config['UPLOAD_FOLDER']}/{filename}", "filename": filename, 70 | 'message': 'Files successfully uploaded'}) 71 | resp.status_code = 206 72 | if success: 73 | resp = jsonify({"filepath": f"{app.config['UPLOAD_FOLDER']}/{filename}", "filename": filename, 74 | 'message': 'Files successfully uploaded'}) 75 | resp.status_code = 201 76 | else: 77 | resp = jsonify(errors) 78 | resp.status_code = 400 79 | resp.html = render_template(HOMEPAGE) 80 | return resp 81 | 82 | return render_template(HOMEPAGE) 83 | 84 | 85 | @app.route('/process/') 86 | def process(input_filename): 87 | image = os.path.join(UPLOAD_FOLDER, input_filename) 88 | output_filename = bg_remover.image( 89 | image, background=False, output=RESULT_IMAGE, save=True) 90 | 91 | return render_template(HOMEPAGE, input_filename=input_filename, output_filename=output_filename) 92 | 93 | 94 | if __name__ == '__main__': 95 | app.run(debug=False, host='0.0.0.0', port=8000) 96 | -------------------------------------------------------------------------------- /assets/background/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/assets/background/background.jpg -------------------------------------------------------------------------------- /assets/sample_image/female.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/assets/sample_image/female.jpeg -------------------------------------------------------------------------------- /assets/sample_image/male.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/assets/sample_image/male.jpeg -------------------------------------------------------------------------------- /assets/sample_video/sample.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/assets/sample_video/sample.mp4 -------------------------------------------------------------------------------- /bg_remove.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import copy 4 | import warnings 5 | 6 | import numpy as np 7 | import cv2 8 | 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | import torchvision.transforms as transforms 13 | 14 | from src.models.modnet import MODNet 15 | 16 | 17 | warnings.filterwarnings("ignore") 18 | 19 | 20 | class BGRemove(): 21 | # define hyper-parameters 22 | ref_size = 512 23 | 24 | # define image to tensor transform 25 | im_transform = transforms.Compose( 26 | [ 27 | transforms.ToTensor(), 28 | transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) 29 | ] 30 | ) 31 | device = 'cuda' if torch.cuda.is_available() else 'cpu' 32 | 33 | # create MODNet and load the pre-trained ckpt 34 | modnet = MODNet(backbone_pretrained=False) 35 | modnet = nn.DataParallel(modnet) 36 | if device == 'cuda': 37 | modnet = modnet.cuda() 38 | 39 | def __init__(self, ckpt_path): 40 | self.parameter_load(ckpt_path) 41 | 42 | def parameter_load(self, ckpt_path): 43 | BGRemove.modnet.load_state_dict( 44 | torch.load(ckpt_path, map_location=BGRemove.device)) 45 | BGRemove.modnet.eval() 46 | 47 | def file_load(self, filename): 48 | im = cv2.imread(filename) 49 | im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) 50 | if len(im.shape) == 2: 51 | im = im[:, :, None] 52 | if im.shape[2] == 1: 53 | im = np.repeat(im, 3, axis=2) 54 | elif im.shape[2] == 4: 55 | im = im[:, :, 0:3] 56 | 57 | return im 58 | 59 | def dir_check(self, path): 60 | os.makedirs(path, exist_ok=True) 61 | if not path.endswith('/'): 62 | path += '/' 63 | return path 64 | 65 | def pre_process(self, im): 66 | self.original_im = copy.deepcopy(im) 67 | 68 | # convert image to PyTorch tensor 69 | im = BGRemove.im_transform(im) 70 | 71 | # add mini-batch dim 72 | im = im[None, :, :, :] 73 | 74 | # resize image for input 75 | im_b, im_c, im_h, im_w = im.shape 76 | self.height, self.width = im_h, im_w 77 | 78 | if max(im_h, im_w) < BGRemove.ref_size or min(im_h, im_w) > BGRemove.ref_size: 79 | if im_w >= im_h: 80 | im_rh = BGRemove.ref_size 81 | im_rw = int(im_w / im_h * BGRemove.ref_size) 82 | elif im_w < im_h: 83 | im_rw = BGRemove.ref_size 84 | im_rh = int(im_h / im_w * BGRemove.ref_size) 85 | else: 86 | im_rh = im_h 87 | im_rw = im_w 88 | 89 | im_rw = im_rw - im_rw % 32 90 | im_rh = im_rh - im_rh % 32 91 | im = F.interpolate(im, size=(im_rh, im_rw), mode='area') 92 | if BGRemove.device == 'cuda': 93 | im = im.cuda() 94 | return im 95 | 96 | def post_process(self, mask_data, background=False, backgound_path='assets/background/background.jpg'): 97 | matte = F.interpolate(mask_data, size=( 98 | self.height, self.width), mode='area') 99 | matte = matte.repeat(1, 3, 1, 1) 100 | matte = matte[0].data.cpu().numpy().transpose(1, 2, 0) 101 | height, width, _ = matte.shape 102 | if background: 103 | back_image = self.file_load(backgound_path) 104 | back_image = cv2.resize( 105 | back_image, (width, height), cv2.INTER_AREA) 106 | else: 107 | back_image = np.full(self.original_im.shape, 255.0) 108 | 109 | self.alpha = np.uint8(matte[:, :, 0]*255) 110 | 111 | matte = matte * self.original_im + (1 - matte) * back_image 112 | return matte 113 | 114 | def image(self, filename, background=False, output='output/', save=True): 115 | output = self.dir_check(output) 116 | 117 | self.im_name = filename.split('/')[-1] 118 | im = self.file_load(filename) 119 | im = self.pre_process(im) 120 | _, _, matte = BGRemove.modnet(im, inference=False) 121 | matte = self.post_process(matte, background) 122 | 123 | if save: 124 | matte = np.uint8(matte) 125 | msg, name = self.save(matte, output, background) 126 | return name 127 | else: 128 | h, w, _ = matte.shape 129 | r_h, r_w = 720, int((w / h) * 720) 130 | image = cv2.resize(self.original_im, (r_w, r_h), cv2.INTER_AREA) 131 | matte = cv2.resize(matte, (r_w, r_h), cv2.INTER_AREA) 132 | 133 | full_image = np.uint8(np.concatenate((image, matte), axis=1)) 134 | self.save(full_image, output, background) 135 | exit_key = ord('q') 136 | while True: 137 | if cv2.waitKey(exit_key) & 255 == exit_key: 138 | cv2.destroyAllWindows() 139 | break 140 | cv2.imshow( 141 | 'MODNet - {} [Press "Q" To Exit]'.format(self.im_name), full_image) 142 | 143 | def video(self, filename, background=False, output='output/'): 144 | output = self.dir_check(output) 145 | 146 | output_name = filename.split('/')[-1] 147 | extension = output_name.split('.')[-1] 148 | output_name = output_name.replace(extension, 'mp4') 149 | 150 | fourcc = cv2.VideoWriter_fourcc(*'MP4V') 151 | 152 | cap = cv2.VideoCapture(filename) 153 | flag = 1 154 | if (cap.isOpened() == False): 155 | print("Error opening video stream or file") 156 | while (cap.isOpened()): 157 | ret, frame = cap.read() 158 | if flag: 159 | height, width, _ = frame.shape 160 | out = cv2.VideoWriter(output+output_name, 161 | fourcc, 20.0, (2*width, height)) 162 | flag = 0 163 | 164 | if ret: 165 | print('Video is processing..', end='\r') 166 | 167 | im = self.pre_process(frame) 168 | _, _, matte = BGRemove.modnet(im, inference=False) 169 | matte = np.uint8(self.post_process(matte, background)) 170 | full_image = np.concatenate((frame, matte), axis=1) 171 | full_image = np.uint8(cv2.resize( 172 | full_image, (2*width, height), cv2.INTER_AREA)) 173 | out.write(full_image) 174 | else: 175 | break 176 | cap.release() 177 | out.release() 178 | cv2.destroyAllWindows() 179 | 180 | def folder(self, foldername, background=False, output='output/'): 181 | output = self.dir_check(output) 182 | foldername = self.dir_check(foldername) 183 | 184 | for filename in os.listdir(foldername): 185 | try: 186 | self.im_name = filename 187 | im = self.file_load(foldername+filename) 188 | im = self.pre_process(im) 189 | _, _, matte = BGRemove.modnet(im, inference=False) 190 | matte = self.post_process(matte, background) 191 | status = self.save(matte, output, background) 192 | print(status) 193 | except: 194 | print('There is an error for {} file/folder'.format(foldername+filename)) 195 | 196 | def webcam(self, background=False): 197 | cap = cv2.VideoCapture(0) 198 | cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) 199 | cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) 200 | width, height = 455, 512 201 | 202 | exit_key = ord('q') 203 | while(True): 204 | _, frame_np = cap.read() 205 | frame_np = cv2.resize(frame_np, (width, height), cv2.INTER_AREA) 206 | im = self.pre_process(frame_np) 207 | _, _, matte = BGRemove.modnet(im, inference=False) 208 | processed_image = self.post_process(matte, background) 209 | 210 | full_image = np.concatenate((frame_np, processed_image), axis=1) 211 | full_image = np.uint8(cv2.resize( 212 | full_image, (2*width, height), cv2.INTER_AREA)) 213 | 214 | if cv2.waitKey(exit_key) & 255 == exit_key: 215 | cv2.destroyAllWindows() 216 | break 217 | cv2.imshow('MODNet - WebCam [Press "Q" To Exit]', full_image) 218 | 219 | def save(self, matte, output_path='output/', background=False): 220 | name = '.'.join(self.im_name.split('.')[:-1])+'.png' 221 | path = os.path.join(output_path, name) 222 | 223 | if background: 224 | try: 225 | matte = cv2.cvtColor(matte, cv2.COLOR_RGB2BGR) 226 | cv2.imwrite(path, matte) 227 | return "Successfully saved {}".format(path), name 228 | except: 229 | return "Error while saving {}".format(path), '' 230 | else: 231 | w, h, _ = matte.shape 232 | png_image = np.zeros((w, h, 4)) 233 | png_image[:, :, :3] = matte 234 | png_image[:, :, 3] = self.alpha 235 | png_image = png_image.astype(np.uint8) 236 | try: 237 | png_image = cv2.cvtColor(png_image, cv2.COLOR_RGBA2BGRA) 238 | cv2.imwrite(path, png_image, [ 239 | int(cv2.IMWRITE_PNG_COMPRESSION), 9]) 240 | return "Successfully saved {}".format(path), name 241 | except: 242 | return "Error while saving {}".format(path), '' 243 | -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from bg_remove import BGRemove 3 | 4 | if __name__ == "__main__": 5 | parser = argparse.ArgumentParser() 6 | parser.add_argument('--ckpt_image', type=str, default='pretrained/modnet_photographic_portrait_matting.ckpt', 7 | required=False, help='Checkpoint path') 8 | parser.add_argument('--ckpt_video', type=str, default='pretrained/modnet_webcam_portrait_matting.ckpt', 9 | required=False, help='Checkpoint path') 10 | parser.add_argument('--image', type=str, default='', 11 | required=False, help='Inference image filename') 12 | parser.add_argument('--video', type=str, default='', 13 | required=False, help='Inference image filename') 14 | parser.add_argument('--webcam', type=bool, default=False, 15 | required=False, help='Realtime webcam') 16 | parser.add_argument('--folder', type=str, default='assets/sample_image', 17 | required=False, help='Inference images foldername') 18 | parser.add_argument('--background', type=bool, default=False, 19 | required=False, help='Background image adding') 20 | 21 | args = parser.parse_args() 22 | try: 23 | if args.webcam or args.video: 24 | bg_remover = BGRemove(args.ckpt_video) 25 | else: 26 | bg_remover = BGRemove(args.ckpt_image) 27 | 28 | if args.image: 29 | bg_remover.image(args.image, background=args.background) 30 | elif args.video: 31 | bg_remover.video(args.video, background=args.background) 32 | elif args.webcam: 33 | bg_remover.webcam(background=args.background) 34 | else: 35 | bg_remover.folder(args.folder, background=args.background) 36 | 37 | except Exception as Err: 38 | print("Erro happend {}".format(Err)) 39 | -------------------------------------------------------------------------------- /output/male.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/output/male.png -------------------------------------------------------------------------------- /output/sample.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/output/sample.gif -------------------------------------------------------------------------------- /output/sample.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/output/sample.mp4 -------------------------------------------------------------------------------- /output/web_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mazhar004/MODNet-BGRemover/75d30850430b506776ce3f4774d209ef2064ffdf/output/web_view.png -------------------------------------------------------------------------------- /pretrained/README.md: -------------------------------------------------------------------------------- 1 | ## MODNet - Pre-Trained Models 2 | ### This folder is the pretrained models of MODNet: 3 | - You can download them from this [link](https://drive.google.com/file/d/11SBrkihQhtitVLqCKPW8mdQM2T1G0LTE/view?usp=sharing) 4 | - Extract It and copy the following files in **MODNet-BGRemover/pretrained** folder: 5 | - modnet_photographic_portrait_matting.ckpt 6 | - modnet_webcam_portrait_matting.ckpt -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy~=1.22 2 | opencv-python~=4.5.1.48 3 | torch~=1.7.1 4 | torchvision~=0.2.2.post3 5 | Pillow~=6.2.2 -------------------------------------------------------------------------------- /src/models/backbones/__init__.py: -------------------------------------------------------------------------------- 1 | from .wrapper import * 2 | 3 | 4 | #------------------------------------------------------------------------------ 5 | # Replaceable Backbones 6 | #------------------------------------------------------------------------------ 7 | 8 | SUPPORTED_BACKBONES = { 9 | 'mobilenetv2': MobileNetV2Backbone, 10 | } 11 | -------------------------------------------------------------------------------- /src/models/backbones/mobilenetv2.py: -------------------------------------------------------------------------------- 1 | """ This file is adapted from https://github.com/thuyngch/Human-Segmentation-PyTorch""" 2 | 3 | import math 4 | import json 5 | from functools import reduce 6 | 7 | import torch 8 | from torch import nn 9 | 10 | 11 | #------------------------------------------------------------------------------ 12 | # Useful functions 13 | #------------------------------------------------------------------------------ 14 | 15 | def _make_divisible(v, divisor, min_value=None): 16 | if min_value is None: 17 | min_value = divisor 18 | new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) 19 | # Make sure that round down does not go down by more than 10%. 20 | if new_v < 0.9 * v: 21 | new_v += divisor 22 | return new_v 23 | 24 | 25 | def conv_bn(inp, oup, stride): 26 | return nn.Sequential( 27 | nn.Conv2d(inp, oup, 3, stride, 1, bias=False), 28 | nn.BatchNorm2d(oup), 29 | nn.ReLU6(inplace=True) 30 | ) 31 | 32 | 33 | def conv_1x1_bn(inp, oup): 34 | return nn.Sequential( 35 | nn.Conv2d(inp, oup, 1, 1, 0, bias=False), 36 | nn.BatchNorm2d(oup), 37 | nn.ReLU6(inplace=True) 38 | ) 39 | 40 | 41 | #------------------------------------------------------------------------------ 42 | # Class of Inverted Residual block 43 | #------------------------------------------------------------------------------ 44 | 45 | class InvertedResidual(nn.Module): 46 | def __init__(self, inp, oup, stride, expansion, dilation=1): 47 | super(InvertedResidual, self).__init__() 48 | self.stride = stride 49 | assert stride in [1, 2] 50 | 51 | hidden_dim = round(inp * expansion) 52 | self.use_res_connect = self.stride == 1 and inp == oup 53 | 54 | if expansion == 1: 55 | self.conv = nn.Sequential( 56 | # dw 57 | nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, dilation=dilation, bias=False), 58 | nn.BatchNorm2d(hidden_dim), 59 | nn.ReLU6(inplace=True), 60 | # pw-linear 61 | nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), 62 | nn.BatchNorm2d(oup), 63 | ) 64 | else: 65 | self.conv = nn.Sequential( 66 | # pw 67 | nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), 68 | nn.BatchNorm2d(hidden_dim), 69 | nn.ReLU6(inplace=True), 70 | # dw 71 | nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, dilation=dilation, bias=False), 72 | nn.BatchNorm2d(hidden_dim), 73 | nn.ReLU6(inplace=True), 74 | # pw-linear 75 | nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), 76 | nn.BatchNorm2d(oup), 77 | ) 78 | 79 | def forward(self, x): 80 | if self.use_res_connect: 81 | return x + self.conv(x) 82 | else: 83 | return self.conv(x) 84 | 85 | 86 | #------------------------------------------------------------------------------ 87 | # Class of MobileNetV2 88 | #------------------------------------------------------------------------------ 89 | 90 | class MobileNetV2(nn.Module): 91 | def __init__(self, in_channels, alpha=1.0, expansion=6, num_classes=1000): 92 | super(MobileNetV2, self).__init__() 93 | self.in_channels = in_channels 94 | self.num_classes = num_classes 95 | input_channel = 32 96 | last_channel = 1280 97 | interverted_residual_setting = [ 98 | # t, c, n, s 99 | [1 , 16, 1, 1], 100 | [expansion, 24, 2, 2], 101 | [expansion, 32, 3, 2], 102 | [expansion, 64, 4, 2], 103 | [expansion, 96, 3, 1], 104 | [expansion, 160, 3, 2], 105 | [expansion, 320, 1, 1], 106 | ] 107 | 108 | # building first layer 109 | input_channel = _make_divisible(input_channel*alpha, 8) 110 | self.last_channel = _make_divisible(last_channel*alpha, 8) if alpha > 1.0 else last_channel 111 | self.features = [conv_bn(self.in_channels, input_channel, 2)] 112 | 113 | # building inverted residual blocks 114 | for t, c, n, s in interverted_residual_setting: 115 | output_channel = _make_divisible(int(c*alpha), 8) 116 | for i in range(n): 117 | if i == 0: 118 | self.features.append(InvertedResidual(input_channel, output_channel, s, expansion=t)) 119 | else: 120 | self.features.append(InvertedResidual(input_channel, output_channel, 1, expansion=t)) 121 | input_channel = output_channel 122 | 123 | # building last several layers 124 | self.features.append(conv_1x1_bn(input_channel, self.last_channel)) 125 | 126 | # make it nn.Sequential 127 | self.features = nn.Sequential(*self.features) 128 | 129 | # building classifier 130 | if self.num_classes is not None: 131 | self.classifier = nn.Sequential( 132 | nn.Dropout(0.2), 133 | nn.Linear(self.last_channel, num_classes), 134 | ) 135 | 136 | # Initialize weights 137 | self._init_weights() 138 | 139 | def forward(self, x, feature_names=None): 140 | # Stage1 141 | x = reduce(lambda x, n: self.features[n](x), list(range(0,2)), x) 142 | # Stage2 143 | x = reduce(lambda x, n: self.features[n](x), list(range(2,4)), x) 144 | # Stage3 145 | x = reduce(lambda x, n: self.features[n](x), list(range(4,7)), x) 146 | # Stage4 147 | x = reduce(lambda x, n: self.features[n](x), list(range(7,14)), x) 148 | # Stage5 149 | x = reduce(lambda x, n: self.features[n](x), list(range(14,19)), x) 150 | 151 | # Classification 152 | if self.num_classes is not None: 153 | x = x.mean(dim=(2,3)) 154 | x = self.classifier(x) 155 | 156 | # Output 157 | return x 158 | 159 | def _load_pretrained_model(self, pretrained_file): 160 | pretrain_dict = torch.load(pretrained_file, map_location='cpu') 161 | model_dict = {} 162 | state_dict = self.state_dict() 163 | print("[MobileNetV2] Loading pretrained model...") 164 | for k, v in pretrain_dict.items(): 165 | if k in state_dict: 166 | model_dict[k] = v 167 | else: 168 | print(k, "is ignored") 169 | state_dict.update(model_dict) 170 | self.load_state_dict(state_dict) 171 | 172 | def _init_weights(self): 173 | for m in self.modules(): 174 | if isinstance(m, nn.Conv2d): 175 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 176 | m.weight.data.normal_(0, math.sqrt(2. / n)) 177 | if m.bias is not None: 178 | m.bias.data.zero_() 179 | elif isinstance(m, nn.BatchNorm2d): 180 | m.weight.data.fill_(1) 181 | m.bias.data.zero_() 182 | elif isinstance(m, nn.Linear): 183 | n = m.weight.size(1) 184 | m.weight.data.normal_(0, 0.01) 185 | m.bias.data.zero_() 186 | -------------------------------------------------------------------------------- /src/models/backbones/wrapper.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import reduce 3 | 4 | import torch 5 | import torch.nn as nn 6 | 7 | from .mobilenetv2 import MobileNetV2 8 | 9 | 10 | class BaseBackbone(nn.Module): 11 | """ Superclass of Replaceable Backbone Model for Semantic Estimation 12 | """ 13 | 14 | def __init__(self, in_channels): 15 | super(BaseBackbone, self).__init__() 16 | self.in_channels = in_channels 17 | 18 | self.model = None 19 | self.enc_channels = [] 20 | 21 | def forward(self, x): 22 | raise NotImplementedError 23 | 24 | def load_pretrained_ckpt(self): 25 | raise NotImplementedError 26 | 27 | 28 | class MobileNetV2Backbone(BaseBackbone): 29 | """ MobileNetV2 Backbone 30 | """ 31 | 32 | def __init__(self, in_channels): 33 | super(MobileNetV2Backbone, self).__init__(in_channels) 34 | 35 | self.model = MobileNetV2(self.in_channels, alpha=1.0, expansion=6, num_classes=None) 36 | self.enc_channels = [16, 24, 32, 96, 1280] 37 | 38 | def forward(self, x): 39 | x = reduce(lambda x, n: self.model.features[n](x), list(range(0, 2)), x) 40 | enc2x = x 41 | x = reduce(lambda x, n: self.model.features[n](x), list(range(2, 4)), x) 42 | enc4x = x 43 | x = reduce(lambda x, n: self.model.features[n](x), list(range(4, 7)), x) 44 | enc8x = x 45 | x = reduce(lambda x, n: self.model.features[n](x), list(range(7, 14)), x) 46 | enc16x = x 47 | x = reduce(lambda x, n: self.model.features[n](x), list(range(14, 19)), x) 48 | enc32x = x 49 | return [enc2x, enc4x, enc8x, enc16x, enc32x] 50 | 51 | def load_pretrained_ckpt(self): 52 | # the pre-trained model is provided by https://github.com/thuyngch/Human-Segmentation-PyTorch 53 | ckpt_path = './pretrained/mobilenetv2_human_seg.ckpt' 54 | if not os.path.exists(ckpt_path): 55 | print('cannot find the pretrained mobilenetv2 backbone') 56 | exit() 57 | 58 | ckpt = torch.load(ckpt_path) 59 | self.model.load_state_dict(ckpt) 60 | -------------------------------------------------------------------------------- /src/models/modnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from .backbones import SUPPORTED_BACKBONES 6 | 7 | 8 | #------------------------------------------------------------------------------ 9 | # MODNet Basic Modules 10 | #------------------------------------------------------------------------------ 11 | 12 | class IBNorm(nn.Module): 13 | """ Combine Instance Norm and Batch Norm into One Layer 14 | """ 15 | 16 | def __init__(self, in_channels): 17 | super(IBNorm, self).__init__() 18 | in_channels = in_channels 19 | self.bnorm_channels = int(in_channels / 2) 20 | self.inorm_channels = in_channels - self.bnorm_channels 21 | 22 | self.bnorm = nn.BatchNorm2d(self.bnorm_channels, affine=True) 23 | self.inorm = nn.InstanceNorm2d(self.inorm_channels, affine=False) 24 | 25 | def forward(self, x): 26 | bn_x = self.bnorm(x[:, :self.bnorm_channels, ...].contiguous()) 27 | in_x = self.inorm(x[:, self.bnorm_channels:, ...].contiguous()) 28 | 29 | return torch.cat((bn_x, in_x), 1) 30 | 31 | 32 | class Conv2dIBNormRelu(nn.Module): 33 | """ Convolution + IBNorm + ReLu 34 | """ 35 | 36 | def __init__(self, in_channels, out_channels, kernel_size, 37 | stride=1, padding=0, dilation=1, groups=1, bias=True, 38 | with_ibn=True, with_relu=True): 39 | super(Conv2dIBNormRelu, self).__init__() 40 | 41 | layers = [ 42 | nn.Conv2d(in_channels, out_channels, kernel_size, 43 | stride=stride, padding=padding, dilation=dilation, 44 | groups=groups, bias=bias) 45 | ] 46 | 47 | if with_ibn: 48 | layers.append(IBNorm(out_channels)) 49 | if with_relu: 50 | layers.append(nn.ReLU(inplace=True)) 51 | 52 | self.layers = nn.Sequential(*layers) 53 | 54 | def forward(self, x): 55 | return self.layers(x) 56 | 57 | 58 | class SEBlock(nn.Module): 59 | """ SE Block Proposed in https://arxiv.org/pdf/1709.01507.pdf 60 | """ 61 | 62 | def __init__(self, in_channels, out_channels, reduction=1): 63 | super(SEBlock, self).__init__() 64 | self.pool = nn.AdaptiveAvgPool2d(1) 65 | self.fc = nn.Sequential( 66 | nn.Linear(in_channels, int(in_channels // reduction), bias=False), 67 | nn.ReLU(inplace=True), 68 | nn.Linear(int(in_channels // reduction), out_channels, bias=False), 69 | nn.Sigmoid() 70 | ) 71 | 72 | def forward(self, x): 73 | b, c, _, _ = x.size() 74 | w = self.pool(x).view(b, c) 75 | w = self.fc(w).view(b, c, 1, 1) 76 | 77 | return x * w.expand_as(x) 78 | 79 | 80 | #------------------------------------------------------------------------------ 81 | # MODNet Branches 82 | #------------------------------------------------------------------------------ 83 | 84 | class LRBranch(nn.Module): 85 | """ Low Resolution Branch of MODNet 86 | """ 87 | 88 | def __init__(self, backbone): 89 | super(LRBranch, self).__init__() 90 | 91 | enc_channels = backbone.enc_channels 92 | 93 | self.backbone = backbone 94 | self.se_block = SEBlock(enc_channels[4], enc_channels[4], reduction=4) 95 | self.conv_lr16x = Conv2dIBNormRelu(enc_channels[4], enc_channels[3], 5, stride=1, padding=2) 96 | self.conv_lr8x = Conv2dIBNormRelu(enc_channels[3], enc_channels[2], 5, stride=1, padding=2) 97 | self.conv_lr = Conv2dIBNormRelu(enc_channels[2], 1, kernel_size=3, stride=2, padding=1, with_ibn=False, with_relu=False) 98 | 99 | def forward(self, img, inference): 100 | enc_features = self.backbone.forward(img) 101 | enc2x, enc4x, enc32x = enc_features[0], enc_features[1], enc_features[4] 102 | 103 | enc32x = self.se_block(enc32x) 104 | lr16x = F.interpolate(enc32x, scale_factor=2, mode='bilinear', align_corners=False) 105 | lr16x = self.conv_lr16x(lr16x) 106 | lr8x = F.interpolate(lr16x, scale_factor=2, mode='bilinear', align_corners=False) 107 | lr8x = self.conv_lr8x(lr8x) 108 | 109 | pred_semantic = None 110 | if not inference: 111 | lr = self.conv_lr(lr8x) 112 | pred_semantic = torch.sigmoid(lr) 113 | 114 | return pred_semantic, lr8x, [enc2x, enc4x] 115 | 116 | 117 | class HRBranch(nn.Module): 118 | """ High Resolution Branch of MODNet 119 | """ 120 | 121 | def __init__(self, hr_channels, enc_channels): 122 | super(HRBranch, self).__init__() 123 | 124 | self.tohr_enc2x = Conv2dIBNormRelu(enc_channels[0], hr_channels, 1, stride=1, padding=0) 125 | self.conv_enc2x = Conv2dIBNormRelu(hr_channels + 3, hr_channels, 3, stride=2, padding=1) 126 | 127 | self.tohr_enc4x = Conv2dIBNormRelu(enc_channels[1], hr_channels, 1, stride=1, padding=0) 128 | self.conv_enc4x = Conv2dIBNormRelu(2 * hr_channels, 2 * hr_channels, 3, stride=1, padding=1) 129 | 130 | self.conv_hr4x = nn.Sequential( 131 | Conv2dIBNormRelu(3 * hr_channels + 3, 2 * hr_channels, 3, stride=1, padding=1), 132 | Conv2dIBNormRelu(2 * hr_channels, 2 * hr_channels, 3, stride=1, padding=1), 133 | Conv2dIBNormRelu(2 * hr_channels, hr_channels, 3, stride=1, padding=1), 134 | ) 135 | 136 | self.conv_hr2x = nn.Sequential( 137 | Conv2dIBNormRelu(2 * hr_channels, 2 * hr_channels, 3, stride=1, padding=1), 138 | Conv2dIBNormRelu(2 * hr_channels, hr_channels, 3, stride=1, padding=1), 139 | Conv2dIBNormRelu(hr_channels, hr_channels, 3, stride=1, padding=1), 140 | Conv2dIBNormRelu(hr_channels, hr_channels, 3, stride=1, padding=1), 141 | ) 142 | 143 | self.conv_hr = nn.Sequential( 144 | Conv2dIBNormRelu(hr_channels + 3, hr_channels, 3, stride=1, padding=1), 145 | Conv2dIBNormRelu(hr_channels, 1, kernel_size=1, stride=1, padding=0, with_ibn=False, with_relu=False), 146 | ) 147 | 148 | def forward(self, img, enc2x, enc4x, lr8x, inference): 149 | img2x = F.interpolate(img, scale_factor=1/2, mode='bilinear', align_corners=False) 150 | img4x = F.interpolate(img, scale_factor=1/4, mode='bilinear', align_corners=False) 151 | 152 | enc2x = self.tohr_enc2x(enc2x) 153 | hr4x = self.conv_enc2x(torch.cat((img2x, enc2x), dim=1)) 154 | 155 | enc4x = self.tohr_enc4x(enc4x) 156 | hr4x = self.conv_enc4x(torch.cat((hr4x, enc4x), dim=1)) 157 | 158 | lr4x = F.interpolate(lr8x, scale_factor=2, mode='bilinear', align_corners=False) 159 | hr4x = self.conv_hr4x(torch.cat((hr4x, lr4x, img4x), dim=1)) 160 | 161 | hr2x = F.interpolate(hr4x, scale_factor=2, mode='bilinear', align_corners=False) 162 | hr2x = self.conv_hr2x(torch.cat((hr2x, enc2x), dim=1)) 163 | 164 | pred_detail = None 165 | if not inference: 166 | hr = F.interpolate(hr2x, scale_factor=2, mode='bilinear', align_corners=False) 167 | hr = self.conv_hr(torch.cat((hr, img), dim=1)) 168 | pred_detail = torch.sigmoid(hr) 169 | 170 | return pred_detail, hr2x 171 | 172 | 173 | class FusionBranch(nn.Module): 174 | """ Fusion Branch of MODNet 175 | """ 176 | 177 | def __init__(self, hr_channels, enc_channels): 178 | super(FusionBranch, self).__init__() 179 | self.conv_lr4x = Conv2dIBNormRelu(enc_channels[2], hr_channels, 5, stride=1, padding=2) 180 | 181 | self.conv_f2x = Conv2dIBNormRelu(2 * hr_channels, hr_channels, 3, stride=1, padding=1) 182 | self.conv_f = nn.Sequential( 183 | Conv2dIBNormRelu(hr_channels + 3, int(hr_channels / 2), 3, stride=1, padding=1), 184 | Conv2dIBNormRelu(int(hr_channels / 2), 1, 1, stride=1, padding=0, with_ibn=False, with_relu=False), 185 | ) 186 | 187 | def forward(self, img, lr8x, hr2x): 188 | lr4x = F.interpolate(lr8x, scale_factor=2, mode='bilinear', align_corners=False) 189 | lr4x = self.conv_lr4x(lr4x) 190 | lr2x = F.interpolate(lr4x, scale_factor=2, mode='bilinear', align_corners=False) 191 | 192 | f2x = self.conv_f2x(torch.cat((lr2x, hr2x), dim=1)) 193 | f = F.interpolate(f2x, scale_factor=2, mode='bilinear', align_corners=False) 194 | f = self.conv_f(torch.cat((f, img), dim=1)) 195 | pred_matte = torch.sigmoid(f) 196 | 197 | return pred_matte 198 | 199 | 200 | #------------------------------------------------------------------------------ 201 | # MODNet 202 | #------------------------------------------------------------------------------ 203 | 204 | class MODNet(nn.Module): 205 | """ Architecture of MODNet 206 | """ 207 | 208 | def __init__(self, in_channels=3, hr_channels=32, backbone_arch='mobilenetv2', backbone_pretrained=True): 209 | super(MODNet, self).__init__() 210 | 211 | self.in_channels = in_channels 212 | self.hr_channels = hr_channels 213 | self.backbone_arch = backbone_arch 214 | self.backbone_pretrained = backbone_pretrained 215 | 216 | self.backbone = SUPPORTED_BACKBONES[self.backbone_arch](self.in_channels) 217 | 218 | self.lr_branch = LRBranch(self.backbone) 219 | self.hr_branch = HRBranch(self.hr_channels, self.backbone.enc_channels) 220 | self.f_branch = FusionBranch(self.hr_channels, self.backbone.enc_channels) 221 | 222 | for m in self.modules(): 223 | if isinstance(m, nn.Conv2d): 224 | self._init_conv(m) 225 | elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.InstanceNorm2d): 226 | self._init_norm(m) 227 | 228 | if self.backbone_pretrained: 229 | self.backbone.load_pretrained_ckpt() 230 | 231 | def forward(self, img, inference): 232 | pred_semantic, lr8x, [enc2x, enc4x] = self.lr_branch(img, inference) 233 | pred_detail, hr2x = self.hr_branch(img, enc2x, enc4x, lr8x, inference) 234 | pred_matte = self.f_branch(img, lr8x, hr2x) 235 | 236 | return pred_semantic, pred_detail, pred_matte 237 | 238 | def freeze_norm(self): 239 | norm_types = [nn.BatchNorm2d, nn.InstanceNorm2d] 240 | for m in self.modules(): 241 | for n in norm_types: 242 | if isinstance(m, n): 243 | m.eval() 244 | continue 245 | 246 | def _init_conv(self, conv): 247 | nn.init.kaiming_uniform_( 248 | conv.weight, a=0, mode='fan_in', nonlinearity='relu') 249 | if conv.bias is not None: 250 | nn.init.constant_(conv.bias, 0) 251 | 252 | def _init_norm(self, norm): 253 | if norm.weight is not None: 254 | nn.init.constant_(norm.weight, 1) 255 | nn.init.constant_(norm.bias, 0) 256 | -------------------------------------------------------------------------------- /web_requirements.txt: -------------------------------------------------------------------------------- 1 | Flask~=2.1.1 2 | Flask-Cors~=3.0.10 3 | Werkzeug~=2.1.1 -------------------------------------------------------------------------------- /web_solution/static/js/detection.js: -------------------------------------------------------------------------------- 1 | var API_URL = "http://0.0.0.0:8000/"; 2 | 3 | $(document).ready(function () { 4 | $('#customFile').change(function () { 5 | let fileName = $(this).val().split('\\').pop(); 6 | document.getElementById('UploadLabel').innerHTML = fileName 7 | }); 8 | }); 9 | 10 | function upload() 11 | { 12 | 13 | console.log(document.getElementById('customFile')) 14 | var form_data = new FormData(); 15 | var ins = document.getElementById('customFile').files.length; 16 | console.log("ins is : ", ins, " files : ", document.getElementById('customFile').files[0]); 17 | if (ins == 0) { 18 | $('#msg').html('Select at least one file'); 19 | return; 20 | } 21 | 22 | // for (var x = 0; x < ins; x++) { 23 | form_data.append("files[]", document.getElementById('customFile').files[0]); 24 | // } 25 | console.log("Form Data : ", form_data) 26 | $.ajax({ 27 | url: '/', // point to server-side URL 28 | dataType: 'json', // what to expect back from server 29 | cache: false, 30 | contentType: false, 31 | processData: false, 32 | data: form_data, 33 | type: 'post', 34 | success: function (response) { // display success response 35 | axios.post(API_URL + '/', { 36 | filelocation: response.filepath 37 | }) 38 | if (response.filename) 39 | { 40 | for (var x = 0; x < 100000; x++) 41 | { 42 | console.log(document.getElementById('customFile')) 43 | } 44 | window.location = "/process/"+response.filename; 45 | } 46 | } 47 | 48 | }); 49 | 50 | 51 | 52 | } -------------------------------------------------------------------------------- /web_solution/template/home.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | Object Detection 19 | 20 | 21 | 22 |
23 |
24 |
25 |
26 |
27 | 28 | 29 |
30 |
31 | 32 |
33 |
34 | 35 | 36 |
37 | {% if output_filename %} 38 |
39 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 50 | 52 | 53 | 54 |
Before Background RemoveAfter Background Remove
Actual ImageDetected Image
55 | 56 | {% endif %} 57 | 58 | 59 | --------------------------------------------------------------------------------