0% found this document useful (0 votes)
146 views

Intro To Anomal Detection With Opencv, Computer Vision, and Scikit-Learn

The document discusses anomaly detection in images using OpenCV, computer vision, and scikit learn machine learning library. It defines anomalies as events that deviate from standard patterns and are rare. It explains that anomalies are hard for machine learning to detect due to class imbalance. It then discusses outlier and novelty detection algorithms for handling this type of problem.

Uploaded by

超揚林
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
146 views

Intro To Anomal Detection With Opencv, Computer Vision, and Scikit-Learn

The document discusses anomaly detection in images using OpenCV, computer vision, and scikit learn machine learning library. It defines anomalies as events that deviate from standard patterns and are rare. It explains that anomalies are hard for machine learning to detect due to class imbalance. It then discusses outlier and novelty detection algorithms for handling this type of problem.

Uploaded by

超揚林
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

MNU

/
A N O M A LY O U T L I  R   D  T  C T I O N   I M AG    D   C R I P T O R    M AC H I N    L  A R N I N G   T U TO R I A L 

Intro to anomal detection with

OpenCV  Computer Vision  and , ,


scikit learn -
 Adrian Roserock on Januar 20  2020 ,

Click here to download the source code to this post

,
In this tutorial  ou will learn how to perform anomal novelt detection in image /
, /
In this tutorial  ou will learn how to perform anomal novelt detection in image

, ,
datasets using OpenCV  Computer Vision  and the scikit learn machine learning -
.
lirar

Imagine this  — ou’re fresh out of college with a degree in Computer cience.
You focused our studies speci몭call on computer vision and machine learning .

Your 몭rst jo out of school is with the United tates National Parks department .

Your task ?

uild a computer vision sstem that can automaticall recognize 몭ower

.
species in the park  uch a sstem can e used to detect invasive plant species

that ma e harmful to the overall ecosstem of the park .

You recognize immediatel that computer vision can e used to recognize 몭ower

species .

ut 몭rst ou need to :

1 Gather example images of each 몭ower species in the park  i e  uild a ( . .,
dataset ).

2 Quantif the image dataset and train a machine learning model to

recognize the species .

3 /
pot when outlier anomal plant species are detected  that wa a trained ,

otanist can inspect the plant and determine if it s harmful to the park s ’
environment .

teps  #1 and #2 and fairl straightforward — ut tep #3 is sustantiall harder
to perform .

How are ou supposed to train a machine learning model to automaticall detect

“ ”
if a given input image is outside the  normal distriution  of what plants look like

in the park ?

The answer lies in a special class of machine learning algorithms  including ,
outlier detection and novelt anomal detection / .

, ’
In the remainder of this tutorial  ou ll learn the di몭erence etween these

algorithms and how ou can use them to spot outliers and anomalies in our own
algorithms and how ou can use them to spot outliers and anomalies in our own

image datasets .

/
To learn how to perform anomal novelt detection in image datasets  just ,
keep reading !

Looking for the source code to this post ?
J U M P   R I G H T   TO   T H    D O W N LOA D      C T I O N  

Intro to anomal detection with OpenCV ,
Computer Vision  and scikit learn , -
, ’
In the 몭rst part of this tutorial  we ll discuss the di몭erence etween standard

events that occur naturall and outlier anomal events / .


We ll also discuss wh these tpes of events can e especiall hard for machine

learning algorithms to detect .


From there we ll review our example dataset for this tutorial .


I ll then show ou how to :

1 Load our input images from disk .

2 Quantif them .

3 Train a machine learning model used for anomal detection on our

quanti몭ed images .

4 ’ /
From there we ll e ale to detect outliers anomalies in new input images .


Let s get started !

What are outliers and anomalies  And wh are the ?
What are outliers and anomalies  And wh are the ?
hard to detect ?

: - ’
Figure 1  cikit learn s de몭nition of an outlier is an important concept for anomal

(
detection with OpenCV and computer vision  image source ).

Anomalies are de몭ned as events that deviate from the standard  rarel ,
, ’
happen  and don t follow the rest of the  pattern “ ”.

xamples of anomalies include :

Large dips and spikes in the stock market due to world events

/
Defective items in a factor on a conveor elt

Contaminated samples in a la

,
If ou were to think of a ell curve  anomalies exist on the far  far ends of the ,
tails.
: .
Figure 2  Anomalies exist at either side of a ell curve  In this tutorial we will

, ,
conduct anomal detection with OpenCV  computer vision  and scikit learn -
(image source).

,
These events will occur  ut will happen with an incredil small proailit .

,
From a machine learning perspective  this makes detecting anomalies hard  — 
, “ ”
de몭nition  we have man examples of  standard  events and few examples of

“anomal” events.

, ,
We  therefore  have a massive skew in our dataset .

,
How are machine learning algorithms  which tend to work optimall with

