function [legMotionArray, projectedDistMatrix] = MotionDetectionFunction(movName,distanceThreshold) % MotionDetectionFunction loads the sorted leg array associated to the movie, finds the moving legs % at each time, and saves the final movement array. % %%%%%%% Arguments: % movName [string]: name of movie to consider (loads sorted leg array) % saveDirectoryNameMotionTracking [string]: name of folder (in current directory) where the motion detection % array is (standard folder name is: "Motion Detection") % distanceThreshold [double OR 'default']: distance leg endpoint moves before the leg is considered % "in motion". Default value is 8. if isequal(distanceThreshold, 'default') distanceThreshold = 8; end % Load Data % Final Leg Endpoints Array (from user corrected movie in Final folder) finalLegEndpointsStoreLoadString = strrep(movName, '.avi', '_finalLegEndPointsStore.mat'); load(finalLegEndpointsStoreLoadString) % loads finalLegEndpointsStore centroidCoordinatesLoadString = strrep(movName, '.avi', '_centroidCoordinates.mat'); headDirectionCoordinatesLoadString = strrep(movName, '.avi', '_headDirectionCoordinates.mat'); frameFlagsLoadString = strrep(movName, '.avi', '_frameFlags.mat'); load(centroidCoordinatesLoadString) load(headDirectionCoordinatesLoadString) load(frameFlagsLoadString) numFrames = length(finalLegEndpointsStore); %#ok<*USENS> legMotionArray = zeros(numFrames-1,6); % for storing motion of each leg. Use numFrames-1 since we need the difference % in leg endpoints between frames to detect motion % Motion Detection % find distance each legged moved in direction parallel to previous frame's body axis (projection) projectedDistMatrix = zeros(numFrames-1,6); v = headDirectionCoordinates-centroidCoordinates; v = v(1:end-1,:); for i = 1:numFrames-1 wMatrix = finalLegEndpointsStore{i+1}-finalLegEndpointsStore{i}; for j = 1:6 projectedDistMatrix(i,j) = dot(wMatrix(j,:),v(i,:))/norm(v(i,:)); end end for i = 1:numFrames-1 for j = 1:6 legMotionArray(i,j) = (projectedDistMatrix(i,j) >= distanceThreshold); end end % Save projectedDistMatrix (note: we don't save leg motion array since that analysis is done in R) if isempty(find(frameFlags ~= 10)) movNameAtOutput = strrep(movName, '.avi', '_MotionDetection.avi'); projectedDistMatrixSaveString = strrep(movNameAtOutput,'.avi','_projectedDistanceMatrix.mat'); save(projectedDistMatrixSaveString,'projectedDistMatrix') end end