A finished round should change what your application does with camera images, not whether it receives them. Closing the preview, releasing the device, or waiting for console input can turn a simple retry into a stalled display. This procedure is for interactive vision demonstrations and operator-driven inspection tools. You will separate acquisition from round state, keep the preview updating while a decision is pending, and reset only the information needed for another round.
Choose a state reset, not a device restart
Keep the camera connection and preview window alive across rounds. When processing finishes, enter a waiting state that displays the outcome over fresh images. A retry creates new round state; an exit closes the application through its normal cleanup path.
Treat these as separate lifecycles:
| Resource or state | Lifetime | What happens on retry |
|---|---|---|
| Camera connection and acquisition | Application session | Remain active |
| Preview window and event handling | Application session | Remain active |
| Detector or processing resources | Usually application session | Reuse unless documented behavior requires otherwise |
| Round timer, counters and decisions | One round | Reset |
| Completed outcome | Until acknowledged or archived | Remove from the active overlay |
| Pending asynchronous results | One identified round | Reject results belonging to earlier rounds |
A frozen outcome display is not necessarily a frozen camera. Draw the outcome on each newly received image rather than repeatedly displaying the final processed image.
This differs from ending acquisition while keeping the application open. Here, acquisition continues even when round-specific analysis is idle.
Establish ownership before changing the loop
Give one component responsibility for opening, reading and closing the device. Give the interface a separate responsibility: receiving actions and drawing the latest preview. A state controller decides whether analysis runs.
These responsibilities can share one event loop when their work is short. They do not automatically require separate threads. The essential rule is that waiting for a retry must not prevent frame acquisition or interface event handling.
Before editing the application, identify these operations:
- Open and start: performed once when the application session begins.
- Read: continues in both running and waiting states.
- Analyze: runs only when the current round needs it.
- Present: draws a fresh image with the appropriate overlay.
- Reset: replaces round-specific data without touching acquisition.
- Close: runs once during application shutdown, including error exits.
Check the acquisition API's documented timeout behavior. A read that can wait indefinitely also prevents a single-threaded interface from responding indefinitely. Use a supported bounded read, or move acquisition to its own worker while following the interface framework's threading requirements.
If processing and interactive controls already compete for the display thread, the approach in designing responsive image tools helps separate preview work from expensive operations.
Implement the restart as explicit transitions
Use three application states: RUNNING, WAITING and EXIT. A round ending is a transition to WAITING, not a reason to leave the acquisition loop.
- Create the session resources. Open the device, start acquisition where required, and create the preview once. Initialize the first round separately.
- Acquire and service events on every iteration. Do this in both active states. Replace blocking console questions with interface actions, key events, or a separately managed input channel.
-
Process only while running. Update the round timer, decisions and counters only in
RUNNING. Continue drawing live images inWAITINGwithout changing the completed outcome. -
Handle completion once. Store the outcome and transition immediately to
WAITING. Schedule any recording operation from this transition, not from the continuously repeated drawing code. -
Handle retry by replacing round data. Clear temporary decisions, reset the timer and counters, and assign a new round identifier. Then return to
RUNNING. - Handle exit through one cleanup path. A quit action from either state should stop workers, finish or cancel pending work according to policy, and release resources in the documented order.
A reset function should return a fresh round object rather than changing scattered global variables. Include every value that can affect the next outcome: countdown state, detected choices, confidence accumulators, completion flags and pending analysis identifiers.
Keep session totals separate from round counters. If a retry starts another round within the same session, resetting both would silently erase information the operator expects to retain.
Use a persistent loop with a replaceable round
The following is backend-neutral pseudocode, not a camera-library API. Map each operation to documented acquisition and interface functions. In particular, read_frame needs a bounded wait, update_round must return promptly, and post_outcome must not perform blocking storage work.
device = open_and_start_device()
view = create_preview()
state = RUNNING
round_id = 1
round_data = new_round(round_id, monotonic_time())
latest_frame = NONE
try:
while state != EXIT:
service_interface_events()
action = poll_action()
if action == QUIT:
state = EXIT
continue
if state == WAITING and action == RETRY:
round_id = round_id + 1
round_data = new_round(round_id, monotonic_time())
state = RUNNING
frame = read_frame(device, bounded_timeout)
if frame is not NONE:
latest_frame = frame
if state == RUNNING:
outcome = update_round(round_data, frame)
if outcome is not NONE:
round_data.outcome = outcome
state = WAITING
post_outcome(round_id, outcome)
if latest_frame is not NONE:
draw_preview(view, latest_frame, round_data, state)
else:
draw_waiting_for_image(view)
finally:
stop_and_join_workers()
stop_and_close_device(device)
close_preview(view)
The loop checks actions even when no image arrives. This matters when a disconnected device produces timeouts: the operator must still be able to quit.
A timeout is also different from a fatal acquisition error. Your adapter should distinguish them and show an acquisition status rather than silently presenting an old image as live.
Treat the source image as unchanged data. Build overlays on a display copy, or use a separate overlay layer. Otherwise, retaining the latest image during a timeout can leave old annotations embedded in it after the round resets.
If the interface owns its event loop, implement the same transitions through its timers and callbacks. Do not add a competing infinite loop inside a button handler. Keep window operations on the thread required by the interface backend.
Base round timing on elapsed time
A frame counter measures received iterations, not reliable elapsed time. Processing load, dropped frames and interface work all change its relationship to seconds.
For example, a countdown based on 60 frames lasts approximately 2 seconds at 30 frames per second. At 15 frames per second, the same counter lasts approximately 4 seconds.
Use a monotonic clock for countdowns. Capture a new start value when retry begins, then test whether elapsed time has reached each deadline. Do not require equality with an exact timestamp or frame count; the loop can pass over that value between iterations.
A frame queue creates a different timing problem. If 20 old frames remain queued and playback consumes them at 30 frames per second, their displayed duration is approximately:
That estimate excludes other buffering and processing delays. It explains why an apparently successful retry can still show activity from the previous round.
For a preview, a latest-frame slot or a small bounded queue often suits the task better than an accumulating queue. For inspections that require every triggered image, preserve the required acquisition sequence separately; do not discard inspection data merely to refresh the display.
Keep slow work and stale results outside the transition
Database writes, network requests and expensive analysis can freeze a preview even when the state machine is correct. Moving the retry question out of the capture loop does not solve those other blocking operations.
Schedule outcome recording once when the round completes. Include a unique outcome identifier and use duplicate handling appropriate to the storage system. Interface retries and transport retries should not create multiple records for the same completed round.
If analysis runs asynchronously, attach the round identifier to every job. Accept a completed result only when its identifier matches the active round. A frame identifier or acquisition timestamp can provide an additional freshness check.
For example, round 8 may begin while an analysis job from round 7 is still running. Resetting visible counters does not cancel that job. Without an identifier check, its late result can immediately alter the new round.
The same ownership problem appears in matching delayed analysis to its source image. Keep result association explicit rather than assuming completion order equals acquisition order.
Bound worker queues and define what happens when they fill. A nonblocking submission function still needs a policy: reject a duplicate, report an error, or retain a required record through a documented persistence mechanism.
Verify responsiveness and diagnose failed retries
Test the waiting state as thoroughly as the active state. A successful first round proves little about resource ownership or reset completeness.
Use this acceptance checklist:
- Wait without answering. Leave the outcome prompt visible for 10 seconds. Motion in the preview should continue throughout the wait.
- Retry repeatedly. Run 20 round transitions. Confirm that timers, temporary decisions and round counters restart consistently.
- Check resource counts. Application-owned acquisition handles, preview windows and workers should not increase with each retry.
- Inject a late result. Delay an old analysis job until the new round starts. Confirm that its result is rejected.
- Delay outcome recording. Simulate a 2-second storage delay. Preview and quit handling should remain responsive if recording is asynchronous.
- Test missing images. Confirm that the interface shows acquisition status and still accepts quit actions during read timeouts.
- Check duplicate actions. Repeated retry input should not start several rounds or create duplicate workers.
Common symptoms usually point to specific ownership mistakes:
| Symptom | Likely cause | First check |
|---|---|---|
| Preview stops at the question | Blocking input or waiting inside a handler | Confirm reads and event handling continue in WAITING
|
| New round immediately finishes | Completion flags or counters survived reset | Inspect the fresh-round object |
| Preview returns with old activity | Queued images or delayed analysis | Check queue policy and round identifiers |
| Each retry becomes slower | Repeated resource creation or growing work queues | Count handles, workers and queued jobs |
| Quit does nothing during camera loss | Unbounded acquisition wait | Check documented timeout behavior |
Restarting the device becomes appropriate when the actual acquisition session has failed or a documented configuration change requires it. Treat that as a separate recovery workflow. For failures in that path, use the checks for acquisition restart timeouts, rather than adding device recovery to every retry.
Choose hardware after the lifecycle works
This architecture applies to host-managed previews from area scan cameras. Start with the camera finder when you need to compare interfaces and imaging requirements. Changing the camera alone will not correct blocking input or stale round state.
The LS-CMR-0166 is an area scan camera with a USB3 interface.
- Sensor format
- 1/1.7"
- Interface
- USB3
- Resolution
- 12 MP
- Shutter
- Rolling
The LS-CMR-0053 is an area scan camera with a GigE interface.
- Sensor format
- 1/1.7"
- Lens mount
- C-mount
- Interface
- GigE
- Resolution
- 12 MP
These are interface examples, not a claim that either provides the pseudocode operations directly. Confirm acquisition-library support, timeout behavior, buffer ownership and your operating environment before selecting a device.
If you are considering smart cameras and vision sensors, first decide where the inspection state belongs. An on-device inspection and a host preview can have separate lifecycles. Verify the specific device's documented control and result interfaces rather than assuming a host-side retry resets its inspection job.
Inspection on the device, no PC
350 models · from $169.00Before ordering, establish the required image size, exposure, trigger behavior, interface and processing location. Then use the camera configuration starting point, or contact the applications team with your acquisition flow and retry requirements.
Questions
Do I need to close the preview window before another round?
Usually not. Keep the window and acquisition session active, replace round-specific data, and redraw the interface from a fresh image. Recreating the window is useful only when its own resources need rebuilding; it does not fix blocked acquisition or incomplete state resets.
Why does the preview freeze while waiting for a retry?
The application is often waiting inside an input function, a long-running handler, or a storage operation. During that wait, it may stop reading images or servicing interface events. Use event-driven actions and keep both responsibilities active while the outcome prompt is visible.
Which information should reset when the user retries?
Reset timers, temporary detections, round counters, completion flags and active outcome text. Preserve the camera connection and other session resources unless their documented behavior requires reinitialization. Separate session totals from round totals, and reject delayed analysis associated with the previous round.
Does a responsive preview require multiple threads?
No. A single event loop can work when acquisition waits are bounded and each processing operation returns promptly. Workers become useful for slower acquisition or analysis, but they introduce queue, shutdown and result-matching responsibilities. Follow the interface backend's rules for window operations.
When should the camera device actually be reopened?
Reopen it when a genuine acquisition failure or a documented configuration procedure requires a new session. An ordinary round transition should not need that recovery path. Keep recovery separate, report its status, and follow the device documentation for stopping, releasing and restarting acquisition.