,
alanced datasets  supposed to work when the anomalies we want to detect

ma onl happen 1%, 0.1%, or 0.0001% of the time?

,
Luckil  machine learning researchers have investigated this tpe of prolem and

have devised algorithms to handle the task .

Anomal detection algorithms
: - ,
Figure 3  To detect anomalies in time series data  e on the lookout for spikes as shown .
- , ,
We will use scikit learn  computer vision  and OpenCV to detect anomalies in this tutorial

(image source).

Anomal detection algorithms can e roken down into two suclasses :

:
Outlier detection  Our input dataset contains examples of oth standard

.
events and anomal events  These algorithms seek to 몭t regions of the

training data where the standard events are most concentrated  disregarding , ,
,
and therefore isolating  the anomal events  uch algorithms are often trained .
( . ., ).
in an unsupervised fashion  i e  without laels  We sometimes use these

methods to help clean and pre-process datasets efore appling additional

machine learning techniques.

:
Novelt detection  Unlike outlier detection  which includes examples of oth,
,
standard and anomal events  novelt detection algorithms have onl the

( . .,
standard event data points  i e  no anomal events  during training time ) .
,
During training  we provide these algorithms with laeled examples of

( ).
standard events  supervised learning  At testing prediction time novelt /
detection algorithms must detect when an input data point is an outlier .

Outlier detection is a form of unsupervised learning  Here we provide our entire .
dataset of example data points and ask the algorithm to group them into inliers

(standard data points) and outliers (anomalies).

Novelt detection is a form of supervised learning  ut we onl have laels for ,
the standard data points  — it’s up to the novelt detection algorithm to predict if
a given data point is an inlier or outlier at test time.

, ’
In the remainder of this log post  we ll e focusing on novelt detection as a

form of anomal detection .

Isolation Forests for anomal detection
: “ ” .’
Figure 4  A technique called  Isolation Forests  ased on Liu et al s 2012 paper is used to

, , - (
conduct anomal detection with OpenCV  computer vision  and scikit learn  image source ).


We ll e using Isolation Forests to perform anomal detection  ased on Liu et ,
.’ , -
al s 2012 paper  Isolation ased Anomal Detection .

Isolation forests are a tpe of ensemle algorithm and consist of multiple

decision trees used to partition the input dataset into distinct groups of inliers .

,
As Figure 4 shows aove  Isolation Forests accept an input dataset  white (
)
points  and then uild a manifold surrounding them .

,
At test time  the Isolation Forest can then determine if the input points fall inside

( ; )
the manifold  standard events  green points  or outside the high densit area -
(anomal events; red points).

Reviewing how the Isolation Forests constructs an ensemle of partitioning trees

,
is outside the scope of this post  so e sure to refer to Liu et al s paper for more .’
details .

Con몭guring our anomal detection development

environment

’ ,
To follow along with toda s tutorial  ou will need a Pthon 3 virtual
environment with the following packages installed :

scikit learn -

OpenCV

NumP

imutils

, -,
Luckil  each of these packages is pip installale  ut there are a handful of pre-
requisites (including Pthon virtual environments). e sure to follow the following

guide 몭rst to set up our virtual environment with OpenCV: pip install opencv

,
Once our Pthon 3 virtual environment is read  the pip install commands

include :

→ Launch Jupter Noteook on Google Cola

Tuning dlib shape predictor hyperparameters to balance speed, accuracy, and model size
1.  $ workon <env­name>
2.  $ pip install numpy
3.  $ pip install opencv­contrib­python
4.  $ pip install imutils
5.  $ pip install scikit­learn

:
Note  The  workon  command ecomes availale once ou install  virtualenv
and  virtualenvwrapper  per the pip install opencv installation guide .

Project structure

e sure to gra the source code and example images to toda s post using the ’
“Downloads” section of the tutorial. After ou unarchive the .zip 몭le ou’ll e
presented with the following project structure :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ tree ­­dirsfirst
2.  .
3.  ├── examples
4.  │   ├── coast_osun52.jpg
5.  │   ├── forest_cdmc290.jpg
6.  │   └── highway_a836030.jpg
7.  ├── forest
8.  │   ├── forest_bost100.jpg
9.  │   ├── forest_bost101.jpg
9.  │   ├── forest_bost101.jpg
10.  │   ├── forest_bost102.jpg
11.  │   ├── forest_bost103.jpg
12.  │   ├── forest_bost98.jpg
13.  │   ├── forest_cdmc458.jpg
14.  │   ├── forest_for119.jpg
15.  │   ├── forest_for121.jpg
16.  │   ├── forest_for127.jpg
17.  │   ├── forest_for130.jpg
18.  │   ├── forest_for136.jpg
19.  │   ├── forest_for137.jpg
20.  │   ├── forest_for142.jpg
21.  │   ├── forest_for143.jpg
22.  │   ├── forest_for146.jpg
23.  │   └── forest_for157.jpg
24.  ├── pyimagesearch
25.  │   ├── __init__.py
26.  │   └── features.py
27.  ├── anomaly_detector.model
28.  ├── test_anomaly_detector.py
29.  └── train_anomaly_detector.py
30.  
31.  3 directories, 24 files

