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

Instance Segmentation With Opencv: Click Here To Download The Source Code To This Post

Uploaded by

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

Instance Segmentation With Opencv: Click Here To Download The Source Code To This Post

Uploaded by

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

MNU

DP LARNING     M A N T I C     G M  N TAT I O N   T U TO R I A L 

Instance segmentation with

OpenCV
 Adrian Roserock on Novemer 26  2018 ,

Click here to download the source code to this post

,
In this tutorial  ou will learn how to perform instance segmentation with

, ,
OpenCV  Pthon  and Deep Learning .

,
ack in eptemer  I saw Microsoft release a reall neat feature to their O몭ce

365 platform  — the ailit to e on a video conference call, lur the
,
ackground  and have our colleagues onl see ou  and not whatever is (
ehind ou).

The GIF at the top of this post demonstrates a similar feature that I have

implemented for the purposes of toda s tutorial ’ .
’ ,
Whether ou re taking the call from a hotel room  working from a downright ugl

, ’
o몭ce uilding  or simpl don t want to clean up around the home o몭ce  the ,
conference call lurring feature can keep the meeting attendees focused on ou

(and not the mess in the ackground).

uch a feature would e especiall helpful for people working from home and

wanting to preserve the privac of their famil memers .

Imagine our workstation eing in clear view of our kitchen  — ou wouldn’t
want our colleagues watching our kids eating dinner or doing their homework !
,
Instead  just pop on the lurring feature and ou re all set ’ .

,
In order to uild such a feature  Microsoft leveraged computer vision  deep ,
, ,
learning  and most notal  instance segmentation .

-
We covered Mask R CNNs for instance segmentation in last week s log post  ’ —
-
toda we are going to take our Mask R CNN implementation and use it to uild a

-
Microsoft O몭ce 365 like video lurring feature .

To learn how to perform instance segmentation with OpenCV  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  

Instance segmentation with OpenCV

Instance Segmentation with OpenCV Demo


Watch later Share
’ () ’
Toda s tutorial is inspired  oth  1  Microsoft s O몭ce 365 video call lurring

( ) .
feature and  2  PImageearch reader Zuair Ahmed  Zuair implemented a

’ (
similar lurring feature using Google s DeepLa  ou can 몭nd his implementation

on his log ).

’ ,
ince we covered instance segmentation in last week s log post  I thought it

was the perfect time to demonstrate how we can mimic the call lurring feature

using OpenCV .

, ’ .
In the 몭rst part of this tutorial  we ll rie몭 cover instance segmentation  From


there we ll use instance segmentation and OpenCV to :

1 Detect and segment the user from the video stream

2 lur the ackground

3 And then add the user ack to the stream itself .


From there we ll look at the results of our OpenCV instance segmentation

,
algorithm  including some of the limitations and drawacks .

What is instance segmentation ?
: .
Figure 1  The di몭erence etween oject detection and instance segmentation  For oject

( ), .
detection  left  a ox is drawn around the individual ojects  In the case of instance segmentation

(right), an attempt is made to determine which pixels elong to each oject. (source)

xplaining instance segmentation is est done with a visual example  — refer to
Figure 1 aove where we have an example of oject detection on the left and

instance segmentation on the right .

Looking at these two examples we can clearl see a di몭erence etween the two .

When performing oject detection we are :

1 Computing the ounding ox  x   ( , )-coordinates for each oject

2 And then associating a class lael with each ounding ox as well .

The prolem is that oject detection tells us nothing regarding the shape of the

oject itself  — all we have is a set of ounding ox coordinates. Instance
, , -
segmentation  on the other hand  computes a pixel wise mask for each oject

in the image .

,
ven if the ojects are of the same class lael  such as the two dogs in the

,
aove image  our instance segmentation algorithm still reports a total of three

:
unique ojects  two dogs and one cat .

Using instance segmentation we now have a more granular understanding of the

oject in the image  — we know speci몭call which (x, )-coordinates the oject
exists in.

,
Furthermore   using instance segmentation we can easil segment our
foreground ojects from the ackground .

’ -
We ll e using a Mask R CNN for instance segmentation in this post .

