MATLAB: This is the part of code for tracking red object in live video but i want to track black color. So what should i do ? data = getsnapshot(vid); % Now to track red objects in real time % we have to subtract the red component % from th

image processingImage Processing Toolboxtrack black objecttrack red object

this is the part of code for tracking red object in live video but i want to track black color. So what should i do ? data = getsnapshot(vid);
% Now to track red objects in real time
% we have to subtract the red component
% from the grayscale image to extract the red components in the image.
diff_im = imsubtract(data(:,:,1), rgb2gray(data));
%Use a median filter to filter out noise
diff_im = medfilt2(diff_im, [3 3]);
% Convert the resulting grayscale image into a binary image.
diff_im = im2bw(diff_im,0.18);
% Remove all those pixels less than 300px
diff_im = bwareaopen(diff_im,300);
% Label all the connected components in the image.
bw = bwlabel(diff_im, 8);
% Here we do the image blob analysis.
% We get a set of properties for each labeled region.
stats = regionprops(bw, 'BoundingBox', 'Centroid');
% Display the image
imshow(data)

Best Answer

Get rid of all that and try this:
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
% Define black as being less than (say) 30 in all color channels.
threshold = 30;
blackPixels = (redChannel < threshold) & (greenChannel < threshold) & (blueChannel < threshold);
% Label all the connected components in the image.
[labeledImage, numRegions] = bwlabel(blackPixels, 8);
% Here we do the image blob analysis.
% We get a set of properties for each labeled region.
stats = regionprops(labeledImage, 'BoundingBox', 'Centroid');
% Display the image
imshow(data)
You can still call bwareaopen() or bwareafilt() if you want to remove regions smaller than a certain area.