Our project consists of  forest/  images and  example/ .


 testing images  Our

anomal detector will tr to determine if an of the three examples is an

anomal compared to the set of forest images .

Inside the  pyimagesearch  module is a 몭le named  features.py .


   This script

contains two functions responsile for loading our image dataset from disk and

calculating the color histogram features for each image .

We will operate our sstem in two stages  — (1) training, and (2) testing.

,
First  the  train_anomaly_detector.py  script calculates features and trains an

Isolation Forests machine learning model for anomal detection  serializing the ,
result as  anomaly_detector.model   .


Then we ll develop  test_anomaly_detector.py  which accepts an example

image and determines if it is an anomal .

Our example image dataset
:
Figure 5  We will use a suset of the 8cenes dataset to detect anomalies among

- , , .
pictures of forests using scikit learn  OpenCV  and computer vision

Our example dataset for this tutorial includes 16 images of forests  each of (
which is shown in Figure 5 aove ).

These example images are a suset of the 8 cenes Dataset from Oliva and

’ ,
Torrala s paper  Modeling the shape of the scene  a holistic representation of :
the spatial envelope .


We ll take this dataset and train an anomal detection algorithm on top of it .

,
When presented with a new input image  our anomal detection algorithm will

return one of two values :

1 1 : “Yep, that’s a forest.”

2 ­1 : “No, doesn’t look like a forest. It must e an outlier.”


You can thus think of this model as a  forest  vs  not forest  detector ” “ ” .

This model was trained on forest images and now must decide if a new input

“ ”
image 몭ts inside the  forest manifold  or if is trul an anomal outlier / .

To evaluate our anomal detection algorithm we have 3 testing images :
: ’ +
Figure 6  Three testing images are included in toda s Pthon   computer vision anomal

detection project.

, — the other two are
As ou can see  onl one of these images is a forest 

examples of highwas and each coasts, respectivel.

,
If our anomal detection pipeline is working properl  our model should return 

1 ( )
  inlier  for the forest image and  ­1  for the two non forest images- .

Implementing our feature extraction and dataset

loader helper functions

: .
Figure 7  Color histograms characterize the color distriution of an image  Color will e the asis

, ,
of our anomal detection introduction using OpenCV  computer vision  and scikit learn - .

efore we can train a machine learning model to detect anomalies and outliers ,
we must 몭rst de몭ne a process to quantif and characterize the contents of our

input images .

, ’
To accomplish this task  we ll e using color histograms .

Color histograms are simple et e몭ective methods to characterize the color

distriution of an image .

. -
ince our task here is to characterize forest vs  non forest images  we ma ,
assume that forest images will contain more shades of green versus their non -
forest counterparts .

Let s take a look at how we can implement color histogram extraction using

OpenCV .

Open up the  features.py  몭le in the  pyimagesearch  module and insert the

following code :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  # import the necessary packages
2.  from imutils import paths
3.  import numpy as np
4.  import cv2
5.  
6.  def quantify_image(image, bins=(4, 6, 3)):
7.    # compute a 3D color histogram over the image and normalize it
8.    hist = cv2.calcHist([image], [0, 1, 2], None, bins,
9.      [0, 180, 0, 256, 0, 256])
10.    hist = cv2.normalize(hist, hist).flatten()
11.  
12.    # return the histogram
13.    return hist

-
Lines 2 4 import our packages  We ll use  . ’ paths  from m  imutils  package to

.
list all images in an input director  OpenCV will e used to calculate and

.
normalize histograms  NumP is used for arra operations .

Now that imports are taken care of  let s de몭ne the  , ’ quantify_image  function .


This function accepts two parameters :

image : -
   The OpenCV loaded image .

bins : , -
   When plotting the histogram  the x axis serves as our  ins “ .” In this
case our  default  speci몭es  4  hue ins   , 6  saturation ins  and , 3  value

. ’
— if we use onl 2 (equall spaced) ins, then we
ins  Here s a rief example 

are counting the numer of times a pixel is in the range [0, 128] or [128, 255].

The numer of pixels inned to the x-axis value is then plotted on the -axis.

:
Note  To learn more aout oth histograms and color spaces including HV ,
, * * , ,
RG  and L a   and Grascale  e sure to refer to Practical Pthon and

OpenCV and PImageearch Gurus .

-
Lines 8 10 compute the color histogram and normalize it  Normalization allows .
us to count percentage and not raw frequenc counts  helping in the case that ,
some images are larger or smaller than others .
Line 13 returns the normalized histogram to the caller .

Our next function handles :

1 Accepting the path to a director containing our dataset of images .