For a more detailed review of instance segmentation  including comparing and ,
, ,
contrasting image classi몭cation  oject detection  semantic segmentation  and ,
,
instance segmentation  please refer to last week s log post ’ .

Project structure

You can gra the source code and trained Mask R CNN model from the -
“Downloads” section of toda’s post.


Once ou ve extracted the archive and navigated into it  simpl take advantage ,
of the  tree  command to view the director structure in our terminal :

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

Instance segmentation with OpenCV
1.  $ tree ­­dirsfirst
2.  .
3.  ├── mask­rcnn­coco
4.  │   ├── frozen_inference_graph.pb
5.  │   ├── mask_rcnn_inception_v2_coco_2018_01_28.pbtxt
6.  │   └── object_detection_classes_coco.txt
7.  └── instance_segmentation.py
8.  
9.  1 directory, 4 files

(
Our project includes one director  consisting of three 몭les  and one Pthon )
script :

mask­rcnn­coco/ : -
   The Mask R CNN model director contains three 몭les :

frozen_inference_graph.pb : -
   The Mask R CNN model weights  The .
-
weights are pre trained on the COCO dataset .

mask_rcnn_inception_v2_coco_2018_01_28.pbtxt :
   The Mask R CNN -
. ’ +
model con몭guration  If ou d like to uild   train our own model on our

own annotated data, refer to Deep Learning for Computer Vision with

Pthon.

object_detection_classes_coco.txt :
   All 90 classes are listed in this

, .
text 몭le  one per line  Open it in a text editor to see what ojects our model

can recognize .
instance_segmentation.py : ’
   We ll e reviewing this ackground lur script

. ’
toda  Then we ll put it to use and evaluate the results .

Implementing instance segmentation with OpenCV


Let s get started implementing instance segmentation with OpenCV .

Open up the  instance_segmentation.py  몭le and insert the following code :

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

Instance segmentation with OpenCV
1.  # import the necessary packages
2.  from imutils.video import VideoStream
3.  import numpy as np
4.  import argparse
5.  import imutils
6.  import time
7.  import cv2
8.  import os


We ll start o몭 the script  importing our necessar packages  You need the .
(
following installed in our environment  virtual environments are highl

recommended ):

. . + — If ou don’t have OpenCV installed, head over to m
OpenCV 3 4 2  

installation tutorials page. The fastest method for installing on most sstems

is via pip which will install OpenCV 3.4.3 at the time of this writing.

imutils — This is m personal package of computer vision convenience
functions. You ma install imutils via:  pip install ­­upgrade imutils  .

,
Again  I highl recommend that ou place this software in an isolated virtual

environment as ou ma need to accommodate for di몭erent versions for other

projects .


Let s parse our command line arguments :

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

Instance segmentation with OpenCV
10.  # construct the argument parse and parse the arguments
11.  ap = argparse.ArgumentParser()
12.  ap.add_argument("­m", "­­mask­rcnn", required=True,
13.    help="base path to mask­rcnn directory")
14.  ap.add_argument("­c", "­­confidence", type=float, default=0.5,
15.    help="minimum probability to filter weak detections")
16.  ap.add_argument("­t", "­­threshold", type=float, default=0.3,
17.    help="minimum threshold for pixel­wise mask segmentation")
18.  ap.add_argument("­k", "­­kernel", type=int, default=41,
19.    help="size of gaussian blur kernel")
20.  args = vars(ap.parse_args())

Descriptions of each command line argument can e found elow :

­­mask­rcnn : -
   The ase path to the Mask R CNN director  We reviewed the .

three 몭les in this director in the  Project structure  section aove ” .

­­confidence :
   The minimum proailit to 몭lter out weak detections  I ve . ’
set this value to a default of  0.5 ,
   ut ou can easil pass di몭erent values via

the command line .

­­threshold :
   Our minimum threshold for the pixel wise mask segmentation - .
The default is set to  0.3 .
 

­­kernel : .
   The size of the Gaussian lur kernel  I found that a 41 x 41 kernel

,
looks prett good  so a default of  41  is set.

For a review on how command line arguments work  e sure to read this guide , .


