Code Monkey home page Code Monkey logo

louisyuzhe / car-damage-detector Goto Github PK

View Code? Open in Web Editor NEW
58.0 5.0 40.0 83.4 MB

Mask R-CNN Model to detect the area of damage on a car. The rationale for such a model is that it can be used by insurance companies for faster processing of claims if users can upload pics and they can assess damage from them. This model can also be used by lenders if they are underwriting a car loan especially for a used car.

License: Other

Jupyter Notebook 93.49% Python 6.51%
mask-rcnn rcnn-model machine-learning convolutional-neural-networks deep-learning ms-coco car-damage-detector applied-machine-learning

car-damage-detector's Introduction

Mask R-CNN for Car Damage Detection and Segmentation

This is an implementation of Mask R-CNN on Python 3, Keras, and TensorFlow. The model generates bounding boxes and segmentation masks for each instance of car in the image. It's based on Feature Pyramid Network (FPN) and a ResNet50/ResNet101 backbone.

Car Damage Detection Sample

Car Damage Detection Sample2

Aim

To build a custom Mask R-CNN model that can detect the area of damage on a car.

The rationale for such a model is that it can be used by insurance companies for faster processing of claims if users can upload pics and they can assess damage from them. This model can also be used by lenders if they are underwriting a car loan especially for a used car.

Mask R-CNN

Mask R-CNN = Faster R-CNN and FCN (Fully Convolutional Network)

Mask R-CNN, extends Faster R-CNN by adding a branch for predicting an object mask in parallel with the existing branch for bounding box recognition. Mask R-CNN is an instance segmentation model that allows identifying pixel wise location for predefined class. Mask R-CNN is different from classical object detection models like Faster R-CNN where, in addition to identifying the class and its bounding box location, it can also color pixels in the bounding box that correspond to that class. Mask R-CNN

How Mask R-CNN works

A detailed description of how Mask R-CNNN works in available at How Mask R-CNN works

Step by Step Application of Convolutional neural networks (CNN) in Automated detection of car exterior damages and subsequent quantification(damage severity)

To help with debugging and understanding the model, car-damage-detection.ipynb.ipynb provides visualizations and allow running the model step by step to inspect the output at each point. Here are the explanations:

1. Data Collection

The dataset is made up of 68 images (50 train + 16 validation + 2 test) from the internet.

Sample Image 1 Sample Image 2
Sample Car Damage 1 Sample Car Damage 2

2. Data Annotation

A Mask R-CNN model requires the images in training dataset to be annotated, which is to have the region of damage in an image identified and the boundary of the damaged area marked accurately. An example of annotation tool is the VGG Image Annotator(VIA). The annotations is then saved as a json format file in the dataset directory.

3. Import dataset and Visualization

This custom Mask R-CNN is built on top of Matterport Mask R-CNN Github repository.

Images and annotations from dataset will be loaded by the load_custom() function in CustomDataset Class. Load Dataset

Visualization of mask on the annotated image is done in car-damage-detection.ipynb

Visualization of Input 1

Visualization of Input 2

4. Training model

Training and evaluation code is in custom.py. The mask_rcnn_coco.h5, a pre-trained weights on coco dataset is used to train this model.

Train function

You can import this module in Jupyter notebook (see the provided notebooks for examples) or you can run it directly from the command line as such:

# Train a new model starting from pre-trained COCO weights
python custom.py train --dataset="D:/Tech Projects/car-damage-detection/Mask_RCNN_damage_detector/" --weights=coco

# Train a new model starting from ImageNet weights
python custom.py train --dataset="D:/Tech Projects/car-damage-detection/Mask_RCNN_damage_detector/" --weights=imagenet

# Continue training the last model you trained. This will find
# the last trained weights in the model directory.
python custom.py train --dataset="D:/Tech Projects/car-damage-detection/Mask_RCNN_damage_detector/" --weights=last

You can also run the COCO evaluation code with:

# Run COCO evaluation on the last trained model
python custom.py evaluate --dataset="D:/Tech Projects/car-damage-detection/Mask_RCNN_damage_detector/" --weights=last

The training schedule, learning rate, and other parameters should be set in custom.py.

5. Model Validation

The model weights is inspected in car-damage-detection.ipynb.ipynb.Link last training checkpoint for model for validation. This step performs a sanity check if your weights and biases are properly distributed. Validation

6. Prediction

Inspect model by performing prediction on test and validation to test the accuracy. Prediction

The repository includes:

  • Source code of Mask R-CNN built on FPN and ResNet101.
  • Training code for MS COCO
  • Pre-trained weights for MS COCO
  • Jupyter notebooks to visualize the detection pipeline at every step
  • ParallelModel class for multi-GPU training
  • Evaluation on MS COCO metrics (AP)
  • Example of training on your own dataset

Requirements

Python 3.7, TensorFlow 1.3, Keras 2.0.8 and other common packages listed in requirements.txt.

MS COCO Requirements:

To train or test on MS COCO, you'll also need:

If you use Docker, the code has been verified to work on this Docker container.

Installation

  1. Clone this repository

  2. Install dependencies

    pip3 install -r requirements.txt
  3. Run setup from the repository root directory

    python3 setup.py install
  4. Download pre-trained COCO weights (mask_rcnn_coco.h5) from the releases page.

  5. (Optional) To train or test on MS COCO install pycocotools from one of these repos. They are forks of the original pycocotools with fixes for Python3 and Windows (the official repo doesn't seem to be active anymore).

car-damage-detector's People

Contributors

louisyuzhe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

car-damage-detector's Issues

ModuleNotFoundError: No module named 'numpy'

Hi,
I'm trying to run your project on the mac.
After pip3 install -r requirements.txt
I got ModuleNotFoundError: No module named 'numpy'

I checked the numpy installed.
Did you meet this problem before? Any ideas?

The full log:
user@Users-MBP car-damage-detector % pip3 install -r requirements.txt
Requirement already satisfied: numpy in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (from -r requirements.txt (line 1)) (1.25.1)
Collecting scipy (from -r requirements.txt (line 2))
Obtaining dependency information for scipy from https://files.pythonhosted.org/packages/c7/09/c07278f3c75018f80288032b09acd76aa4c2056cdb7fa9b0a145bac6b06b/scipy-1.11.1-cp311-cp311-macosx_10_9_x86_64.whl.metadata
Using cached scipy-1.11.1-cp311-cp311-macosx_10_9_x86_64.whl.metadata (54 kB)
Collecting Pillow (from -r requirements.txt (line 3))
Obtaining dependency information for Pillow from https://files.pythonhosted.org/packages/7a/54/f6a14d95cba8ff082c550d836c9e5c23f1641d2ac291c23efe0494219b8c/Pillow-10.0.0-cp311-cp311-macosx_10_10_x86_64.whl.metadata
Using cached Pillow-10.0.0-cp311-cp311-macosx_10_10_x86_64.whl.metadata (9.5 kB)
Collecting cython (from -r requirements.txt (line 4))
Obtaining dependency information for cython from https://files.pythonhosted.org/packages/8f/c8/49c446320661cb335c593b25c7b64e6844dde33dd0da7d625d7099790637/Cython-3.0.0-cp311-cp311-macosx_10_9_x86_64.whl.metadata
Using cached Cython-3.0.0-cp311-cp311-macosx_10_9_x86_64.whl.metadata (3.1 kB)
Collecting matplotlib (from -r requirements.txt (line 5))
Obtaining dependency information for matplotlib from https://files.pythonhosted.org/packages/7e/2c/1e25437f4419f2828bbd213be42c8fd23a3b795c5c4bb776987d177fc615/matplotlib-3.7.2-cp311-cp311-macosx_10_12_x86_64.whl.metadata
Using cached matplotlib-3.7.2-cp311-cp311-macosx_10_12_x86_64.whl.metadata (5.6 kB)
Collecting scikit-image (from -r requirements.txt (line 6))
Obtaining dependency information for scikit-image from https://files.pythonhosted.org/packages/08/53/f28cfb52248665b42db7e45a36ffc3a304fef46b308e5065fe2046e78daf/scikit_image-0.21.0-cp311-cp311-macosx_10_9_x86_64.whl.metadata
Using cached scikit_image-0.21.0-cp311-cp311-macosx_10_9_x86_64.whl.metadata (14 kB)
Using cached scikit-image-0.16.2.tar.gz (28.9 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [22 lines of output]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in
main()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
return hook(config_settings)
^^^^^^^^^^^^^^^^^^^^^
File "/private/var/folders/16/_jltgn491kzg85vj913wr4cm0000gn/T/pip-build-env-r08y3b2j/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel
return self._get_build_requires(config_settings, requirements=['wheel'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/private/var/folders/16/_jltgn491kzg85vj913wr4cm0000gn/T/pip-build-env-r08y3b2j/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 323, in _get_build_requires
self.run_setup()
File "/private/var/folders/16/_jltgn491kzg85vj913wr4cm0000gn/T/pip-build-env-r08y3b2j/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 488, in run_setup
self).run_setup(setup_script=setup_script)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/private/var/folders/16/_jltgn491kzg85vj913wr4cm0000gn/T/pip-build-env-r08y3b2j/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 338, in run_setup
exec(code, locals())
File "", line 243, in
File "", line 71, in openmp_build_ext
ModuleNotFoundError: No module named 'numpy'
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip

Thanks for your help,
Gennady.

ValueError: Tried to convert 'shape' to a tensor and failed. Error: None values not supported.

Dear Author,
When I am running this part of the code inside Google Colab,

Creating model in Inference mode
import tensorflow as tf
with tf.device(DEVICE):
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

Loading the last best model which is trained
weights_path = model.find_last()[1]
custom_WEIGHTS_PATH = '/content/drive/MyDrive/car-damage-detection-using-CNN/logs/mask_rcnn_coco.h5'

Load weights
print("Loading weights ", custom_WEIGHTS_PATH)
model.load_weights(custom_WEIGHTS_PATH, by_name=True)

I get the following error:
ValueError: None values not supported.

During handling of the above exception, another exception occurred:

ValueError Traceback (most recent call last)
ValueError: None values not supported.

During handling of the above exception, another exception occurred:

ValueError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(op_type_name, name, **keywords)
538 raise ValueError(
539 "Tried to convert '%s' to a tensor and failed. Error: %s" %
--> 540 (input_name, err))
541 prefix = ("Input '%s' of '%s' Op has type %s that does not match" %
542 (input_name, op_type_name, observed))

ValueError: Tried to convert 'shape' to a tensor and failed. Error: None values not supported. Kindly assist me on the same

module 'keras.engine' has no attribute 'Layer' error

Dear Author,
When I run this part of the code
"# Import all the packages of Matterport Mask R-CNN
import os
import sys
import itertools
import math
import logging
import json
import re
import random
from collections import OrderedDict
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.lines as lines
from matplotlib.patches import Polygon
from tensorflow import keras
from mrcnn import utils
from mrcnn import visualize
from mrcnn.visualize import display_images
from mrcnn import model
import mrcnn.model as modellib
from mrcnn.model import log
import cv2
import custom,custom_1
import imgaug,h5py,IPython

%matplotlib inline"

I get this error
AttributeError Traceback (most recent call last)
in ()
22 from mrcnn import visualize
23 from mrcnn.visualize import display_images
---> 24 from mrcnn import model
25 import mrcnn.model as modellib
26 from mrcnn.model import log

/content/Mask_RCNN/mrcnn/model.py in ()
253
254
--> 255 class ProposalLayer(KE.Layer):
256 """Receives anchor scores and selects a subset to pass as proposals
257 to the second stage. Filtering is done based on anchor scores and

AttributeError: module 'keras.engine' has no attribute 'Layer'
Please reply

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.