2 Looping over the image paths while quantifing them using our 

quantify_image  method .


Let s take a look at this method now :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
15.  def load_dataset(datasetPath, bins):
16.    # grab the paths to all images in our dataset directory, then
17.    # initialize our lists of images
18.    imagePaths = list(paths.list_images(datasetPath))
19.    data = []
20.  
21.    # loop over the image paths
22.    for imagePath in imagePaths:
23.      # load the image and convert it to the HSV color space
24.      image = cv2.imread(imagePath)
25.      image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
26.  
27.      # quantify the image and update the data list
28.      features = quantify_image(image, bins)
29.      data.append(features)
30.  
31.    # return our data list as a NumPy array
32.    return np.array(data)

Our  load_dataset  function accepts two parameters :

datasetPath :
   The path to our dataset of images .

bins : .
   Num of ins for the color histogram  Refer to the explanation aove .
The ins are passed to the  quantify_image  function .

Line 18 gras all image paths in the  datasetPath  .

Line 19 initializes a list to hold our features  data  .

,
From there  Line 22 egins a loop over the  imagePaths .
   Inside the loop we

load an image and convert it to the HV color space  Lines 24 and 25  Then we( ).


quantif the  image ,
   and add the resulting  features  to the  data (
 list  Lines

28 and 29 ).
,
Finall  Line 32 returns our  data  list as a NumP arra to the caller .

Implementing our anomal detection training script

with scikit learn -
With our helper functions implemented we can now move on to training an

anomal detection model .

’ ,
As mentioned earlier in this tutorial  we ll e using an Isolation Forest to help

determine anomal/novelt data points.

Our implementation of Isolation Forests comes from the scikit learn lirar - .

Open up the  train_anomaly_detector.py ’
 몭le and let s get to work :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  # import the necessary packages
2.  from pyimagesearch.features import load_dataset
3.  from sklearn.ensemble import IsolationForest
4.  import argparse
5.  import pickle
6.  
7.  # construct the argument parser and parse the arguments
8.  ap = argparse.ArgumentParser()
9.  ap.add_argument("­d", "­­dataset", required=True,
10.    help="path to dataset of images")
11.  ap.add_argument("­m", "­­model", required=True,
12.    help="path to output anomaly detection model")
13.  args = vars(ap.parse_args())

- .
Lines 2 6 handle our imports  This script uses our custom  load_dataset
- ’
function and scikit learn s implementation of Isolation Forests  We ll serialize . ’
our resulting model as a pickle 몭le .

-
Lines 8 13 parse our command line arguments including :

­­dataset :
   The path to our dataset of images .

­­model :
   The path to the output anomal detection model .

, ’
At this point  we re read to load our dataset and train our Isolation Forest

model :
→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
15.  # load and quantify our image dataset
16.  print("[INFO] preparing dataset...")
17.  data = load_dataset(args["dataset"], bins=(3, 3, 3))
18.  
19.  # train the anomaly detection model
20.  print("[INFO] fitting anomaly detection model...")
21.  model = IsolationForest(n_estimators=100, contamination=0.01,
22.    random_state=42)
23.  model.fit(data)

Line 17 loads and quanti몭es the image dataset .

Lines 21 and 22 initializes our  IsolationForest  model with the following

parameters :

n_estimators : ( . ., )
   The numer of ase estimators  i e  trees  in the ensemle .

contamination :
   The proportion of outliers in the dataset .

random_state :
   The random numer generator seed value for

.
reproduciilit  You can use an integer   ; 42  is commonl used in the

,
machine learning world as it relates to a joke in the ook  Hitchhiker s Guide ’
to the Galax .

e sure to refer to other optional parameters to the Isolation Forest in the scikit -
learn documentation .

Line 23 trains the anomal detector on top of the histogram  data  .

,
Now that our model is trained  the remaining lines serialize the anomal detector

to a pickle 몭le on disk :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
25.  # serialize the anomaly detection model to disk
26.  f = open(args["model"], "wb")
27.  f.write(pickle.dumps(model))
28.  f.close()

Training our anomal detector

Now that we have implemented our anomal detection training script  let s put it , ’


to work .
“ ”
tart  making sure ou have used the  Downloads  section of this tutorial to

download the source code and example images .

,
From there  open up a terminal and execute the following command :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ python train_anomaly_detector.py ­­dataset forest ­­model anomaly_detector.model
2.  [INFO] preparing dataset...
3.  [INFO] fitting anomaly detection model...

To verif that the anomal detector has een serialized to disk  check the ,
contents of our working project director :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ ls *.model
2.  anomaly_detector.model

Creating the anomal detector testing script

At this point we have trained our anomal detection model  — ut how do we
use to actuall detect anomalies in new data points ?

,
To answer that question  let s look at the ’ test_anomaly_detector.py  script.

- ,
At a high level  this script :

