Best Practices#
Resource Management#
Always ensure that camera resources are acquired and released properly.
Benefits:
- Automatic cleanup
- Exception safety
- Prevents resource leaks
Device Identification#
Never rely on device indices as they are not stable:
Use unique identifiers instead:
- Serial number
- User-defined name
See Discovering and Selecting a Camera for details.
パフォーマンスの最適化#
Use Appropriate Grab Strategy#
LatestImageOnly→ low latencyOneByOne→ complete processing
Reduce Data at Source#
- Specify a ROI.
- Reduce resolution.
- Lower frame rate if possible.
Avoid Unnecessary Copies#
- Copy only when required.
- Reuse buffers when possible.
Threading Design#
Separate Acquisition and Processing#
Benefits:
- Better CPU utilization
- Avoids blocking acquisition
Use Producer–Consumer Pattern#
- Acquisition thread pushes images.
- Processing threads consume them.
Use Thread-Safe Queues#
Multi-Stage Pipelines#
Structure complex applications as pipelines:
Guidelines:
- Each stage has one responsibility.
- Communicate via queues.
- Allow independent scaling per stage.
Error Handling#
Always Check Grab Success#
if grab_result.GrabSucceeded():
process(grab_result.Array)
else:
log_error(grab_result.ErrorDescription)
Catch and Log Exceptions#
Implement Recovery Logic#
Shutdown Strategy#
Implement clean shutdown mechanisms:
- Use
threading.Event. - Avoid blocking calls without timeout.
- Stop acquisition explicitly.
OpenCV Integration Rules#
- Run
imshow()only in main thread. - Avoid GUI in worker threads.
System Monitoring#
Track key metrics:
- Frame rate
- Processing latency
- Queue sizes
- CPU usage
Configuration Management#
- Store camera parameters externally.
- Avoid hardcoded values.
- Validate configuration at startup.
Recommendations for Testing#
- Test with real hardware.
- Simulate load conditions.
- Verify recovery behavior.
Common Pitfalls#
- Using image buffers after release
- Blocking queues indefinitely
- Ignoring synchronization requirements
- Mixing UI and worker threads
Mental Model#
Key Takeaways#
- Design for robustness from the start.
- Separate concerns (acquisition vs. processing).
- Validate every external interaction.
- Plan for failure and recovery.