找到需要识别的脸
faceDetector = vision.CascadeObjectDetector();
读取一段录像并从中获取需识别的脸
videoFileReader = vision.VideoFileReader(‘tilted_face.avi’);
videoFrame = step(videoFileReader);
bbox = step(faceDetector, videoFrame);
在被检测的脸周围构建框架
videoFrame = insertShape(videoFrame, ‘Rectangle’, bbox);
figure; imshow(videoFrame); title(‘Detected face’);
将框架转化为一系列的4个点,即使被识别的脸发生旋转也能够被看到
bboxPoints = bbox2points(bbox(1, :));
在脸部区域识别特征点
points = detectMinEigenFeatures(rgb2gray(videoFrame), ‘ROI’, bbox);
(指定被保留特征值的最小值,一般为1 )
显示特征点
figure, imshow(videoFrame), hold on, title(‘Detected features’);
plot(points);
创建一个点的踪迹将错误进行双向限制,以使它即使在噪声存在时也能正常表示
pointTracker = vision.PointTracker(‘MaxBidirectionalError’, 2);
用初始化框架的点的位置初始化踪迹
points = points.Location;
initialize(pointTracker, points, videoFrame);
初始化一个视频播放器显示结果
videoPlayer = vision.VideoPlayer(‘Position’,…
[100 100 [size(videoFrame, 2), size(videoFrame, 1)]+30]);
复制点用于之前的点和现在的框架之间进行几何转换
oldPoints = points;
while ~isDone(videoFileReader)
创建下一个框架
videoFrame = step(videoFileReader);
跟随点的踪迹,注意有几个点可能会丢失
[points, isFound] = step(pointTracker, videoFrame);
visiblePoints = points(isFound, :);
oldInliers = oldPoints(isFound, :);
if size(visiblePoints, 1) >= 2 % need at least 2 points
在之前的点和新的点之间进行几何转换并建立边界线
[xform, oldInliers, visiblePoints] = estimateGeometricTransform(…
oldInliers, visiblePoints, ‘similarity’, ‘MaxDistance’, 4);
运行边界点的转换
bboxPoints = transformPointsForward(xform, bboxPoints);
在被追随的物体周围插入边界框
bboxPolygon = reshape(bboxPoints’, 1, []);
videoFrame = insertShape(videoFrame, ‘Polygon’, bboxPolygon, …
‘LineWidth’, 2);
(reshape表示重新调整矩阵的行数、列数、维数)
显示被追随的点
videoFrame = insertMarker(videoFrame, visiblePoints, ‘+’, …
‘Color’, ‘white’); (在图像或视频中插入标记)
重置点
oldPoints = visiblePoints;
setPoints(pointTracker, oldPoints); (设置跟随点,用于点需要重新检测且很多点丢失在跟踪过程中,可以使用此方法。)
end
用视频播放器显示被注释的视频框架
step(videoPlayer, videoFrame);
end
清空
release(videoFileReader);
release(videoPlayer);
release(pointTracker);