1 Loads the anomal detection model trained in the previous step .

2 , ,
Loads  preprocesses  and quanti몭es a quer image .

3 Makes a prediction with our anomal detector to determine if the quer

(. .
image is an inlier or an outlier  i e  anomal ).

4 Displas the result .

Go ahead and open  test_anomaly_detector.py  and insert the following code :

→ Launch Jupter Noteook on Google Cola
Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  # import the necessary packages
2.  from pyimagesearch.features import quantify_image
3.  import argparse
4.  import pickle
5.  import cv2
6.  
7.  # construct the argument parser and parse the arguments
8.  ap = argparse.ArgumentParser()
9.  ap.add_argument("­m", "­­model", required=True,
10.    help="path to trained anomaly detection model")
11.  ap.add_argument("­i", "­­image", required=True,
12.    help="path to input image")
13.  args = vars(ap.parse_args())

- .
Lines 2 5 handle our imports  Notice that we import our custom 

quantify_image  function to calculate features on our input image  We also .


import  pickle .
 to load our anomal detection model  OpenCV will e used for

, ,
loading  preprocessing  and displaing images .

Our script requires two command line arguments :

­­model :
   The serialized anomal detector residing on disk .

­­image : (. .
   The path to the input image  i e  our quer ).


Let s load our anomal detector and quantif our input image :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
15.  # load the anomaly detection model
16.  print("[INFO] loading anomaly detection model...")
17.  model = pickle.loads(open(args["model"], "rb").read())
18.  
19.  # load the input image, convert it to the HSV color space, and
20.  # quantify the image in the *same manner* as we did during training
21.  image = cv2.imread(args["image"])
22.  hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
23.  features = quantify_image(hsv, bins=(3, 3, 3))

-
Line 17 loads our pre trained anomal detector .

- , ,
Lines 21 23 load  preprocess  and quantif our input  image .
   Our preprocessing

(. .
steps must e the same as in our training script  i e  converting from GR to HV

color space ).

, ’
At this point  we re read to make an anomal prediction and displa results :

→ Launch Jupter Noteook on Google Cola
Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
25.  # use the anomaly detector model and extracted features to determine
26.  # if the example image is an anomaly or not
27.  preds = model.predict([features])[0]
28.  label = "anomaly" if preds == ­1 else "normal"
29.  color = (0, 0, 255) if preds == ­1 else (0, 255, 0)
30.  
31.  # draw the predicted label text on the original image
32.  cv2.putText(image, label, (10,  25), cv2.FONT_HERSHEY_SIMPLEX,
33.    0.7, color, 2)
34.  
35.  # display the image
36.  cv2.imshow("Output", image)
37.  cv2.waitKey(0)

Line 27 makes predictions on the input image  features .
   Our anomal

detection model will return  1 “ ”
 for a  normal  data point and  ­1 “
 for an  outlier ”.

Line 28 assigns either an  "anomaly"  or  "normal"  lael to our prediction .

-
Lines 32 37 then annotate the  label  onto the quer image and displa it on

screen until an ke is pressed .

Detecting anomalies in image datasets using

computer vision and scikit learn -
To see our anomal detection model in action make sure ou have used the

“Downloads” section of this tutorial to download the source code, example
, -
image dataset  and pre trained model .

,
From there  ou can use the following command to test the anomal detector :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ python test_anomaly_detector.py ­­model anomaly_detector.model \
2.    ­­image examples/forest_cdmc290.jpg 
3.  [INFO] loading anomaly detection model...
: .
Figure 8  This image is clearl not an anomal as it is a green forest  Our intro to anomal

detection method with computer vision and Pthon has passed the 몭rst test .

Here ou can see that our anomal detector has correctl laeled the forest as

an inlier.


Let s now see how the model handles an image of a highwa  which is certainl ,
not a forest :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ python test_anomaly_detector.py ­­model anomaly_detector.model \
2.    ­­image examples/highway_a836030.jpg
3.  [INFO] loading anomaly detection model...
:
Figure 9  A highwa is an anomal compared to our set of forest images and has een marked as

- .
such in the top left corner  This tutorial presents an intro to anomal detection with OpenCV ,
, -
computer vision  and scikit learn.

Our anomal detector correctl laels this image as an outlier anomal / .

, ’
As a 몭nal test  let s suppl an image of a each coast to the anomal detector / :

→ Launch Jupter Noteook on Google Cola

Intro to anomaly detection with OpenCV, Computer Vision, and scikit­learn
1.  $ python test_anomaly_detector.py ­­model anomaly_detector.model \
2.    ­­image examples/coast_osun52.jpg 
3.  [INFO] loading anomaly detection model...

:
Figure 10  A coastal landscape is marked as an anomal against a set of forest images using

, , - ,
Pthon  OpenCV  scikit learn  and computer vision anomal detection techniques .

,
Once again  our anomal detector correctl identi몭es the image as an

