Location>code7788 >text

C# USB camera OpenCV video picBox rendering, capture images saved and rendered. No commented version.

Popularity:291 ℃/2025-03-05 10:21:31
public partial class Form2 : Form { //Modify member variables private volatile Bitmap _latestFrameBitmap; private readonly object _bitmapLock = new object(); private VideoCapture _capture; private CancellationTokenSource _cts; public Form2() { InitializeComponent(); } private async void Form2_Load(object sender, EventArgs e) { _capture = new VideoCapture(0); if (!_capture.IsOpened()) { ("The camera cannot be turned on!"); return; } _cts = new CancellationTokenSource(); try { await StartCapturingAsync(_cts.Token); } catch (OperationCanceledException) { //Cancel normally } catch (Exception ex) { ($"Capture error: {}"); } } private async Task StartCapturingAsync(CancellationToken token) { using (var frame = new Mat()) { while (!) { _capture.Read(frame); if (()) continue; var newBitmap = (frame); //Update the latest frame lock (_bitmapLock) { var old = _latestFrameBitmap; _latestFrameBitmap = newBitmap; old?.Dispose(); } await UpdateCameraPreviewAsync(newBitmap); await (30, token); } } } private async Task UpdateCameraPreviewAsync(Bitmap bitmap) { if () { (); return; } try { if () { (new Action(() => UpdateCamera(bitmap))); } else { UpdateCamera(bitmap); } } catch (ObjectDisposedException) { (); } } private void UpdateCamera(Bitmap newBitmap) { if () { (); return; } var old = ; = newBitmap; old?.Dispose(); } //Optimized capture method private async void catchBtn_Click(object sender, EventArgs e) { try { Bitmap snapshot = null; //Securely get the current frame lock (_bitmapLock) { if (_latestFrameBitmap != null) { snapshot = (Bitmap)_latestFrameBitmap.Clone(); } } if (snapshot == null) { ("There are currently no video frames available"); return; } //Asynchronous saving prevents interface from being stuck await (() => SaveSnapshot(snapshot)); } catch (Exception ex) { ($"Failed to capture: {}"); } } private void SaveSnapshot(Bitmap bitmap) { try { var fileName = GenerateUniqueFileName(); using (bitmap) //Ensure resources are released { (fileName, ); //Show preview (need to clone a new instance) var previewBitmap = (Bitmap)(); BeginInvoke(new Action(() => { UpdateSnapshotPreview(previewBitmap); ($"The image has been saved to:\n{fileName}"); })); } } catch (Exception ex) { BeginInvoke(new Action(() => { ($"Saving failed: {}"); })); } } //Added preview update method private void UpdateSnapshotPreview(Bitmap newBitmap) { if () { (); return; } //Handle cross-thread access if () { (new Action(() => UpdateSnapshotPreview(newBitmap))); return; } //Update controls and release old resources var old = ; = newBitmap; old?.Dispose(); } private string GenerateUniqueFileName() { var docs = (); var timestamp = ("yyyyMMdd_HHmmssfff"); return (docs, $"Snapshot_{timestamp}.jpg"); } private void Form2_FormClosing(object sender, FormClosingEventArgs e) { _cts?.Cancel(); _cts?.Dispose(); //Free up all resources _capture?.Dispose(); lock (_bitmapLock) { _latestFrameBitmap?.Dispose(); } //Clean the preview image if ( != null) { var img = ; = null; (); } //Added snapshot preview cleaning if ( != null) { var img = ; = null; (); } } }