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.

Load Reference Image

This example uses the reference image image01.png.

refImage = double(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.

fig = figure("Name","Water Level Tracker","Visible","off");
ax1 = subplot(2,2,1);
ax2 = subplot(2,2,3);
ax3 = subplot(2,2,[2,4]); grid on;
h = animatedline(ax3,"Color","red","LineWidth",3);

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.

% Start time-stamp timer for plotting water level against time
t = tic;

while(toc(t) < 180)
   % Read the image captured from the webcam

% Connect to selected webcam
cam = webcam("Lenovo EasyCamera",...

% Acquire webcam image
img = snapshot(cam);

% Clear existing webcam connection
clear cam
    sampleImage = double(img);
    % Store the relative timestamp
    tStamp = toc(t);
    % Subtract the sample image from the reference image
    diffImage = refImage - sampleImage;
    dims = size(diffImage);
    % Extract RGB components from the difference image
    R = uint8(diffImage(:,:,1));
    G = uint8(diffImage(:,:,2));
    B = uint8(diffImage(:,:,3));
    % Convert the difference image to grayscale
    greyDiffImage = zeros(dims(1),dims(2),'uint8');
    for row = 1:dims(1)
        for col = 1:dims(2)
            greyDiffImage(row,col) = (0.2989 * R(row,col)) + (0.5870 * G(row,col)) + (0.1140 * B(row,col));
    % Find mean pixel intensity value across each row of the image
    rowMean = [];
    for row = 1: dims(1)
        rowMean = [rowMean mean(greyDiffImage(row,:))];
    % Find the image pixel corresponding to the top of water level
    % Find the difference instesities between the n+10th and nth pixel.
    % Store this pixel value as the water level, if this intesnity is greater than a threshold
    windowSize = 10;
    intensityThreshold = 15;
    waterLevelPixel = dims(1);
    for rowIndex = 1:length(rowMean)-windowSize
        if rowMean(rowIndex+windowSize) - rowMean(rowIndex) > intensityThreshold
            waterLevelPixel = rowIndex;
    % Display images
    % Display the reference image
    subplot(2,2,1);imshow(uint8(refImage)); hold on;
    title("Reference Image");
    % Display the current water level
    hold on;
    hold off;
    title("Water Level");
    % Plot water level vs/ time
    title('Water level v/s Time');
    xlabel('Time (in s)');
    ylabel('Water level (normalized)');
    addpoints(h,tStamp,abs(1 - (waterLevelPixel/dims(1))));
    fig.Visible = "on"';