/
outlier anomal .

'
What s next  I recommend PImageearch ?
' ?
What s next  I recommend PImageearch

Universit .

Course information   :
• • : /
13 total classes   21h 2m video   Last updated  4 2021 

★★★★★ 4.84 (128 Ratings) • 3,690 tudents nrolled

I strongl elieve that if ou had the right teacher ou could master

computer vision and deep learning .

Do ou think learning computer vision and deep learning has to e

- , , ?
time consuming  overwhelming  and complicated  Or has to involve

?
complex mathematics and equations  Or requires a degree in

computer science ?


That s not the case .

All ou need to master computer vision and deep learning is for

, . ’
someone to explain things to ou in simple  intuitive terms  And that s

.
exactl what I do  M mission is to change education and how complex

Arti몭cial Intelligence topics are taught .

' ,
If ou re serious aout learning computer vision  our next stop should
,
e PImageearch Universit  the most comprehensive computer

, ,
vision  deep learning  and OpenCV course online toda  Here ou ll . ’
learn how to successfull and con몭dentl appl computer vision to

, , .
our work  research  and projects  Join me in computer vision master .

Inside PImageearch Universit ou ll 몭nd ' :

✓ 13 courses on essential computer vision, deep learning, and
OpenCV topics

✓ 13 Certi몭cates of Completion

✓ 21h 2m on-demand video

✓ rand new courses released ever month, ensuring ou can keep
up with state-of-the-art techniques

✓ Pre-con몭gured Jupter Noteooks in Google Cola

✓ Run all code examples in our we rowser — works on Windows,
macO, and Linux (no dev environment con몭guration required!)

✓ Access to centralized code repos for all 400+ tutorials on
PImageearch

✓ as one-click downloads for code, datasets, pre-trained models,
etc.

✓ Access on moile, laptop, desktop, etc.

C L I C K   H  R    TO   J O I N   P Y I M AG    A R C H   U N I V  R  I T Y

ummar

In this tutorial ou learned how to perform anomal and outlier detection in

-
image datasets using computer vision and the scikit learn machine learning
lirar .

To perform anomal detection  we , :

1 Gathered an example image dataset of forest images .

2 Quanti몭ed the image dataset using color histograms and the OpenCV

lirar .

3 Trained an Isolation Forest on our quanti몭ed images .

4 Used the Isolation Forest to detect image outliers and anomalies .

-
Along with Isolation Forests ou should also investigate One class VMs  lliptic ,
,
nvelopes  and Local Outlier Factor algorithms as the can e used for

/
outlier anomal detection as well .

ut what aout deep learning ?

Can deep learning e used to perform anomal detection too ?


I ll answer that question in a future tutorial .

(
To download the source code to this post  and e noti몭ed when future

tutorials are pulished here on PImageearch ), just enter our email address
in the form elow !
Download the ource Code and FR 17 page -
Resource Guide

.
nter our email address elow to get a  zip of the code and a FR 17 page -
, ,
Resource Guide on Computer Vision  OpenCV  and Deep Learning  Inside ou ll . '
- , , ,
몭nd m hand picked tutorials  ooks  courses  and liraries to help ou master CV

and DL !

Your email address D O W N L OA D   T H    C O D  !

Aout the Author

, ’ , .
Hi there  I m Adrian Roserock  PhD  All too often I see developers  students , ,
, ,
and researchers wasting their time  studing the wrong things  and generall

struggling to get started with Computer Vision, Deep Learning, and OpenCV. I

created this wesite to show ou what I elieve is the est possile wa to
get our start .

Previous Article :
Optimizing dli shape predictor accurac with 몭nd _min_gloal

:
Next Article

-
YOLO and Tin YOLO oject detection on the Rasperr Pi and

Movidius NC

:
22 responses to  Intro to anomal detection with

,
OpenCV  Computer Vision  and scikit learn , -

undaresh

,
Januar 20  2020 at 2 46 pm :

Hello Adrian ,

. ,
Thank ou for the article  A technicalit  ut nump is included as part of the

- .
scikit learn package  I suggest our code could e changed to install just

scikit-learn instead of oth the packages. Not that it does an harm either

wa.

,
Regards  

undaresh

Adrian Roserock

,
Januar 20  2020 at 4 36 pm :

, - -
You are correct  NumP is a pre req of scikit learn  opencv contri pthon, - - ,
.
and even imutils  If ou installed an of those NumP would also e pulled

in.

Giovanni

,
Januar 23  2020 at 1 12 pm :

,
Awesome argument  awesome explanation and awesome approach .

, ’ ;
ut  i ll leave that there  what aout Anomal Recognition from Video ource   ?

I d like to implement mself an anomal recognition model which can detect

,
anomalies in various environment ased on a video source  such as cit video

;
surveillance sstems or even factories video surveillance  it must recognize

, ,
anomalies such as explosions  strange walking pattern  roer etc .

