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).
This example uses the reference image
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 the figure to plot the water level changes in real time.
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:
Select a webcam from the webcams connected to your computer.
Clear the Show image check box to prevent displaying the image in each loop iteration.
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.
Select Live preview to view the live video from the webcam while adjusting webcam properties.
Do the following:
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.
sampleImage from the
refImage to get the
Extract the the RGB components from
diffImage and convert the image to grayscale to reduce the noise in the image.
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.
Define a window size and a threshold for the intensity by moving the slider.
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.
Plot the water level against time.