Let s load our laels and our OpenCV instance segmentation model :

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

Instance segmentation with OpenCV
22.  # load the COCO class labels our Mask R­CNN was trained on
23.  labelsPath = os.path.sep.join([args["mask_rcnn"],
24.    "object_detection_classes_coco.txt"])
25.  LABELS = open(labelsPath).read().strip().split("\n")
26.  
27.  # derive the paths to the Mask R­CNN weights and model configuration
28.  weightsPath = os.path.sep.join([args["mask_rcnn"],
29.    "frozen_inference_graph.pb"])
30.  configPath = os.path.sep.join([args["mask_rcnn"],
31.    "mask_rcnn_inception_v2_coco_2018_01_28.pbtxt"])
32.  
33.  # load our Mask R­CNN trained on the COCO dataset (90 classes)
34.  # from disk
35.  print("[INFO] loading Mask R­CNN from disk...")
36.  net = cv2.dnn.readNetFromTensorflow(weightsPath, configPath)

Our laels 몭le needs to e located in the  mask­rcnn­coco/  director  — the


.
director speci몭ed via command line argument  Lines 23 and 24 uild the 

labelsPath  and then Line 25 reads the  LABELS  into a list .


The same goes for our  weightsPath  and  configPath  which are uilt on Lines

28 31- .

,
Using these two paths  we take advantage of the  dnn  module to initialize the

neural  net ( ). -
  Line 36  This call loads the Mask R CNN into memor efore we

(
start processing frames  we onl need to load it once ).


Let s construct our lur kernel and start our wecam video stream :

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

Instance segmentation with OpenCV
38.  # construct the kernel for the Gaussian blur and initialize whether
39.  # or not we are in "privacy mode"
40.  K = (args["kernel"], args["kernel"])
41.  privacy = False
42.  
43.  # initialize the video stream, then allow the camera sensor to warm up
44.  print("[INFO] starting video stream...")
45.  vs = VideoStream(src=0).start()
46.  time.sleep(2.0)

The lur kernel tuple is de몭ned on Line 40 .

:“ ”
Our project has two modes   normal mode  and  privac mode “ ”. Thus, a 
privacy .
 oolean is used for the mode logic  It is initialized to  False  on Line

41.

Our wecam video stream is started on Line 45 where we pause for two

seconds to allow the sensor to warm up  Line 46 ( ).

,
Now that all of our variales and ojects are initialized  let s start processing ’
frames from the wecam :

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

Instance segmentation with OpenCV
48.  # loop over frames from the video file stream
49.  while True:
50.    # grab the frame from the threaded video stream
51.    frame = vs.read()
52.  
53.    # resize the frame to have a width of 600 pixels (while
54.    # maintaining the aspect ratio), and then grab the image
55.    # dimensions
56.    frame = imutils.resize(frame, width=600)
57.    (H, W) = frame.shape[:2]
58.  
59.    # construct a blob from the input image and then perform a
60.    # forward pass of the Mask R­CNN, giving us (1) the bounding
61.    # box coordinates of the objects in the image along with (2)
62.    # the pixel­wise segmentation for each specific object
63.    blob = cv2.dnn.blobFromImage(frame, swapRB=True, crop=False)
64.    net.setInput(blob)
65.    (boxes, masks) = net.forward(["detection_out_final",
66.      "detection_masks"])

Our frame processing loop egins on Line 49 .

, ’
At each iteration  we ll gra a  frame (
  Line 51  and  ) resize  it to a known width ,
maintaining aspect ratio  Line 56 ( ).

,
For scaling purposes later  we go ahead and extract the dimensions of the 

frame (
  Line 57 ).

,
Then  we construct a  blob  and complete a forward pass through the network

(Lines 63-66). You can read more aout how this process works in this previous
log post.

The result is oth  boxes  and  masks . ’


   We ll e taking advantage of the  masks  ,
ut we also need to use the data contained in  boxes   .


Let s sort the indexes and initialize variales :

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