(
It could e done approaching the prolem using TV  patio Temporal -
)
Volume  framing the videos in images and using those to train the CNN model

(or even a RNN).

?
What would e our approach for such kind of prolem  Would e nice to

have some opinions on the matters .

Cheers !

Adrian Roserock

,
Januar 30  2020 at 8 33 am :

ee m repl to William .

Willian

,
Januar 26  2020 at 8 40 am :
/
441 5000 

!
Hi Adrian  First thanks for the excellent tutorial   .
,
Following the logic of this article  would it e possile to create a sstem to

detect tales that customers in a store have left dirt  that is  with ojects that , ,


have een consumed such as tras  glasses  etc , , .? 
Would it e the case of anomal detection in this case too   ?
Or would I have to do tale detection training and analze what is on the

tale and if there are people in the room   ?
Thanks !

Adrian Roserock

,
Januar 30  2020 at 8 32 am :

, ’ .
Yes  it s asolutel possile  asicall would create an autoencoder that

uses 2D convolution with LTM modules as well .

Carlos Jiménez

,
Januar 27  2020 at 9 39 am :

Hi  ὤ i love our tutorial, thank ou. 

I m new on this topic ut i have a question   .
Can i do this with a rasperr zero   ?
I did this question ecause i think ou were using a computer Mac   ( ).
Have a nice da .

Adrian Roserock

,
Januar 30  2020 at 8 32 am :


You wouldn t perform feature extraction or model training on the RPi .
,
Instead  ou would train the model on our laptop desktop and then /
deplo it to the RPi to make predictions .
This time of work몭ow is covered in Rasperr Pi for Computer Vision .

mohamed kedir noordeen

,
Januar 28  2020 at 3 23 am :

-
What aout using extracted features from a pre trained Imagenet model to

uild an isolation forest instead of using color histogram features  It makes ?
our model more roust to the prolem .

Adrian Roserock

,
Januar 30  2020 at 8 31 am :

You can use whatever input features ou would like provided that are

.
relevant to the task  I would suggest experimenting and giving it a tr .

Marc

,
Feruar 4  2020 at 7 07 am :

Hi Andrian  ,
,
thanks for this ver nice tutorial  I am a ig fan of our wesite   !
,
For me  the di몭cult in anomal detection is mainl to 몭nd the right features

. ,
that are relevant to identif anomalies  Here  ou use the histogram which is

.
ver straightforward in this prolem  I would love to see more examples of

. . .
anomal detection  Like e g  identifing wear out for predictive maintenance

of machines   .
Cheers

Adrian Roserock

,
Feruar 5  2020 at 1 42 pm :
,
Rest assured Marc  there are more anomal detection tutorials coming

soon  ὤ

Alejandro ilvestri

,
Feruar 6  2020 at 10 25 am :

Hi Adrian ,

! ’ . !
This log is great  I m alwas 몭nding new stu몭 here  It never runs out  

’ ,
I m asking for a ver speci몭c suject  ma e ou can give me directions   .
I’m looking for a wa to recognize ant paths in the 몭eld. 

,
Do ou happen to know aout some alread availale model  or a wa to

start working on it   ?
Thank ou !

Adrian Roserock

,
Feruar 13  2020 at 10 50 am :

’ ’ - .
I don t think there s a pre trained ant detector  You would likel have to

.
train our own  I would suggest ou read Deep Learning for Computer

Vision with Pthon if ou want to learn how to train our own custom

oject detectors .

Ahijith 

,
Feruar 22  2020 at 2 31 pm :

, .
Hello Adrian  Nice tutorial  I wanted to know if it is possile to train on

di몭erent ojects like dogs, cats, cars etc and detect anomal images which

do not elong to trained ojects.
Adrian Roserock

,
Feruar 27  2020 at 8 59 am :

, . ’
Yes  ou can certainl do that  Refer to next week s post on anomal

detection with deep learning.

Jed Masterson

,
March 2  2020 at 2 43 am :

. ’
Thanks for thus guide  I m still new at this and can get so man thing wrong .
:
And here i have a question  can we implement isolating trees to line ased

? , .
detection  For example  i have anomal detection on vehicles ottom task  Is

? ,
it possile to distinguish needed features  In advance  thanks for repl

Patrick

,
March 2  2020 at 10 03 pm :

Hi Adrian 

As alwas  – thank ou for such great posts.

‘ ’ .
I was wondering wh the  contamination  value was set to 0 01 when the

training data set onl had Forest pictures .

Thank ou again

Patrick

,
March 2  2020 at 10 51 pm :
Hi Adrian

,
Not so much a question  ut an oservation on the performance of this model

and approach .

I was curious aout the accurac of the IsolationForest model and the

. ,
approach in the post  o I trained the model just as in this log post  ut I

scored the performance against the 3scenes dataset ou descried in this

