MATLAB: How to count number of car passing through virtual line when centroid is already calculated

blob analysiscar countingcentriodComputer Vision ToolboxImage Processing Toolbox

I have found some solution from MATLAB answer. Where Image analyst has already answer this question.
if ~isempty([centroid])
S =size(centroid)
for i = 1: S(1)
ynew = centroid(i,2)
if sign(ynew-192) ~= sign(yold(i)-192)
counter = counter +1
end
yold(i)=ynew;
end
However, when a new car is detected after some frames. It count car once again as per using the yold and ynew information.

Best Answer

Keep a matrix of centroids of currently known objects, together with a flag indicating whether the object had been counted.
In each step, detect current objects. For each detected object, go through and match it to the closest old object (that is, a prediction that objects move sufficiently alike in speed that any given object probably moved there from the closest known previous object.) Copy the old "has been counted" status to the new information array. Then, if the object is not marked as already counted, then see if the old location and new location together cross the virtual line; if so update the global count and marked the object as counted in the new data. For new objects that had no close-enough previous match, leave them marked as uncounted in the new array. Then, having processed all current objects, throw away the previous information and make the current information the "old" information.
Related Question