Instance segmentation with OpenCV
68.    # sort the indexes of the bounding boxes in by their corresponding
69.    # prediction probability (in descending order)
70.    idxs = np.argsort(boxes[0, 0, :, 2])[::­1]
71.  
72.    # initialize the mask, ROI, and coordinates of the person for the
73.    # current frame
74.    mask = None
75.    roi = None
76.    coords = None

Line 70 sorts the indexes of the ounding oxes  their corresponding

. ’
prediction proailit  We ll e making the assumption that the person with the

largest corresponding detection proailit is our user .

We then initialize the  mask , roi  , and ounding ox  coords  (Lines 74-76).


   


Let s loop over the indexes and 몭lter the results :

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

Instance segmentation with OpenCV
78.    # loop over the indexes
79.    for i in idxs:
80.      # extract the class ID of the detection along with the
81.      # confidence (i.e., probability) associated with the
82.      # prediction
83.      classID = int(boxes[0, 0, i, 1])
84.      confidence = boxes[0, 0, i, 2]
85.  
86.      # if the detection is not the 'person' class, ignore it
87.      if LABELS[classID] != "person":
88.        continue
89.  
90.      # filter out weak predictions by ensuring the detected
91.      # probability is greater than the minimum probability
92.      if confidence > args["confidence"]:
93.        # scale the bounding box coordinates back relative to the
94.        # size of the image and then compute the width and the
95.        # height of the bounding box
96.        box = boxes[0, 0, i, 3:7] * np.array([W, H, W, H])
97.        (startX, startY, endX, endY) = box.astype("int")
98.        coords = (startX, startY, endX, endY)
99.        boxW = endX ­ startX
100.        boxH = endY ­ startY

We egin looping over the  idxs  on Line 79 .

We then extract the  classID  and  confidence  using  boxes  and the current

(
index  Lines 83 and 84 ).

, ’ — we onl care aout the  "person"
usequentl  we ll perform our 몭rst 몭lter 

class. If an other oject class is encountered, we’ll continue to the next index

(Lines 87 and 88).

Our next 몭lter ensures the  confidence  of the prediction exceeds the threshold

set via command line arguments  Line 92 ( ).

, ’
If we pass that test  then we ll scale the ounding  box  coordinates ack to the

( ).
relative dimensions of the image  Lines 96  We then extract the  coords  and

oject width/height (Lines 97-100).


Let s compute our mask and extract the ROI :

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

Instance segmentation with OpenCV
102.        # extract the pixel­wise segmentation for the object,
103.        # resize the mask such that it's the same dimensions of
104.        # the bounding box, and then finally threshold to create
105.        # a *binary* mask
106.        mask = masks[i, classID]
107.        mask = cv2.resize(mask, (boxW, boxH),
108.          interpolation=cv2.INTER_NEAREST)
109.        mask = (mask > args["threshold"])
110.  
111.        # extract the ROI and break from the loop (since we make
112.        # the assumption there is only *one* person in the frame
113.        # who is also the person with the highest prediction
114.        # confidence)
115.        roi = frame[startY:endY, startX:endX][mask]
116.        break

-
Lines 106 109 extract the  mask , ,
   resize it  and appl the threshold to create the

.
inar mask itself  An example mask is shown in Figure 2 :

:
Figure 2  The inar mask computed via

instance segmentation of me in front of m

wecam using OpenCV and instance

.
segmentation  Computing the mask is part of

the privac 몭lter pipeline.

In Figure 2 aove all white pixels are assumed to e a person  i e  the ( . .,
)
foreground  while all lack pixels are the ackground .

With the  mask , ’
   we ll also compute the  roi ( )
  Line 115  via NumP arra slicing .

We then  break (
 from the loop on Line 116  since we have found the  "person"
with the largest proailit ).


Let s initialize our output frame and compute our lur if we are in  privac mode “ ”:

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

Instance segmentation with OpenCV
118.    # initialize our output frame
119.    output = frame.copy()
120.  
121.    # if the mask is not None *and* we are in privacy mode, then we
122.    # know we can apply the mask and ROI to the output image
123.    if mask is not None and privacy:
124.      # blur the output frame
125.      output = cv2.GaussianBlur(output, K, 0)
126.  
127.      # add the ROI to the output frame for only the masked region
128.      (startX, startY, endX, endY) = coords
129.      output[startY:endY, startX:endX][mask] = roi