:[
post   https ://www.pimagesearch.com/2019/01/14/machine-learning-in-
pthon /].

Running against the 3scenes dataset with a total of 939 images the model

was 63 5 . % accurate.

,
Which seems prett good to me  given that we are onl looking at the color

distriution throughout the image .

I am now o몭 to read the latest post on using TensorFlow and Keras

[https://www.pimagesearch.com/2020/03/02/anomal-detection-with-keras-
tensor몭ow-and-deep-learning/]

Thanks again for all of the great content .

Pat

Adrian Roserock

, :
March 4  2020 at 1 20 pm

!
Thanks Pat  And nice jo extending the tutorial to work with our own

dataset ὤ

Jaco Okomo
,
March 6  2020 at 2 35 pm :

.
This man Dr  Adrian is here doing awesome sta몭s ma Go less our ,
hands … 
’ .
You ll one da hit 1 5 Million suscriers i pra … 
Hope that google support ou

Adrian Roserock

,
March 11  2020 at 4 33 pm :

Thank ou for the kind words  Jaco , !

Comment section

, ,
He  Adrian Roserock here  author and creator of PImageearch  While I .
,
love hearing from readers  a couple ears ago I made the tough decision to

:
no longer o몭er 1 1 help over log post comments .

+
At the time I was receiving 200  emails per da and another 100  log +
.
post comments  I simpl did not have the time to moderate and respond to

,
them all  and the shear volume of requests was taking a toll on me .

,
Instead  m goal is to do the most good for the computer vision  deep ,
,
learning  and OpenCV communit at large  focusing m time on

-
authoring high qualit log posts  tutorials  and ooks courses , , / .

If ou need help learning computer vision and deep learning  I suggest ,
ou refer to m full catalog of ooks and courses  — the have helped
tens of thousands of developers  students  and researchers just like , ,
ourself learn Computer Vision  Deep Learning  and OpenCV , , .
Click here to rowse m full catalog .

PImageearch Universit  — NOW NROLLING!

, ,
You can master Computer Vision  Deep Learning  and OpenCV

Course information  :
• • : /
13 total classes   21h 2m video   Last updated  4 2021 

★★★★★ 
4.84 (128 Ratings) • 3,690 tudents nrolled

✓ 13 courses on essential computer vision, deep learning, and OpenCV topics 

✓ 13 Certi몭cates of Completion 

✓ 21h 2m on-demand video 

✓ rand new courses released ever month, ensuring ou can keep up with state-of-

-
the art techniques 

✓ Pre-con몭gured Jupter Noteooks in Google Cola 

✓ Run all code examples in our we rowser — works on Windows, macO, and Linux

(no dev environment con몭guration required!) 

✓ Access to centralized code repos for all 400+ tutorials on PImageearch 

✓ as one-click downloads for code, datasets, pre-trained models, etc. 

✓ Access on moile, laptop, desktop, etc.

JOIN NOW
Picked For You

Local inar Patterns with Pthon  & OpenCV

: -
Your First Image Classi몭er  Using k NN to Classif Images

, ,
Anomal detection with Keras  TensorFlow  and Deep Learning
Multiprocessing with OpenCV and Pthon

’ , ,
Detecting Parkinson s Disease with OpenCV  Computer Vision  and the piral Wave Test /

imilar articles

K I C K  TA R T  R

’ .
It s time  The Deep Learning for Computer Vision with Pthon Kickstarter is

LIV .
Januar 18  2017,

DP LARNING K  R A    A N D   T  N  O R F LOW RAPRRY PI T U TO R I A L 

Keras and deep learning on the Rasperr Pi

Decemer 18  2017 ,

M AC H I N    L  A R N I N G T U TO R I A L 
-
Non Maximum uppression for Oject Detection in Pthon

,
Novemer 17  2014

You can learn Computer Vision  Deep Learning  and , ,


OpenCV .
, ,
Get our FR 17 page Computer Vision  OpenCV  and Deep Learning Resource

. ’ - , , ,
Guide PDF  Inside ou ll 몭nd m hand picked tutorials  ooks  courses  and liraries to

help ou master CV and DL .
Your email address D O W N L OA D   F O R   F R  

Topics Machine Learning and Computer Vision

Medical Computer Vision
Deep Learning

Dli Lirar
(
Optical Character Recognition  OCR )

/
medded IoT and Computer Vision
Oject Detection

Oject Tracking
Face Applications

OpenCV Tutorials
Image Processing

Rasperr Pi
Interviews

Keras

ooks  & Courses PImageearch

, ,
FR CV  DL  and OpenCV Crash Course Get tarted

Practical Pthon and OpenCV OpenCV Install Guides

Deep Learning for Computer Vision with Aout

Pthon
FAQ

PImageearch Gurus Course
log

Rasperr Pi for Computer Vision
Contact

Privac Polic
© 2021 PImageearch. All Rights Reserved.

You might also like