how to track a red pixel in matlab

To track a red pixel in MATLAB, you can follow these steps:

  1. Read the input video frames using VideoReader.
main.m
v = VideoReader('video.avi');
30 chars
2 lines
  1. Initialize a VideoWriter object to write the output video.
main.m
writerObj = VideoWriter('output.avi');
open(writerObj);
56 chars
3 lines
  1. Define the red color range in the HSV color space using rgb2hsv function.
main.m
redBand = 1; % Red color band in the RGB color space
hsvImage = rgb2hsv(read(v,1)); % Convert the first frame to HSV color space
hueImage = hsvImage(:,:,1); % Extract the hue plane
redHSV = [hueImage < 0.1 | hueImage > 0.9, hsvImage(:,:,2) > 0.4, hsvImage(:,:,3) > 0.4]; % Define the red color range in the HSV color space
323 chars
5 lines
  1. Iterate over the video frames and track the red pixels using regionprops.
main.m
while hasFrame(v)
    frame = readFrame(v); % Read the current frame
    hsvFrame = rgb2hsv(frame); % Convert to HSV space
    redFrame = hsvFrame(:,:,1) < 0.1 | hsvFrame(:,:,1) > 0.9; % Generate a binary mask
    redFrame = imfill(redFrame, 'holes'); % Fill any holes
    stats = regionprops(redFrame, 'centroid', 'area'); % Detect the red pixels
    if ~isempty(stats)
        [~, idx] = max([stats.Area]); % Select the largest red region
        centroid = stats(idx).Centroid; % Extract the centroid
        frame = insertMarker(frame, centroid, 'color', 'red'); % Insert the marker
    end
    writeVideo(writerObj,frame); % Write the frame to the video
end
663 chars
14 lines
  1. Release the video objects.
main.m
close(writerObj);
release(v);
30 chars
3 lines

The output video will contain the red pixel tracking.

gistlibby LogSnag