Scaler Academy
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Blob detection with OpenCV :::section{.abstract} ## Overview Blob detection is a computer vision technique used to identify regions or areas of an image that share common properties, such as color or texture. In this technique, we aim to identify objects or **regions** of an image that differ from their surroundings and have a **distinct shape**. Blob detection opencv is used in a wide range of applications, including image segmentation, object detection, and tracking. ::: :::section{.scope} ## Scope This article aims to provide an introduction to the concept of **blob detection in computer vision** and image processing. It covers the basics of what a blob is, what blob detection opencv is, and some common techniques for detecting blobs in images. ::: :::section{.main} ## Introduction Blob detection is an important technique in computer vision and image processing. Blob detection is the process of identifying and localizing these regions in an image. Blobs can be useful in a variety of applications, such as object detection, tracking, and recognition. For example, in object recognition, a blob can represent a particular feature of an object, such as an **edge or a corner**. ::: :::section{.main} ## Pre-requisites To understand blob detection opencv, it is helpful to have some familiarity with image processing concepts such as **convolution, filters, and image segmentation**. ::: :::section{.main} ## What is a Blob? In image processing, a blob is a region of an image that appears different from its surroundings in terms of **intensity or color**. Blobs can come in various shapes and sizes and can represent a variety of features, such as **edges, corners, or objects**. ![blob-analysis](https://i.imgur.com/H8SEn2s.png) ::: :::section{.main} ## What is Blob Detection? Blob detection is the process of **identifying and localizing blobs** in an image. The goal of blob detection is to find regions of an image that are significantly different from their surroundings and represent a meaningful feature or object. There are several techniques for blob detection, including **thresholding, Laplacian of Gaussian (LoG) filtering, and the Difference of Gaussian (DoG)** method. These techniques involve convolving the image with various filters to identify regions that have high intensity or high contrast relative to their surroundings. Once blobs have been detected, they can be used for various tasks, such as **object detection, tracking, and recognition**. For example, in object recognition, blobs can be used to represent specific features of an object, such as **edges or corners**, which can then be matched with features in other images to identify the object. ![blob-detection](https://i.imgur.com/sDCBZec.png) ::: :::section{.main} ## Need for Blob Detection Blob detection opencv is needed for various reasons, such as: **Object Detection:** Blob detection helps to identify objects in an image. By detecting and localizing blobs, we can separate objects from the background and determine their size, shape, and position in the image. **Feature Extraction:** Blob detection is used to extract features from an image. These features can be used to classify objects or to match them with objects in other images. **Tracking:** Blob detection helps to track the movement of objects over time. By detecting and tracking blobs, we can determine the direction and speed of objects, which is useful in applications such as autonomous driving or robotics. **Segmentation:** Blob detection is used to segment an image into different regions based on their texture or color. This segmentation is useful for identifying regions of interest in an image and for separating them from the background. Overall, blob detection opencv is an essential technique in computer vision that helps us to understand the structure and composition of an image. It has numerous applications in various fields such as robotics, medical imaging, and autonomous driving. ![image-processing-blob-detection](https://i.imgur.com/vFjdUOP.png) ::: :::section{.main} ## Blob Extraction Blob extraction is the process of **isolating and extracting** blobs from an image. This involves identifying regions in the image that are significantly different from their surroundings and represent a meaningful feature or object. This can be done using various techniques such as **thresholding, filtering, or segmentation**. ::: :::section{.main} ## Blob representation Once blobs have been extracted from an image, they need to be represented in a way that is suitable for further processing and analysis. One common representation is to use a binary image, where the blobs are represented as white pixels and the background as black pixels. Other representations can include using a set of features or descriptors that describe the **size, shape, and texture** of the blobs. ![blob-representation](https://i.imgur.com/bK1uhUT.png) ::: :::section{.main} ## Blob classification Blob classification is the process of **assigning a label or category** to a blob based on its properties. This can be useful in various applications such as object recognition, where blobs can be classified based on the object they represent. Classification can be done using various techniques such as **machine learning or pattern recognition algorithms.** The choice of technique will depend on the specific application and the properties of the blobs being classified. ![blob-classification](https://i.imgur.com/ItPbArw.png) ::: :::section{.main} ## How to perform Background Subtraction? Background subtraction is a common technique used in blob detection opencv to extract **foreground objects** from a video or image sequence. There are several ways to perform background subtraction, and here are three common methods: ### Manual subtraction from the first frame This method involves **manually subtracting** the first frame from all subsequent frames to extract the moving foreground objects. The first frame is considered as the background, and any pixel values that differ from the background by a certain threshold are considered as foreground objects. This method is simple but is prone to errors due to changes in **lighting conditions** or sudden movements in the background. Here is a code snippet to perform manual subtraction from first frame: ```python import cv2 # read the first frame cap = cv2.VideoCapture('video.mp4') ret, frame1 = cap.read() # convert the frame to grayscale gray1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) while True: # read the next frame ret, frame2 = cap.read() if not ret: break # convert the frame to grayscale gray2 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY) # subtract the first frame from the current frame diff = cv2.absdiff(gray1, gray2) # apply a threshold to the difference image thresh = cv2.threshold(diff, 30, 255, cv2.THRESH_BINARY)[1] # display the resulting image cv2.imshow('frame', thresh) if cv2.waitKey(1) & 0xFF == ord('q'): break # update the first frame gray1 = gray2 cap.release() cv2.destroyAllWindows() ``` ### Subtraction using Subtractor MOG2 MOG2 (Mixture of Gaussians) is a popular background subtraction algorithm that models the background as a mixture of **Gaussian distributions**. This algorithm maintains a history of pixel values and updates the Gaussian model of each pixel over time. The algorithm then subtracts the current pixel value from the background model to detect the foreground objects. This method is more **robust to changes** in lighting conditions and can adapt to dynamic backgrounds. Here is a code snippet to perform manual subtraction in blob detection opencv using subtractor MOG2 : ```python import cv2 # create the background subtractor object bs = cv2.createBackgroundSubtractorMOG2() cap = cv2.VideoCapture('video.mp4') while True: # read the next frame ret, frame = cap.read() if not ret: break # apply background subtraction fgmask = bs.apply(frame) # apply morphological opening to remove noise kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel) # display the resulting image cv2.imshow('frame', fgmask) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ``` ![blob-background-subtraction](https://i.imgur.com/7UfYviB.png) ::: :::section{.main} ## Blob Detection using LoG, DoG, and DoH Blob detection is a technique used to identify regions of an image that differ in properties such as brightness, color, or texture. **LoG (Laplacian of Gaussian), DoG (Difference of Gaussian), and DoH (Determinant of Hessian) are commonly used methods for blob detection.** These methods of blob detection opencv apply a filter to the image to highlight regions of interest and then threshold the resulting image to extract the blobs. This method is useful when the foreground objects have distinct texture or color from the background. Here's some code to perform blob detection using LoG (Laplacian of Gaussian), DoG (Difference of Gaussian), and DoH (Determinant of Hessian) filters: ```python import cv2 import numpy as np # load the image img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) # apply LoG filter LoG = cv2.Laplacian(img, cv2.CV_32F) LoG = cv2.GaussianBlur(LoG, (5, 5), 0) # apply DoG filter DoG1 = cv2.GaussianBlur(img, (3, 3), 0) - cv2.GaussianBlur(img, (7, 7), 0) DoG2 = cv2.GaussianBlur(img, (5, 5), 0) - cv2.GaussianBlur(img, (11, 11), 0) # apply DoH filter DoH = cv2.GaussianBlur(img, (5, 5), 0) Dxx = cv2.Sobel(DoH, cv2.CV_64F, 2, 0) Dyy = cv2.Sobel(DoH, cv2.CV_64F, 0, 2) Dxy = cv2.Sobel(DoH, cv2.CV_64F, 1, 1) DoH = (Dxx * Dyy) - (Dxy ** 2) # perform blob detection on the filtered images params = cv2.SimpleBlobDetector_Params() params.filterByArea = True params.minArea = 10 params.filterByCircularity = False params.filterByConvexity = False params.filterByInertia = False detector = cv2.SimpleBlobDetector_create(params) keypoints_LoG = detector.detect(LoG) keypoints_DoG1 = detector.detect(DoG1) keypoints_DoG2 = detector.detect(DoG2) keypoints_DoH = detector.detect(DoH) # draw the detected blobs on the original image img_with_keypoints_LoG = cv2.drawKeypoints(img, keypoints_LoG, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) img_with_keypoints_DoG1 = cv2.drawKeypoints(img, keypoints_DoG1, np.array([]), (0, 255, 0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) img_with_keypoints_DoG2 = cv2.drawKeypoints(img, keypoints_DoG2, np.array([]), (255, 0, 0), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) img_with_keypoints_DoH = cv2.drawKeypoints(img, keypoints_DoH, np.array([]), (0, 255, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # display the resulting images cv2.imshow('LoG', img_with_keypoints_LoG) cv2.imshow('DoG1', img_with_keypoints_DoG1) cv2.imshow('DoG2', img_with_keypoints_DoG2) cv2.imshow('DoH', img_with_keypoints_DoH) cv2.waitKey(0) cv2.destroyAllWindows() ``` ![LoG-DoG-DoH](https://i.imgur.com/VFmygaM.png) ::: :::section{.main} ## Implementing Blob Detection with OpenCV **Import necessary libraries:** ```python import cv2 import numpy as np ``` The cv2 module provides access to various OpenCV functions, while the numpy module is used for array manipulation. **Read an Image using OpenCV imread() function.** ``` img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) ``` The **imread() function** reads the input image file and stores it as a numpy array to perform blob detection opencv. The second argument, cv2.IMREAD_GRAYSCALE, specifies that the image should be read in grayscale mode. **Create or Set up the Simple Blob Detector.** ```python params = cv2.SimpleBlobDetector_Params() params.filterByArea = True params.minArea = 100 params.filterByCircularity = False params.filterByConvexity = False params.filterByInertia = False detector = cv2.SimpleBlobDetector_create(params) ``` We first create a **SimpleBlobDetector_Params object** to set up the detector parameters. We then enable the filter for area, and set the minimum area to detect blobs as 100. We disable the filters for circularity, convexity, and inertia. Finally, we create a **detector object** using the specified parameters. **Input image in the created detector.** ```python keypoints = detector.detect(img) ``` The **detect() function** takes the input grayscale image as argument and detects blobs using the detector object created in the previous step. It returns a list of **KeyPoint objects**, where each KeyPoint represents a detected blob and makes it easier to perform blob detection opencv. **Obtain key points on the image.** ```python img_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) ``` The drawKeypoints() function is used to draw circles around the detected blobs on the input image. We pass the input image, the detected keypoints, an empty array, **a red color tuple (0, 0, 255)**, and the flag **cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS**. The flag ensures that the size of the circle corresponds to the size of the detected blob. **Draw shapes on the Key points found on the image.** ```python cv2.imshow('Blob Detection', img_with_keypoints) cv2.waitKey(0) cv2.destroyAllWindows() ``` Finally, we display the output image using **cv2.imshow()** function, with the window title 'Blob Detection'. We wait for a key press using cv2.waitKey(0) and destroy all open windows using cv2.destroyAllWindows(). Putting all the steps together, here's the complete code for performing blob detection OpenCV: ```python import cv2 import numpy as np # Read the image using OpenCV imread() function img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE) # Create SimpleBlobDetector object with default parameters params = cv2.SimpleBlobDetector_Params() # Set up the detector parameters params.filterByArea = True params.minArea = 100 params.filterByCircularity = False params.filterByConvexity = False params.filterByInertia = False # Create a detector with the parameters detector = cv2.SimpleBlobDetector_create(params) # Detect blobs using the detector keypoints = detector.detect(img) # Draw detected blobs as red circles # cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob img_with_keypoints = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 0, 255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Display the image with the detected blobs cv2.imshow('Blob Detection', img_with_keypoints) # Wait for a key press and then exit cv2.waitKey(0) cv2.destroyAllWindows() ``` **Sample Output** ![blob-detection-filter-by-area](https://i.imgur.com/KtEsJCC.png) ::: :::section{.summary} ## Conclusion * In conclusion, blob detection opencv is a fundamental technique in computer vision that involves identifying objects or regions of an image that have a distinct shape or texture. * It is used in various applications such as object detection, tracking, and segmentation. * OpenCV provides a simple and intuitive interface for performing blob detection using various techniques such as LoG, DoG, and DoH. * By detecting and visualizing blobs, we can gain insights into the structure and composition of an image. * Overall, blob detection is a powerful tool in computer vision and has numerous applications in various fields such as robotics, medical imaging, and autonomous driving. ::: :::section{.main} ## MCQs **1. What is blob detection?** A. A technique used to identify regions or areas of an image that share common properties B. A technique used to remove noise from an image C. A technique used to resize an image D. A technique used to blur an image **Answer: A. A technique used to identify regions or areas of an image that share common properties** **2. Which of the following is a popular technique used for blob detection opencv?** A. Sobel filter B. Canny edge detection C. Laplacian of Gaussian (LoG) filter D. Haar cascade classifier **Answer: C. Laplacian of Gaussian (LoG) filter** **3. Which library is commonly used for performing blob detection?** A. TensorFlow B. PyTorch C. OpenCV D. Keras **Answer: C. OpenCV** :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully