<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Video Tracking for Behaviour Research]]></title><description><![CDATA[Video Tracking for Behaviour Research]]></description><link>https://videotracking.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:26:51 GMT</lastBuildDate><atom:link href="https://videotracking.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Practising balance in virtual reality: what to train and what to measure]]></title><description><![CDATA[Weight shift, standing endurance and stepping can be practised in a headset, but only if you also measure balance in the real world.]]></description><link>https://videotracking.hashnode.dev/practising-balance-in-virtual-reality-what-to-train-and-what-to-measure</link><guid isPermaLink="true">https://videotracking.hashnode.dev/practising-balance-in-virtual-reality-what-to-train-and-what-to-measure</guid><category><![CDATA[Virtual Reality]]></category><category><![CDATA[rehabilitation]]></category><category><![CDATA[balance]]></category><category><![CDATA[physiotherapy]]></category><category><![CDATA[stroke-rehab]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:14:37 GMT</pubDate><content:encoded><![CDATA[<p>Balance training asks a person to keep their posture, shift their weight, or step, often while doing something with their eyes or attention. Virtual reality is attractive here because the visual world can be controlled, repeated and made slightly more difficult without leaving a safe space. It is not a substitute for a clear therapeutic goal. The scene is a way to practise; the outcome is whether balance improves in the clinic and in daily life.</p>
<h2>Choose a real-world skill, then build a virtual task around it</h2>
<p>Useful targets are ordinary ones: standing with a narrower base, shifting weight to one side in order to reach or to step, turning the head while keeping posture, stepping in a stated direction, or walking with the eyes taking in a moving scene. A VR task should make that skill happen at a dose you can describe: how long, how many repetitions, how hard, and with how much support.</p>
<p>Visual flow is the ingredient VR adds most easily. A moving scene can challenge postural control even when the floor is firm. That can be useful, but it can also produce dizziness, and it can tempt you to train "not falling in the game" rather than standing up to reach a shelf. Keep the visual challenge related to the skill you care about, and increase it only when the person can perform the basic posture safely.</p>
<p>If the person has had a stroke, an episode of imbalance, or a high risk of falls, the same rule applies, with a stricter safety margin. Weakness, neglect, reduced sensation and visual problems all change what a headset is asking of them. The task should be set by a clinician who has seen those impairments, not only by a difficulty slider in the software. A general orientation to how VR is used in rehabilitation practice is at <a href="https://virtualrealityrehabilitation.com/">Virtual Reality Rehabilitation</a>.</p>
<h2>Safety is part of the protocol, not a footnote</h2>
<p>A headset blocks the real room. People trip on cables, reach for virtual objects that are not there, or take a step they would not have taken with a full view of the floor. Plan for that.</p>
<ul>
<li>Use a harness, a parallel-bar setup, or a stand-by assistant when the risk of a fall is more than trivial.</li>
<li>Clear the real floor of obstacles and set a fixed standing or stepping area.</li>
<li>Manage cables, or use a wireless headset that still has a defined space.</li>
<li>Start in sitting or with light support if standing in a headset is new.</li>
<li>Stop for dizziness, pain, or a loss of confidence that makes the next attempt unsafe.</li>
</ul>
<p>The first session is often an equipment and safety session as well as a therapy session. That time is not wasted. It tells you whether the person can tolerate the display and whether your staff can manage the setup in an ordinary appointment slot.</p>
<h2>Measure balance outside the headset</h2>
<p>In-game scores, stars and "levels completed" can motivate practice, and they can show that the person did the virtual task. They are not, on their own, evidence that balance has improved. Include measures that would make sense if the same therapy had been done without VR: a standard clinical balance scale, a timed standing or walking test, a count of near-falls or completed daily tasks, or a quiet-standing measure if you have the equipment and a reason to use it.</p>
<p>Take those measures at the start and at a planned later point, under conditions that do not depend on the headset. If the only improvement is a higher game score, you have learned that the person got better at the game.</p>
<p>It also helps to record dose: minutes of standing or stepping practice, number of sessions attended, and how much physical assistance was given. Two people can "do VR balance training" with very different amounts of actual postural work.</p>
<h2>Keep the difficulty honest</h2>
<p>If the virtual task is too easy, the person is entertained but not trained. If it is too hard, they stiffen, rely on the assistant, or become fearful, and the practice is no longer the skill you intended. Adjust one thing at a time: base of support, reaching distance, speed of the visual scene, or a second task such as counting or carrying, not all of them at once.</p>
<p>When you write up a programme, name the skill, the virtual task, the safety arrangement, the dose, and the real-world measures. That is enough for another clinician to decide whether your setup is relevant to their patient. The headset is optional in that sentence. The measured balance is not.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Presence, cybersickness and pacing in VR therapy]]></title><description><![CDATA[A well-designed exposure fails if the patient spends the session fighting nausea or feeling that the scene is not real.]]></description><link>https://videotracking.hashnode.dev/presence-cybersickness-and-pacing-in-vr-therapy</link><guid isPermaLink="true">https://videotracking.hashnode.dev/presence-cybersickness-and-pacing-in-vr-therapy</guid><category><![CDATA[Virtual Reality]]></category><category><![CDATA[VR Therapy]]></category><category><![CDATA[clinical-practice]]></category><category><![CDATA[Exposure Therapy]]></category><category><![CDATA[cybersickness]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:11:00 GMT</pubDate><content:encoded><![CDATA[<p>Virtual reality is used in therapy because a scene can be presented, repeated and adjusted in a way that a real street, aircraft or social setting often cannot. That advantage only holds if the patient experiences the scene as a place to respond to, rather than as a flat video, and if they can stay in the headset long enough for the session to do its work. Presence and cybersickness are therefore clinical issues, not only technical ones. They should be planned for in the first sessions, not discovered when someone drops out.</p>
<h2>Presence is the feeling that the scene is a place</h2>
<p>Presence, in this setting, is the sense of being in the virtual environment rather than looking at a display. It does not require a perfect image. It does require that what the patient sees stays in step with their head and, where relevant, their hands or body, and that the scene contains enough of the cues that matter for their fear or concern.</p>
<p>Lag, judder, a badly fitted headset, a scene that clips or drifts, and frequent pauses to debug the software all cut presence. So does an environment that is visually rich but missing the one cue the patient actually fears. A short conversation before the first exposure about what feels real, and what feels missing, is more useful than adding detail at random.</p>
<p>Presence can be too high as well as too low. If a patient is overwhelmed in the first minutes, the task is not to turn the quality down in a vague way, but to reduce the difficulty of the scene, as you would in any graded exposure: greater distance, less crowded view, shorter periods in the headset, or a lower-intensity version of the same situation. A <a href="https://virtualrealitytherapy.info/videos/">collection of VR therapy session videos</a> gives a sense of how different clinical scenes are actually presented, which is a better starting point than a technical specification alone.</p>
<h2>Cybersickness is common enough to plan for</h2>
<p>A mismatch between what the eyes see and what the balance system feels can produce symptoms similar to motion sickness: nausea, sweating, dizziness, headache or visual discomfort. Movement in the scene that the patient does not produce themselves, such as a simulated vehicle or a smooth virtual walk while they sit still, is a frequent trigger. Long first sessions, a poorly set headset, and a hot room make it worse.</p>
<p>Plan a first visit that is shorter than a full treatment session, with permission to stop at once if symptoms build. Teach a simple stop signal. Have a stable chair or a place to sit after the headset comes off, and allow time before the patient has to travel. If symptoms appear, do not push through a long exposure in the hope that fear will habituate: you will not know whether later avoidance is about the therapy content or about feeling unwell.</p>
<p>Simple adjustments often help: more stable movement, letting the patient control motion, reducing visual flow in the periphery, correcting the fit and the inter-pupillary setting, and building time in the headset gradually. If a patient cannot tolerate the display at all, they need a different route, not a scolding about perseverance.</p>
<h2>Pace the early sessions and write down what happened</h2>
<p>The first sessions have two jobs: to introduce the environment safely, and to begin the therapeutic work at a level the patient can use. Those jobs are easy to confuse. A technically impressive first session that produces sickness or a panic that was not contained is a poor start, even if the software behaved.</p>
<p>Agree a simple intensity ladder in advance, as you would without a headset, and move along it only when the patient can stay in the current step with a manageable level of distress. Record, in ordinary clinical notes or a short session log:</p>
<ul>
<li>how long they were in the headset, including breaks</li>
<li>which scene and which difficulty step you used</li>
<li>a brief rating of distress, and a brief rating of how real the scene felt</li>
<li>any sickness or discomfort, and what you changed</li>
<li>whether the session ended as planned or was stopped early</li>
</ul>
<p>Those notes protect the next clinician, and they stop you from raising difficulty on a day when the limiting factor was a bad fit or a night of poor sleep. They also make research and audit possible without claiming more precision than a short rating can bear.</p>
<p>If presence is consistently low, fix the fit, the lag and the relevant cues before you conclude that VR is the wrong modality. If sickness is consistently high despite slower pacing and simpler movement, it may indeed be the wrong modality for that person. Either conclusion is easier to reach when you have treated presence and comfort as part of the treatment plan, not as an afterthought about the equipment.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Tracking two or more animals in the same arena]]></title><description><![CDATA[Identity swaps are the usual failure mode. Here is how to reduce them and what to report when they still happen.]]></description><link>https://videotracking.hashnode.dev/tracking-two-or-more-animals-in-the-same-arena</link><guid isPermaLink="true">https://videotracking.hashnode.dev/tracking-two-or-more-animals-in-the-same-arena</guid><category><![CDATA[video-tracking]]></category><category><![CDATA[animal-behaviour]]></category><category><![CDATA[social-behaviour]]></category><category><![CDATA[computer vision development services]]></category><category><![CDATA[Laboratory Methods]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:07:25 GMT</pubDate><content:encoded><![CDATA[<p>A single-animal tracker can follow a blob around an open field or a maze and, with a decent contrast and a fixed camera, do a reliable job. Add a second animal and the problem changes. The tracks can cross, the animals can huddle, and the software can hand one identity to the other. If you then score social contact, chase, or who spent time in a zone, a swap can invert the result. Multi-animal tracking is worth doing, but only if you treat identity as something you have to maintain and audit.</p>
<h2>Decide whether you truly need identities</h2>
<p>Some questions do not need a permanent name on each animal. Total movement in a home cage, or the number of animals in a feeder zone, can sometimes be scored from unmarked detections. As soon as you ask who initiated a contact, whether one animal avoids another, or how a particular individual's path changed, you need identities that survive the whole session.</p>
<p>Write that requirement down, because it decides the method. Temporary colour marks, natural coat differences, a tagged cap or a painted patch, and multi-animal pose estimators that try to keep identities across frames are all in use. Each has a cost: marks must be safe, visible from above, and distinct under your lighting; natural differences may not be enough in an inbred group; estimators still swap when bodies overlap.</p>
<p>If you can test animals one at a time without ruining the behaviour you care about, do that. Multi-animal tracking is for social and group-housing questions that cannot be reduced to a solo test.</p>
<h2>Where identity usually breaks</h2>
<p>Swaps cluster around a few situations:</p>
<ul>
<li>crossings, where two paths meet and leave at an angle the linking rule guesses wrongly</li>
<li>huddling or piling, where one blob appears and then splits</li>
<li>a lost frame, after which the nearest detection is the wrong animal</li>
<li>similar marks, or marks that vanish when the animal rears or turns</li>
<li>reflections, bedding and shadows that create extra detections</li>
</ul>
<p>A higher frame rate helps through crossings, because the next position is closer to the true animal. It does not help much when two animals sit still in a pile. For huddling you may need marks that remain visible, a short manual correction, or a decision that identity is unknown for that interval.</p>
<p>Colour or pattern marks should be read in the same lighting you will use in the experiment, after drying, and from the camera height. A mark that looks obvious on the bench can disappear on a white floor or under red light. Recheck marks during a long study: they fade.</p>
<h2>Clean the tracks, then count what you changed</h2>
<p>After the automatic pass, inspect crossings and any period where two identities come very close. Many labs step through a contact or overlap list rather than watching every minute of video. When you correct a swap, keep a log: the time, the animals involved, and whether you interpolated a short gap or redrew the identities to the end of the session.</p>
<p>Report, for the study or for a sampled set of videos:</p>
<ul>
<li>how identities were assigned at the start</li>
<li>how many sessions needed manual correction, and roughly how much</li>
<li>the rule for gaps (for example, a short interpolation versus marking the period as unknown)</li>
<li>any sessions excluded because identity could not be recovered</li>
</ul>
<p>A social contact rule should use a stated distance and a stated minimum duration, and should be applied only while identities are trusted. A brief overlap that was a swap, or a period scored as "unknown", should not enter a contact total as if it were an interaction. Guidance on the tests where this matters, including social and group assays, is collected at <a href="https://animalbehaviortracking.com/">Animal Behavior Tracking</a>.</p>
<h2>Design the arena to help the tracker</h2>
<p>Plain floors, even light, and enough space that animals are not forced into constant overlap will do more for identity than a more elaborate algorithm. In a very small box, crossings are continuous. In a complex home cage, nests and shelters hide marks; if the nest is the behaviour you care about, plan for unseen periods rather than inventing tracks inside it.</p>
<p>Start and stop times, cage mates, and whether a session begins with a fresh introduction or with already-housed animals all belong in the methods, because they change how often animals meet. The tracking method should be described with the same frankness: not only the software, but the mark, the frame rate, and how swaps were found and handled.</p>
<p>If you cannot recover identity with confidence, it is better to drop that session, or to fall back to measures that do not need names, than to publish a social result built on mixed-up paths.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Scoring the open field from video: zones, sessions and arena size]]></title><description><![CDATA[Time in the centre only means something if the centre, the session length and the box itself were defined before you looked at the groups.]]></description><link>https://videotracking.hashnode.dev/scoring-the-open-field-from-video-zones-sessions-and-arena-size</link><guid isPermaLink="true">https://videotracking.hashnode.dev/scoring-the-open-field-from-video-zones-sessions-and-arena-size</guid><category><![CDATA[open-field]]></category><category><![CDATA[video-tracking]]></category><category><![CDATA[animal-behaviour]]></category><category><![CDATA[neuroscience]]></category><category><![CDATA[Laboratory Methods]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:03:47 GMT</pubDate><content:encoded><![CDATA[<p>The open field is a bare arena, usually square or circular, in which an animal is allowed to move. From a top-down video you can score how far it travelled, how fast, where it spent its time, and how those values change within a session and across days. The test is simple to run and easy to over-interpret. Most of the interpretation sits in choices you should make before the first animal is placed in the box: the size of the arena, the definition of the centre, the length of the session, and the lighting.</p>
<h2>Define the arena and the centre in real units</h2>
<p>Arena size changes the numbers. A larger floor gives more path length and can change how quickly an animal reaches the middle. Wall height changes whether the animal can rear to look out and whether it treats the space as open. Use the same box for every animal in the study, and report internal length or diameter, wall height, and material or colour, because contrast against the floor is what the tracker needs.</p>
<p>The "centre" is not a natural object. Common definitions include a central square or circle of a stated size, or a central region that is a stated fraction of the floor area. A narrow wall zone and a large centre will make most animals look less avoidant of the middle than a wide wall zone and a small centre. Pick one definition, draw it on the calibrated floor (not by eye on a distorted image), and use it for every session.</p>
<p>Other useful zones are corners, a wall corridor, and sometimes an intermediate ring. Corner time and wall time are often more informative than a single centre percentage, especially in a square box, where many animals settle in a corner after the first exploration.</p>
<p>A map of tests that can be scored from video, including the open field, is on this <a href="https://videotracking.info/tests-you-can-track/">guide to tests you can track</a>. For how those movement and zone measures sit beside other rodent tests, see <a href="https://animalbehaviortracking.com/">Animal Behavior Tracking</a>.</p>
<h2>Session length and the shape of the session</h2>
<p>The first minutes of an open field are not the same as the last. Many animals explore more at the start and slow down or settle later. If you only report a single total for a long session, you can hide a difference that was present only at the beginning, or you can let a long quiet period wash out an early difference.</p>
<p>Decide the session length in advance and, if you will analyse time bins, decide the bin width in advance too. Typical practice is to report both the whole session and the early part, or to show a simple time course of distance and centre time. Do not choose a window after you have seen which window is significant.</p>
<p>Repeated daily sessions measure habituation of locomotor activity as well as the first reaction to the box. If your question is about novelty, the first session may be the one that matters. If your question is about baseline activity or a treatment that should change habituation, you need more than one day, and you should say which day is which in every figure.</p>
<h2>What to score, and what the scores can support</h2>
<p>From a clean top-down track you can usually take:</p>
<ul>
<li>total distance and mean or peak speed</li>
<li>time and entries in the centre, walls and corners</li>
<li>latency to first entry of the centre</li>
<li>periods of very low speed, if you have defined a freeze or rest rule in advance</li>
</ul>
<p>Rearing, grooming and some risk-assessment postures need a side view, a closer camera, or a pose estimator that can see those points. Do not claim them from a centroid that only knows where the body was.</p>
<p>Lighting and the room around the box affect how exposed the centre feels. Uneven light, a dark shelter in one corner, or a noisy door on one side will bias zone times. Even, moderate light and a quiet, plain room are the usual starting point. If you are using the test as a rough anxiety-related measure, remember that locomotion and anxiety both influence centre time. A treatment that simply slows the animal can look like avoidance, which is why distance and zone time should be read together.</p>
<h2>Make the video easy to track</h2>
<p>A plain, high-contrast floor, no bedding if your protocol allows a bare floor, and lighting that does not throw moving shadows will save you more time than any later clean-up. Reflections from shiny walls, a tail that matches the floor, and an animal that sits in a dark corner are the usual sources of lost frames.</p>
<p>Calibrate the floor, confirm that a square box looks square, and keep the camera fixed for the study. If you change the box size between cohorts, do not pool the raw distances without comment: the same animal would have produced different numbers in a different arena.</p>
<p>Write the zone geometry, session length, lighting and arena size in the methods with the same care you would give to a drug dose. The open field is only a simple test when those details are fixed.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[From pixels to centimetres: calibrating a behaviour video without fooling yourself]]></title><description><![CDATA[A ruler on the floor is a start, not a finished calibration. Distortion, camera height and a scale taken in the wrong plane all leak into speed and…]]></description><link>https://videotracking.hashnode.dev/from-pixels-to-centimetres-calibrating-a-behaviour-video-without-fooling-yourself</link><guid isPermaLink="true">https://videotracking.hashnode.dev/from-pixels-to-centimetres-calibrating-a-behaviour-video-without-fooling-yourself</guid><category><![CDATA[video-tracking]]></category><category><![CDATA[calibration]]></category><category><![CDATA[animal-behaviour]]></category><category><![CDATA[Laboratory Methods]]></category><category><![CDATA[computer vision development services]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 19:00:08 GMT</pubDate><content:encoded><![CDATA[<p>Every distance, speed and zone time that comes out of a video tracker is only as good as the conversion from pixels to real units. If that conversion is wrong, group differences can still appear, but the numbers will not match another lab, and some measures will be more wrong than others. Calibration is a short job. Doing it carelessly is one of the more common reasons a methods section cannot be repeated.</p>
<h2>Measure in the plane where the animal actually moves</h2>
<p>The scale that matters is the floor of the arena, or the water surface in a pool, not the bench, not the top of the wall, and not a ruler held up towards the camera. A centimetre at the water surface does not subtend the same number of pixels as a centimetre on the pool rim if the camera is close or the lens is wide.</p>
<p>Place an object of known length in the animal's plane: a rigid bar, a marked rod, or a square of known size. Measure it in the same units you will report. Take the length in pixels from the same kind of image the tracker will see, after any cropping or deinterlacing you plan to use. Then:</p>
<p>centimetres per pixel = known length in centimetres / length in pixels</p>
<p>Do this in more than one place, including near the centre and near the edge. If the numbers disagree, you have distortion, a camera that is not square to the plane, or both. A single scale taken in the centre of a badly distorted image will under- or over-state paths that run along the wall, which is exactly where thigmotaxis and many open-field measures live.</p>
<h2>Check that the camera is looking straight down</h2>
<p>An angled camera turns a circle into an oval and makes one end of the arena look larger than the other. Animals then appear to move faster in the far end, and circular zones drawn on a flat image will not match the real floor. Level the camera, centre it over the arena, and confirm that a circular pool looks circular and that a square box has right angles and equal sides in the image.</p>
<p>If you cannot mount the camera truly overhead, you need a spatial calibration that accounts for perspective, not a single multiplier. For most behaviour rooms it is easier to fix the mount than to correct a skewed image later.</p>
<p>Lens distortion, especially on wide-angle or cheap web cameras, bows straight walls. Some software can apply a distortion correction if you photograph a checkerboard. If you do not correct it, at least measure the scale at the wall as well as at the centre and say so. The <a href="https://videotracking.info/how-video-tracking-works/">overview of how video tracking works</a> places this scale step in the same pipeline as background subtraction and centroid extraction, which is the right way to think about it: calibration is not a last-minute spreadsheet conversion.</p>
<h2>Aspect ratio, frame rate and things that look like scale errors</h2>
<p>A mismatch between the pixel aspect ratio and the way the file is read can stretch one axis. Distance is then wrong in a direction-dependent way, and a circular zone becomes an ellipse in real space. Open a still frame and measure a known square in both directions.</p>
<p>Frame rate does not change the centimetres-per-pixel factor, but it does change speed and any measure that uses time. Use the true capture frame rate, not the nominal value on the camera box, and be careful with variable-frame-rate files. A dropped-frame gap that is treated as a single time step will create a false high-speed jump.</p>
<p>Recalibrate whenever the camera, the lens, the zoom, the height or the arena is moved. Write the date of the calibration, the object used, the measured factor, and the arena diameter or side length in your lab record and in the methods. If you analyse old video after a room change, use the calibration that belonged to that video, not the current one.</p>
<h2>What a bad scale does to common measures</h2>
<p>Distance and speed scale directly with the factor. A 5 per cent error in centimetres per pixel is a 5 per cent error in path length. Zone times are more subtle: if the arena size in the software does not match the real arena, a "centre" zone drawn as a percentage of the image can be right even when absolute distances are wrong, but a centre defined as a 20 centimetre circle will be wrong. Heading and some strategy labels that use angles are more robust to a uniform scale error, and much less robust to distortion and tilt.</p>
<p>Do not calibrate from the animal itself. Body length changes with posture, and using the subject as the ruler makes every size difference between animals look like a tracking difference.</p>
<p>A five-minute calibration check at the start of a study, and again after any change to the camera, is enough for most top-down behaviour work. The point is not ceremony. It is so that a path length in centimetres, a speed threshold in centimetres per second, and a wall zone a few centimetres wide all mean what you say they mean.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Designing landmarks and boundaries in a human virtual water maze]]></title><description><![CDATA[The virtual room can quietly turn a place task into a beacon task. Here is how to stop that happening.]]></description><link>https://videotracking.hashnode.dev/designing-landmarks-and-boundaries-in-a-human-virtual-water-maze</link><guid isPermaLink="true">https://videotracking.hashnode.dev/designing-landmarks-and-boundaries-in-a-human-virtual-water-maze</guid><category><![CDATA[Virtual Reality]]></category><category><![CDATA[spatial-memory]]></category><category><![CDATA[morris water maze]]></category><category><![CDATA[neuroscience]]></category><category><![CDATA[experimental-design]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 18:56:30 GMT</pubDate><content:encoded><![CDATA[<p>A human virtual water maze asks a person to find a hidden location in a computer-generated arena, often a circular pool in a room, using a desktop display, a headset, or walking tracking. The logic comes from the rodent task: the goal is not visible, so the participant has to use the surrounding layout. That only holds if the virtual room is built that way. A single bright object over the goal, a unique pattern on the arena wall, or an instruction that names a landmark will change the task without changing the name of the test.</p>
<h2>Landmarks should define a layout, not a target</h2>
<p>Give the participant several distal landmarks, placed around the room, each clearly different from the others and visible from many points in the arena. The hidden location should be defined by relations among those landmarks and the arena boundary, not by standing under one of them.</p>
<p>A beacon is a cue at or very near the goal. In a virtual environment it is easy to add one by accident: a column in the water, a bright light on the floor of the arena, a unique stain on the pool wall at the platform location, or a ceiling feature that sits only above the goal. Participants will use it, and they will often be able to tell you that they used it. That is useful information, but it is not place learning in the sense the rodent hidden-platform task is meant to capture.</p>
<p>Boundaries matter as much as paintings on the walls. People, like other animals, use the shape of the space. A perfectly circular arena with a uniform wall puts more weight on the distal landmarks. A break in the circular wall, a ramp, or a coloured quadrant painted inside the pool can become a local mark. If you need those features for another reason, treat them as part of the cue set and report them.</p>
<h2>Instructions can give the answer away</h2>
<p>Unlike a rat, a person will use language. If you say "the platform is near the window", you have turned the window into a beacon. If you say "use the objects in the room to find a hidden platform that stays in the same place", you have described the place task without naming the solution.</p>
<p>Keep the instruction script identical for every participant and write it in the methods. A familiarisation phase should teach movement, looking around, and what success feels like, ideally in a different room or with a different goal, so that the layout of the test environment is not learned during the practice of the controls.</p>
<p>Do not answer mid-trial questions with spatial hints. "Keep searching" is fine. "You are getting closer to the painting" is a different experiment.</p>
<h2>Starts, views and the edge of the arena</h2>
<p>Vary start positions, and consider the view at the start. If every trial begins facing the same landmark, a heading strategy will look like accurate place memory. If the display or the headset field of view is narrow, some landmarks will be out of sight at the start, which changes the first few seconds of each trial and can inflate early heading error.</p>
<p>Decide what happens at the arena wall. In some setups the participant slides along it, in others movement stops, in others the wall is not solid. Each choice changes how tempting a wall-following strategy is, and how you should interpret long paths that hug the edge. If you plan to compare results with rodent swims, a solid circular boundary and a modest period of being "stuck" on the wall is closer to the original task than a wall that can be walked through.</p>
<p>Trial time limits, the absence of the platform on probe trials, and the feedback at the end of a trial (silence, a tone, or a visible platform after a delay) all need to be chosen before recruitment. The <a href="https://virtualmorriswatermaze.com/designing-a-study/">virtual water maze study design notes</a> are a practical place to record those choices next to display type and movement control, so the environment and the procedure are specified together.</p>
<h2>Check the room the way you would check a real pool</h2>
<p>Before you collect data, walk or navigate the environment yourself and ask a colleague who does not know the goal location to do the same. Look for unique marks at the goal, landmarks that are only visible from one side, and lighting that flags a quadrant. Try a cue-rotation or landmark-removal condition in a pilot if your claim is about the layout rather than about following one object.</p>
<p>Ask participants, after the test, how they found the goal. A short debrief will not replace the path data, but it will tell you when a sizeable group used a verbal rule or a beacon you had not noticed. If they did, you can still report the study, provided you describe the environment that was actually used, not the one you meant to build.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Distal cues, pool-wall marks and the cue-rotation test]]></title><description><![CDATA[If an animal can solve the maze from a stain on the wall, it is not doing the place task you think it is.]]></description><link>https://videotracking.hashnode.dev/distal-cues-pool-wall-marks-and-the-cue-rotation-test</link><guid isPermaLink="true">https://videotracking.hashnode.dev/distal-cues-pool-wall-marks-and-the-cue-rotation-test</guid><category><![CDATA[morris water maze]]></category><category><![CDATA[neuroscience]]></category><category><![CDATA[spatial-memory]]></category><category><![CDATA[experimental-design]]></category><category><![CDATA[animal-behaviour]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 18:52:53 GMT</pubDate><content:encoded><![CDATA[<p>The Morris water maze is a place task only if the hidden platform is defined by cues outside the pool. If the animal can aim at a scratch on the pool wall, a shiny inlet, or the experimenter standing in the same spot every trial, it can escape without learning a location in the room. Cue design is therefore not decoration. It is the difference between spatial memory and a simpler association.</p>
<h2>Distal cues have to be the ones that work</h2>
<p>Distal cues sit on the walls of the room, or otherwise well outside the water: large, stable, and visible from the water surface at many points in the pool. Several cues, distributed around the room rather than clustered on one wall, give the animal a layout instead of a single beacon.</p>
<p>A single striking object can dominate. If one poster is much brighter or closer to the platform than everything else, many animals will learn "swim towards that" rather than "search in this place in the layout". That may still be learning, but it is closer to cued navigation than to place learning.</p>
<p>Cues should not move during the study unless you are moving them as a planned test. A door left open on some days, a coat on a hook, a changing screen, or a person who sometimes sits in a new chair all become uncontrolled cues. The people in the room need a standing position and a habit of not looming over one quadrant.</p>
<h2>The pool must not offer its own beacon</h2>
<p>Intra-maze marks are the usual leak. Look for:</p>
<ul>
<li>seams, drains, inlets, heaters and thermometer probes that sit in a fixed place on the wall</li>
<li>stains, chips, or a waterline that is darker on one side</li>
<li>reflections that always fall in the same quadrant</li>
<li>a platform that leaves a faint mark when it is hidden</li>
</ul>
<p>If you can see a unique feature from camera height, the animal may be able to use it from the water. Plain, even pool walls and a well-mixed opaque surface are part of cue control, not only of hygiene.</p>
<p>Start positions should vary around the pool so that a single motor pattern or a single view of one cue is not enough. If every trial starts opposite the same poster, a simple heading strategy can mimic place learning.</p>
<h2>Use a cue-rotation test when the claim matters</h2>
<p>When you need to show that the animal is using the distal layout, rotate the cues (or the cue set on a curtain) and move the platform so that it keeps the same relation to those cues. An animal that has learned the place relative to the cues should search in the new location defined by the rotated layout. An animal that has learned a place relative to uncontrolled room geometry, a noise source, or a mark on the pool will search in the old absolute location.</p>
<p>You do not need this test in every routine cohort, but you do need it if you are making a strong claim about place learning, or if you have any reason to suspect an intra-maze cue. Plan it in advance, keep the rotation large enough to be unambiguous, and score the search with the same rules you use on a probe trial.</p>
<p>A second, simpler check is to remove or cover a cue that you think is doing too much work and see whether the search falls apart. If it does, you had a beacon, not a rich layout. The <a href="https://morriswatermaze.online/protocol/">protocol pages at Morris Water Maze Online</a> are a useful place to hang these control trials next to the standard hidden-platform and probe sequence, so they are written down rather than added after a surprising result.</p>
<h2>Lighting and the experimenter's body are cues too</h2>
<p>A shaft of sunlight, an uneven lamp, or a bright computer screen in one corner can be as salient as a poster. Diffuse, even light is kinder to the animal and to the tracker, and it stops a bright patch of water from becoming a landmark.</p>
<p>The experimenter is a moving cue. Wear plain clothing, stand in a consistent place that is not lined up with the platform, and avoid retrieving the animal from the same point on the wall on every trial if that point can be used as a heading mark. If a second person enters only on some days, treat that as a change in the cue set.</p>
<p>Write down what the animal could actually see: the main distal objects, whether the pool was plain, where people stood, and any cue-rotation or cue-removal test. That short list tells a reader whether your hidden platform was truly hidden in space, or only hidden from the camera.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Sizing the pool, the water and the platform in the Morris water maze]]></title><description><![CDATA[Diameter, depth, temperature, opacity and platform size change the difficulty of the task as much as the training schedule does.]]></description><link>https://videotracking.hashnode.dev/sizing-the-pool-the-water-and-the-platform-in-the-morris-water-maze</link><guid isPermaLink="true">https://videotracking.hashnode.dev/sizing-the-pool-the-water-and-the-platform-in-the-morris-water-maze</guid><category><![CDATA[morris water maze]]></category><category><![CDATA[neuroscience]]></category><category><![CDATA[Laboratory Methods]]></category><category><![CDATA[spatial-memory]]></category><category><![CDATA[animal-behaviour]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 18:49:17 GMT</pubDate><content:encoded><![CDATA[<p>A Morris water maze is a circular pool of opaque water with a hidden escape platform. The protocol gets most of the attention, but the physical setup is part of the task. A smaller pool, warmer water or a larger platform all make escape easier, and they change what a given latency means. Set these details on purpose, keep them constant, and write them in the methods as carefully as you write the trial counts.</p>
<h2>Pool diameter and water depth</h2>
<p>Rats are usually tested in a larger pool than mice. A pool that is too small relative to the animal lets a circling or wall-hugging path find the platform by chance more often, which weakens the spatial demand. A pool that is very large increases fatigue, especially in mice or in older or impaired animals, and can push the animal back to the wall. Choose a diameter that is standard for the species in your field and stick to it for the whole study, including any later cohorts.</p>
<p>Water depth must cover the platform by a consistent margin and still let the animal swim comfortably, with its feet well off the floor of the pool. If the water is too shallow an animal may bounce off the bottom or stand. If it is too deep, climbing onto the platform becomes harder and some animals cling to the wall instead. Mark the fill level so that top-ups after evaporation do not change the hidden margin from day to day.</p>
<p>The pool itself should be a plain, even colour, with no unique seam, inlet, heater housing or scuff that could act as a local landmark. Those marks turn a place task into a beacon task, which is a different experiment.</p>
<h2>Temperature and what the animal will actually do</h2>
<p>Water that is too cold is a stressor and can change swim speed, floating and willingness to search. Water that is too warm reduces the motivation to escape. Labs typically aim for a mild, stable temperature in a narrow range and measure it in the pool, not only on the heater display, at the start of the day and again if the room temperature shifts.</p>
<p>Check temperature after a long run of trials. A heater that cycles can leave one squad of animals in cooler water than the next. If animals begin to float more as the session goes on, do not assume it is only fatigue or memory: look at the water and the inter-trial interval as well.</p>
<p>Dry the animal thoroughly after each trial and keep the holding area warm. A wet, cold animal on the next trial is not a fair test of spatial memory.</p>
<h2>Opacity, colour and the hidden platform</h2>
<p>The water is made opaque so that the platform cannot be seen from the surface. The usual methods are a small amount of non-toxic white powder, an opaque pool lining, or both. Whatever you use should be even, stable during a session, and comfortable for the animal. Stir after settling, and look from the animal's viewpoint, not only from the camera: a platform that is invisible to you from the gallery may still be visible as a shadow or a change in hue from water level.</p>
<p>Platform size is a compromise. A very small platform makes the task harder and can increase failures in a way that looks like a memory deficit. A very large platform is found more often by chance. Keep the size constant, and use the same platform in visible-platform control trials, raising or marking it so that it is clearly available without changing its location rules mid-week.</p>
<p>The platform must be stable under the animal's weight, easy to climb, and flush enough that a tracking camera does not pick a bright rim when the platform is supposed to be hidden. A quietly sinking or wobbly platform will produce odd paths that have nothing to do with learning.</p>
<h2>Lighting the water for the animal and for the camera</h2>
<p>Even lighting is part of the physical setup, not only of the room decor. A bright patch on the water can act as a cue, and a reflection of a window or lamp can hide the animal from a video tracker or create a second blob. Place the camera directly above the centre, use diffuse light, and block sources that glare on the surface.</p>
<p>A practical walk-through of why the pool is built this way, including the original logic of a hidden platform in open water, is in <a href="https://water-maze.com/episodes/episode-1-the-pool-morris-water-maze/">this episode on the pool itself</a>. For a broader orientation to the test, including setup choices that later affect analysis, see the guides at <a href="https://watermaze.org">watermaze.org</a>.</p>
<p>Before the first acquisition day, run a few tracking checks with an empty pool and then with a floating object of known size. If the surface glare or the opacity makes the target flicker in and out of the mask, fix the lighting and the water before you start collecting real trials. Changing the fill, the powder or the lamps halfway through a study is a new experiment, even if the protocol document stays the same.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[How to classify search strategies in the Morris water maze]]></title><description><![CDATA[Two swims can share the same escape latency and still show completely different learning. Here is a practical way to name, define and report the path.]]></description><link>https://videotracking.hashnode.dev/how-to-classify-search-strategies-in-the-morris-water-maze</link><guid isPermaLink="true">https://videotracking.hashnode.dev/how-to-classify-search-strategies-in-the-morris-water-maze</guid><category><![CDATA[neuroscience]]></category><category><![CDATA[morris water maze]]></category><category><![CDATA[spatial-memory]]></category><category><![CDATA[behaviour-analysis]]></category><category><![CDATA[video-tracking]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 18:45:15 GMT</pubDate><content:encoded><![CDATA[<p>Escape latency is a useful training measure, but it is a poor description of how an animal found the platform. A direct swim and a long period of wall-hugging that ends in a lucky crossing can produce similar times. If you want to say that a treatment changed spatial memory, you need to say something about the search itself.</p>
<p>Strategy classification is the habit of labelling each trial, or each segment of a trial, as one of a small set of path types. The labels are not magic, and they are only as good as the rules behind them. Used carefully, they stop you from treating every short swim as place learning.</p>
<h2>The labels most labs actually use</h2>
<p>The exact names vary, but a well-established set covers most paths you will see in a hidden-platform task:</p>
<ul>
<li>Wall-hugging, or thigmotaxis: the animal stays in a corridor along the pool wall. This is common early in training and in anxious or motor-impaired animals. It is not a spatial search for the platform.</li>
<li>Random or non-systematic search: the path crosses the pool with little repetition and little bias towards the platform location.</li>
<li>Scanning: wide, often looping passes that cover a large part of the pool, still without a tight focus on one place.</li>
<li>Chaining: a circular swim at roughly the same distance from the wall as the platform. The animal has learned something about distance from the wall, not the place defined by room cues.</li>
<li>Focal or centred search: tight looping or circling in a limited region, ideally the region that contains the platform.</li>
<li>Directed or direct swim: a relatively straight path towards the platform, sometimes after a brief orientation at the start.</li>
</ul>
<p>You may also want a separate label for floating, and another for a path that heads to a former platform location after a reversal. Keep the list short. A scheme with a dozen overlapping categories is hard to apply consistently and hard for a reader to interpret.</p>
<h2>Turn the labels into rules before you score</h2>
<p>A name without a rule will drift from scorer to scorer. Decide the operational definitions before you look at group differences, and write them down.</p>
<p>Useful building blocks are already in most tracking files:</p>
<ul>
<li>Time or path length in a wall zone, often a ring a few centimetres wide. A high wall-zone fraction is the usual definition of thigmotaxis. State the ring width.</li>
<li>Mean distance to the platform, or time in a small circle around it, for focal search.</li>
<li>Time in an annulus at the platform's radial distance, for chaining.</li>
<li>Path straightness or tortuosity, and the heading at the start of the trial relative to the platform, for directed swims. The <a href="https://morriswatermazesoftware.com/videos/heading-angle/">heading angle guide</a> walks through that start-of-trial heading in more detail.</li>
<li>Speed, so that a float is not scored as a focused search.</li>
</ul>
<p>You can combine rules (for example, a directed swim must be reasonably straight and must end at the platform, or come close). You can also classify by the dominant strategy in the trial, or segment the trial and allow the strategy to change, which is more honest for long swims that start at the wall and later become a search.</p>
<p>If you classify by eye from path plots, use two scorers on a subset and report how often they agree. If you classify by software, report the zone sizes, speed thresholds and the order in which rules are applied. The order matters: a tight circle at the platform radius could be called chaining or focal search depending on which rule you test first.</p>
<h2>Training trials and probe trials are not the same job</h2>
<p>During hidden-platform training the animal can succeed by more than one strategy, and the interesting change is often the shift across days from wall-hugging towards directed or focal search. Plot the proportion of each strategy over sessions, not only mean latency.</p>
<p>On a probe trial the platform is absent, so "direct swim to escape" no longer applies in the same way. Here the useful questions are whether the animal heads for the trained location, searches nearby, chains, or stays on the wall. Probe measures such as time in the target quadrant or proximity to the former platform then sit naturally beside the strategy label. A short introduction to those probe measures is in this <a href="https://morriswatermazesoftware.com/videos/probe-trials/">probe trial overview</a>.</p>
<p>Do not average strategy labels as if they were numbers. Report frequencies, or the session on which a directed or focal strategy first becomes common.</p>
<h2>What a strategy label can and cannot claim</h2>
<p>A directed swim in the presence of stable room cues is consistent with place learning, but it is not proof on its own. Animals can also learn a heading from a single start point, or approach a visible mark. That is why start positions are varied, and why a visible-platform control still belongs in the study.</p>
<p>Chaining is a real solution to the task, just not the one most people mean when they talk about spatial memory. If your treated group chains and your control group swims directly, the escape times might be closer than the behaviour. The classification is what makes that difference visible.</p>
<p>Report enough for someone else to apply your rules to their own tracks: the category list, the zone geometry, any speed threshold, whether you scored the whole trial or a time window, and whether the scorer could see the group label. That is the difference between a useful figure and a set of adjectives.</p>
<p>Published by watermaze.org.</p>
]]></content:encoded></item><item><title><![CDATA[Finding floating bouts in a tracked swim: a speed threshold, a minimum duration, and why both matter]]></title><description><![CDATA[In the water maze some animals stop swimming and float. Floating adds seconds to every trial and looks exactly like forgetting if you only read escape…]]></description><link>https://videotracking.hashnode.dev/finding-floating-bouts-in-a-tracked-swim-a-speed-threshold-a-minimum-duration-and-why-both-matter</link><guid isPermaLink="true">https://videotracking.hashnode.dev/finding-floating-bouts-in-a-tracked-swim-a-speed-threshold-a-minimum-duration-and-why-both-matter</guid><category><![CDATA[Python]]></category><category><![CDATA[Data Science]]></category><category><![CDATA[Science ]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 12:07:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0eb74acb7404ac93a7312f/a1a65caf-2005-40ec-b842-ae894404f1ea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the water maze some animals stop swimming and float. Floating adds seconds to every trial and looks exactly like forgetting if you only read escape latency. Tracking data make it measurable, but only if you define it carefully.</p>
<p>A floating bout here is a stretch where speed stays below a threshold (2 cm/s) for at least a minimum time (1 s). The duration rule matters: tracking jitter makes a swimming animal briefly "slow" between frames, and without a minimum bout length you count noise.</p>
<pre><code class="language-python">def floating_bouts(t, x, y, still=2.0, min_bout=1.0):
    """Bouts where speed stays below `still` cm/s for at least `min_bout` s.
    Returns total floating time (s) and the list of (start, duration)."""
    v = np.hypot(np.diff(x), np.diff(y)) / np.diff(t)
    slow = np.r_[v &lt; still, False]
    bouts, i = [], 0
    while i &lt; len(slow):
        if slow[i]:
            j = i
            while slow[j]:
                j += 1
            dur = t[j] - t[i]
            if dur &gt;= min_bout:
                bouts.append((round(float(t[i] - t[0]), 2), round(float(dur), 2)))
            i = j
        else:
            i += 1
    return round(sum(d for _, d in bouts), 2), bouts
</code></pre>
<p>On a simulated swim with one 3-second pause the function returns <code>(3.0, [(39.96, 3.0)])</code>: three seconds of floating, starting at about 40 s.</p>
<p><strong>Choices to report:</strong> the speed threshold, the minimum bout, the frame rate and any smoothing. Thresholds differ between rats and mice and between pools, so fix them before the study.</p>
<p><strong>What floating is not:</strong> wall-hugging (thigmotaxis) is moving along the wall; floating is not moving at all. Report both.</p>
<p>More on tracking quality on <a href="https://videotracking.info/data-quality/">proving your tracking data are clean</a> and on how a tracker finds the animal in <a href="https://videotracking.info/how-video-tracking-works/">how video tracking works</a>.</p>
<p><em>Video Tracking for Behaviour Research (</em><a href="https://videotracking.info/"><em>videotracking.info</em></a><em>) is a plain-English guide to tracking animal behaviour on video. Published by watermaze.org.</em></p>
]]></content:encoded></item><item><title><![CDATA[A video tracker for behaviour experiments you can actually audit: background subtraction, centroids and a data-quality report in OpenCV]]></title><description><![CDATA[Every commercial tracker does the same five steps. Here they are in 70 lines, plus the numbers a reviewer will ask you for.]]></description><link>https://videotracking.hashnode.dev/a-video-tracker-for-behaviour-experiments-you-can-actually-audit-background-subtraction-centroids-and-a-data-quality-report-in-opencv</link><guid isPermaLink="true">https://videotracking.hashnode.dev/a-video-tracker-for-behaviour-experiments-you-can-actually-audit-background-subtraction-centroids-and-a-data-quality-report-in-opencv</guid><category><![CDATA[Python]]></category><category><![CDATA[opencv]]></category><category><![CDATA[Computer Vision]]></category><category><![CDATA[Science ]]></category><dc:creator><![CDATA[Video Tracking for Behaviour Research]]></dc:creator><pubDate>Tue, 01 Dec 2026 12:06:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0eb74acb7404ac93a7312f/ac038304-dba8-49e7-a406-234569868033.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Behaviour labs record an animal from above in an open field, a water maze or a plus maze, then turn hours of video into positions. Commercial software and deep-learning pose estimators do this very well. It still pays to understand the basic pipeline, because almost every tracking problem traces back to one of its steps, and because reviewers increasingly ask how clean your tracking was.</p>
<h3>The five steps</h3>
<ol>
<li><strong>Separate the animal from the background.</strong> With good contrast (a dark mouse on a white floor) a fixed threshold can work, but background subtraction is sturdier: build an image of the empty arena and subtract it from every frame.</li>
<li><strong>Find the centre.</strong> Take the largest blob of changed pixels and its centroid. Systems that also find the nose and tail base can measure heading and body orientation.</li>
<li><strong>Time-stamp and scale.</strong> Every position gets a time from the frame rate and is converted from pixels to centimetres with an arena calibration.</li>
<li><strong>Clean the track.</strong> Flag lost frames and impossible jumps, interpolate short gaps, and <em>count what you changed</em>.</li>
<li><strong>Analyse.</strong> Distance, speed, zone times and strategy measures are arithmetic on the clean track.</li>
</ol>
<p>The diagram on our <a href="https://videotracking.info/how-video-tracking-works/">how video tracking works</a> page shows the same flow.</p>
<h3>The code</h3>
<pre><code class="language-python">"""Minimal top-down tracker: background subtraction, centroid, clean-up."""
import csv, sys
import cv2
import numpy as np

def median_background(path, n=50):
    """Median of n frames spread through the video: the animal moves, so it
    vanishes from the median and an empty arena is left."""
    cap = cv2.VideoCapture(path)
    total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frames = []
    for i in np.linspace(0, total - 1, n).astype(int):
        cap.set(cv2.CAP_PROP_POS_FRAMES, int(i))
        ok, f = cap.read()
        if ok:
            frames.append(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY))
    cap.release()
    return np.median(frames, axis=0).astype(np.uint8)

def track(path, cm_per_px, thresh=40, min_area=30):
    bg = median_background(path)
    cap = cv2.VideoCapture(path)
    fps = cap.get(cv2.CAP_PROP_FPS)
    kernel = np.ones((3, 3), np.uint8)
    rows, i = [], 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        diff = cv2.absdiff(gray, bg)
        _, mask = cv2.threshold(diff, thresh, 255, cv2.THRESH_BINARY)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        n, labels, stats, cents = cv2.connectedComponentsWithStats(mask)
        x = y = np.nan
        if n &gt; 1:
            k = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA])  # largest blob
            if stats[k, cv2.CC_STAT_AREA] &gt;= min_area:
                x, y = cents[k] * cm_per_px
        rows.append((i / fps, x, y))
        i += 1
    cap.release()
    return np.array(rows), fps

def clean(track_xy, fps, max_speed=100.0):
    """Flag lost frames and impossible jumps, then interpolate short gaps.
    Returns the cleaned track and a quality report."""
    t, x, y = track_xy.T.copy()
    lost = np.isnan(x)
    v = np.hypot(np.diff(x), np.diff(y)) * fps
    jump = np.zeros_like(lost)
    jump[1:] = v &gt; max_speed            # cm/s: faster than the animal can go
    bad = lost | jump
    good = ~bad
    x[bad] = np.interp(t[bad], t[good], x[good])
    y[bad] = np.interp(t[bad], t[good], y[good])
    report = {"frames": len(t), "lost_pct": round(float(100 * lost.mean()), 2),
              "jump_pct": round(float(100 * jump.mean()), 2), "interpolated": int(bad.sum())}
    return np.column_stack([t, x, y]), report

if __name__ == "__main__":
    video, scale = sys.argv[1], float(sys.argv[2])   # e.g. arena.mp4 0.25
    raw, fps = track(video, scale)
    cleaned, report = clean(raw, fps)
    print(report)
    with open(video.rsplit(".", 1)[0] + "_track.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["t_s", "x_cm", "y_cm"])
        w.writerows(cleaned.round(3))
</code></pre>
<p>Run it as <code>python track.py session01.mp4 0.25</code> where 0.25 is centimetres per pixel (pool or arena diameter in cm divided by its diameter in pixels). It writes <code>session01_track.csv</code> and prints the quality report.</p>
<h3>Why a median background?</h3>
<p>A moving animal is rarely in the same place in more than a few of 50 frames spread across a session, so the per-pixel median is the empty arena, without needing a separate empty recording. It fails if the animal sits still for most of the session (a floating rat, a freezing mouse). Then record an empty-arena clip before each session.</p>
<h3>The quality report is the point</h3>
<p>Reviewers and the ARRIVE guidelines expect you to say how good your data were. The <code>clean()</code> step returns:</p>
<ul>
<li><strong>lost_pct</strong>, frames with no animal found. Set an exclusion threshold (for example 5 percent of a trial) <em>before</em> you start, not after you see the results.</li>
<li><strong>jump_pct</strong>, positions implying a speed no animal can reach (here more than 100 cm/s; set it for your species).</li>
<li><strong>interpolated</strong>, the number of frames the script filled in.</li>
</ul>
<p>Keep the raw track as well as the cleaned one so anyone can re-run the analysis. More in <a href="https://videotracking.info/data-quality/">proving your tracking data are clean</a>.</p>
<h3>Most problems start at the camera</h3>
<p>No code fixes a bad recording. Mount the camera directly above the arena centre, aim for an animal at least a few dozen pixels across, use 25 to 30 frames per second for rodents (more for fast behaviour or larval fish), keep the light even with no hotspots on water, and use infrared light with an IR-sensitive camera for dark-phase tests. Our <a href="https://videotracking.info/camera-and-lighting/">camera and lighting checklist</a> has a 60-second pre-session check.</p>
<h3>Where to go from here</h3>
<ul>
<li>Multiple animals need identity tracking, not just the largest blob.</li>
<li>Body-part tracking (nose, tail base) needs either shape analysis or a pose-estimation model.</li>
<li>The <a href="https://videotracking.info/tests-you-can-track/">tests you can track</a> page lists what each common test measures, so you know which numbers to compute from the track.</li>
</ul>
<p><em>Video Tracking for Behaviour Research (</em><a href="https://videotracking.info/"><em>videotracking.info</em></a><em>) is a free, plain-English guide to tracking animal behaviour on video. Published by watermaze.org.</em></p>
<p><strong>References</strong></p>
<ul>
<li>Percie du Sert N, et al. (2020). The ARRIVE guidelines 2.0. <em>PLoS Biology</em> 18(7): e3000410.</li>
<li>OpenCV documentation: background subtraction and connected components (<a href="http://docs.opencv.org">docs.opencv.org</a>).</li>
</ul>
]]></content:encoded></item></channel></rss>