Main Content

Detect and Plot Water Level Change with USB Webcam Live Editor Task

This example shows you how to set up your USB webcam to detect and plot the change in water level. Interactively capture images from a USB webcam using the Acquire Webcam Image task in the Live Editor. For more information on Live Editor tasks, see Add Interactive Tasks to a Live Script.

In this example, you will estimate the level of water in a cup using image subtraction to subtract sample images from a reference image. You will also plot the normalized water levels in real-time. Use the Acquire Webcam Image task in a loop to capture the sample images.

Note: To view and run the code that is shown as image in this example, click Open Live Script or View MATLAB Command (based on your selection for MATLAB Help Preferences).

Load Reference Image

This example uses the reference image image01.png.

refImage = imread("image01.png");

This image is of an empty glass with a resolution of 640 x 480.

Alternatively, you can capture this image using the Acquire Webcam Image task.

Set up Output Window

Set up the figure to plot the water level changes in real time.

Plot Water Level Change

To determine the change in water level, use image subtraction. Subtract each sample image from the reference image. To capture the sample images,use the Acquire Webcam Image task.

Ensure the following in the Live Task:

  1. Select a webcam from the webcams connected to your computer.

  2. Clear the Show image check box to prevent displaying the image in each loop iteration.

  3. Turn off the Autorun feature if you want the live task to execute only when the entire script is executed. To disable autorun, click the autorun icon.

  4. Select Live preview to view the live video from the webcam while adjusting webcam properties.

Do the following:

  1. Capture images using the Acquire Webcam Image task in a loop. You can vary the time for which the loop executes by entering the time in seconds in the textbox.

  2. Subtract each sampleImage from the refImage to get the diffImage.

  3. Extract the the RGB components from diffImage and convert the image to grayscale to reduce the noise in the image.

  4. Find the mean pixel intensity value across each row of the image. The mean pixel intensity is used to find the image pixel corresponding to the top of the water level.

  5. Define a window size and a threshold for the intensity by moving the slider.

  6. Find the difference in the instensities between the n+10th pixel and nth pixel in the windowSize. 'n' is the row index and 10 is the window size used in this example. If the intensity of the pixel value is greater than the threshold intensity, store the pixel value as the water level.

  7. Plot the water level against time.