Our  output  frame is simpl a  copy  of the original  frame (


  Line 119 ).

If we oth :

1 Have a  mask  that is not empt

2 And we are in    ” privacy  mode ”…

…then we’ll lur the ackground (using our kernel) and appl the  mask  to the 

output  frame (Lines 123-129).


Now let s displa the  output  image and handle kepresses :

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

Instance segmentation with OpenCV
131.    # show the output frame
132.    cv2.imshow("Video Call", output)
133.    key = cv2.waitKey(1) & 0xFF
134.  
135.    # if the `p` key was pressed, toggle privacy mode
136.    if key == ord("p"):
137.      privacy = not privacy
138.  
139.    # if the `q` key was pressed, break from the loop
140.    elif key == ord("q"):
141.      break
142.  
143.  # do a bit of cleanup
144.  cv2.destroyAllWindows()
145.  vs.stop()

Our  output  frame is displaed via Line 132 .

( ).
Kepresses are captured  Line 133  Two kes cause di몭erent ehaviors  Lines (
-
136 141 ):

"p" :
   When this ke is pressed   , “ privacy ”
 mode  is toggled either on or o몭 .

"q" : , ’
   If this ke is pressed  we ll reak out of the loop and  quit  the script “ ” .

,
Whenever we do quit  Lines 144 and 145 close the open window and stop the

video stream .
Instance segmentation results


Now that we ve implemented our OpenCV instance segmentation algorithm  let s , ’
see it in action !

“ ”
e sure to use the  Downloads  section of this log post to download the code

and Mask R CNN model- .

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

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

Instance segmentation with OpenCV
1.  $ python instance_segmentation.py ­­mask­rcnn mask­rcnn­coco ­­kernel 41
2.  [INFO] loading Mask R­CNN from disk...
3.  [INFO] starting video stream...

: “ ”
Figure 3  M demonstration of a  privac 몭lter  for we chatting .

I ve used OpenCV and Pthon to perform instance segmentation

( ),
to 몭nd the prominent person  me  and then applied lurring to

the ackground .

Here ou can see a short GIF of me demoing our instance segmentation

pipeline .

,
In this image  I am meant to e the  conference call attendee “ ”. Trisha, m wife, is
working in the ackground .


 enaling  privac mode  I can ” :

1 Use OpenCV instance segmentation to 몭nd the person detection with the

(
largest corresponding proailit  most likel that will e the person closest
to the camera ).

2 lur the ackground of the video stream .

3 , -
Overla the segmented  non lurr person ack onto the video stream .

,
I have included a video demo  including m commentar  elow , :

Instance Segmentation with OpenCV Demo


Watch later Share

’ -
You ll immediatel notice that we are not otaining true real time performance

though  — we’re onl processing a few frames per second. Wh is this?

How come our OpenCV instance segmentation pipeline isn t faster ’ ?

,
To answer those questions  e sure to refer to the section elow .

, ,
Limitations  drawacks  and potential improvements

The 몭rst limitation is the most ovious one  — our OpenCV instance
segmentation implementation is too slow to run in real time - .


On m Intel Xeon W we re onl processing a few frames per second .
-
In order to otain true real time instance segmentation performance  we ,
would need to leverage our GPU .

ut therein lies the prolem :


OpenCV s GPU support for its  dnn   module is fairl limited .

,
Currentl  it mainl supports Intel GPUs .

,
NVIDIA CUDA GPU support is in development  ut is currentl not availale .

Once OpenCV o몭ciall supports NVIDIA GPUs for the  dnn ’
  module we ll e

- (
more easil ale to uild real time  and even super real time  deep learning - )
applications .

,
ut for now  this OpenCV instance segmentation tutorial serves as an

educational demo of :

1 ’
What s currentl possile

2 And what will e possile in a few months

Another improvement we can make is related to the overlaing of the

segmented person ack on the lurred ackground .


When ou compare our implementation to Microsoft s O몭ce 365 video lurring

, ’ ’
feature  ou ll see that Microsoft s is much more  smooth “ ”.

We can mimic this feature  utilizing a it of alpha lending .

A simple et e몭ective update to our instance segmentation pipeline would e to

potentiall :

1 Use morphological operations to increase the size of our mask

2 Appl a small amount of Gaussian lurring to the mask itself  helping ,
smooth the mask

3 cale the mask values to the range  0  1 [ , ]

4 Create an alpha laer using the scaled mask
5 +
Overla the smoothed mask   person ROI on the lurred ackground

,
Alternativel  ou could compute the contours of the mask itself and then appl

“ ”
contour approximation to help create a  more smoothed  mask .

— it’s just something I thought
Please note that I have not tried this algorithm 

of o몭 the top of m head that I thought could give visuall pleasing results.

If ou wish to implement this instance segmentation update I would suggest

reading this post where I discuss alpha lending in more detail .

' ?
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 toda s log post ou learned how to perform instance segmentation using

OpenCV, Deep Learning, and Pthon.

Instance segmentation is the process of :

1 Detecting each oject in an image

2 -
Computing a pixel wise mask for each oject

,
ven if ojects are of the same class  an instance segmentation should return

a unique mask for each oject .

In order to appl instance segmentation with OpenCV  we used our Mask R CNN , -


implementation from last week .

- “
We then used our Mask R CNN model to uild a  video conference call lurring

”, similar to the feature Microsoft released for O몭ce 365 ack in the
feature

summer.

Our instance segmentation results were similar to Microsoft s feature  however ’ ; ,


-
we could not otain true real time performance since OpenCV s GPU support for ’
the  dnn   module is currentl quite limited .

, ’ ,
Therefore  toda s tutorial serves as a demo  highlighting what is currentl

possile and what will e possile when OpenCV s GPU support increases ’ .

I hope ou enjoed toda s 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 :
-
Mask R CNN with OpenCV

:
Next Article

Deep Learning and Medical Image Analsis with Keras

:
24 responses to  Instance segmentation with OpenCV

Zuair Ahmed

, :
Novemer 26  2018 at 10 18 am

,
Adrian  

Wonderful post as alwas and thanks for the mention  ὤ
Adrian Roserock

,
Novemer 26  2018 at 2 23 pm :

Thanks Zuar   !ὤ

sophia

,
Novemer 27  2018 at 9 59 am :

,
Hello Zuair  Is the link to our log

(http://zuairahmed.net/2018/07/17/ackground-lurring-with-semantic-
image-segmentation-using-deeplav3/) correct? I’m getting an rror 403

– This we app is stopped.

Thanks .

Adrian Roserock

,
Novemer 30  2018 at 9 30 am :

.
I just checked and it seems to e working for me  Perhaps it was just a

temporar hiccup .

Arthur Zhang

,
Novemer 27  2018 at 2 37 am :

Reall practical course !

Adrian Roserock

,
Novemer 30  2018 at 9 34 am :

,
Thanks so much  Arthur !
Wilf

,
Decemer 6  2018 at 9 22 am :

This was terri몭c !!

:
Question  what is the frame processing speed on our computer   .
M laptop does not have a GPU so m processing times are V--R-Y slow.  

(I read in a video clip and stored the “private” lurred frames to disk to etter
enjo the ackground lurring)

Adrian Roserock

,
Decemer 6  2018 at 9 25 am :

.
M CPU is onl processing a few frames per second  For true real time -
performance using this method ou would need a GPU  which OpenCV s ( ’
GPU support is currentl a it limited ).

jstumpin

,
Decemer 9  2018 at 10 38 pm :

Unless someone made a PR to OpenCV repo to optimize the said kernel

(https://githu.com/opencv/opencv/issues/12155#issuecomment-
445120430), CPU will alwas e faster should anone decide to use

NVIDIA/AMD GPU for DNN inferencing on OpenCV. Otherwise, just stick

to CAFF/TNORFLOW/TORCH etc.

suresh

,
Feruar 4  2020 at 11 50 pm :

,
HI Adrian  What is the est wa to achieve decent speed on CPU  the ,
<.
current FP is  1  Please suggest .
Adrian Roserock

,
Feruar 5  2020 at 1 54 pm :

/
I would suggest ou look into model weight quantization and

.
optimization  Those methods can help make models run faster on

, ’ .
our CPU  ut ou ll likel have to sacri몭ce a it of accurac

Angelo

,
Decemer 8  2018 at 5 22 pm :

,
Too slow to run into rasperr pi  thanks for the info

Muhammad ilal

,
Januar 11  2019 at 6 51 am :

, !
hello  Adrian   

,
an amazingl useful write  like alwas   .
Can ou please guide me, I want to run image segmentation on Rasperr Pi

3+ 

1. If i train a custom Ca몭e for di몭erent terrains (i.e: grass, Roads, Rock,

water/wet, and di몭erent shades of sk) 

2. Question: if i reduce the Classes (to just 2 or 3) would i e ale to achieve

at-least 2-3 Fps on m Rasperr ?

Thanks in advance  3  <
-ig fan to ou.

Adrian Roserock

,
Januar 11  2019 at 9 24 am :
, -
The Rasperr Pi will e far  far too slow to run a Mask R CNN network  You .
- , ’
will not e ale to get 2 3 FP for instance segmentation on a Pi  it s just

too slow .

ourah

,
Januar 29  2019 at 6 12 am :

!
Amazing work   Thank ou

Adrian Roserock

,
Januar 29  2019 at 6 26 am :

Thanks ourah !

PRAHANT ANOD

,
March 19  2019 at 6 11 am :

, .
Hi Adrian  thanks for the great tutorial  I would like to know whether I can use

this for extracting human silhouette extraction or there is a etter approach to

.
tackle it  Thanks

Adrian Roserock

,
March 19  2019 at 9 51 am :

,
Yes  instance segmentation is the suggested technique to otain a pixel -
wise mask of a person .
santanu

,
Jul 5  2019 at 3 17 pm :

( ,
Which one is est for instance segmentation mask rcnn  segnet and deepla )
??

Adrian Roserock

,
Jul 10  2019 at 9 57 am :

’ “ ” . ’
There isn t one  est  network for instance segmentation  It s dependent

on our dataset, our project requirements, and an computational

limitations on the machine ou’re either training or deploing to. You need

to alance of all these when selecting an architecture.

avantika

,
eptemer 4  2019 at 3 36 am :

-
wh did ou use Mask R CNN for this video lurring e몭ect over YOLO or D

? The also use deep learning

Adrian Roserock

,
eptemer 5  2019 at 10 24 am :

- .
Mask R CNN is an instance segmentation algorithm  It gives ou a pixel -
. .
wise mask  YOLO and Ds are oject detectors  The onl produce

ounding oxes .

Ton

,
Novemer 9  2019 at 9 33 pm :
How would ou replace the video feed from our camera with a prerecorded

video?

Adrian Roserock

,
Novemer 14  2019 at 9 30 am :

You would use the  cv2.VideoCapture function and pass it in the path to
the video 몭le. If ou’ve never done that efore ou can refer to Practical

Pthon and OpenCV which will teach ou how to do exactl that.

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

- , ,
Image egmentation with Mask R CNN  GraCut  and OpenCV

‘ ’ : % faster YOLO, D, and Mask R-CNN
OpenCV  dnn  with NVIDIA GPUs  1549

-
Mask R CNN with OpenCV
emantic segmentation with OpenCV and deep learning

What is Deep Learning ?

imilar articles

DP LARNING K  R A    A N D   T  N  O R F LOW OJCT DTCTION

O P  N C V   T U TO R I A L  T U TO R I A L 

- ,
R CNN oject detection with Keras  TensorFlow  and Deep Learning ,
,
Jul 13  2020

O P  N C V   T U TO R I A L  T U TO R I A L 

, ,
Resolving macO  OpenCV  and Homerew install errors

,
Ma 15  2017
DP LARNING DLI FAC    A P P L I C AT I O N  T U TO R I A L 

, ,
Face recognition with OpenCV  Pthon  and deep learning

,
June 18  2018

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 .
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