aisop/tests/Mvs.Smoke/Program.cs

164 lines
10 KiB
C#

using MvCameraControl;
using SopHelper.Engine.Camera;
using OpenCvSharp;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
try
{
using var camera=new HikvisionCameraService();
var errors=new List<string>();
camera.Error+=message=>{errors.Add(message);Console.Error.WriteLine(message);};
Console.WriteLine("SDK: "+SDKSystem.GetSDKVersion());
var cameras=await camera.EnumerateAsync();
foreach(var device in cameras)Console.WriteLine($"DEVICE: {device.Name}");
if(errors.Count>0)throw new Exception("Camera enumeration reported an error");
Console.WriteLine($"PASS: SDK initialized and enumerated {cameras.Count} camera(s)");
var d3BenchmarkIndex = Array.IndexOf(args, "--d3-benchmark");
var benchmarkIndex = d3BenchmarkIndex >= 0 ? d3BenchmarkIndex : Array.IndexOf(args, "--imajev-benchmark");
if (benchmarkIndex >= 0)
{
if (benchmarkIndex + 1 >= args.Length) throw new ArgumentException("AI benchmark requires an output directory");
var directory = Path.GetFullPath(args[benchmarkIndex + 1]);
Directory.CreateDirectory(directory);
var device = cameras.FirstOrDefault() ?? throw new Exception("No Hikvision camera found");
TaskCompletionSource<(Mat Image, long Started)>? requested = null;
var seen = 0;
camera.FrameArrived += frame =>
{
if (Interlocked.Increment(ref seen) < 5) return;
var pending = Interlocked.Exchange(ref requested, null);
if (pending is not null)
{
var started = Stopwatch.GetTimestamp();
pending.TrySetResult((frame.Bgr.Clone(), started));
}
};
if (!await camera.ConnectAsync(device) || !await camera.StartAsync()) throw new Exception("Open/start failed");
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
var runs = new List<object>();
for (var index = 0; index <= 20; index++)
{
var next = new TaskCompletionSource<(Mat Image, long Started)>(TaskCreationOptions.RunContinuationsAsynchronously);
Interlocked.Exchange(ref requested, next);
var captured = await next.Task.WaitAsync(TimeSpan.FromSeconds(10));
using var image = captured.Image;
using var resized = new Mat();
var scale = 512.0 / Math.Max(image.Width, image.Height);
Cv2.Resize(image, resized, new Size((int)Math.Round(image.Width * scale), (int)Math.Round(image.Height * scale)), 0, 0, InterpolationFlags.Area);
if (!Cv2.ImEncode(".jpg", resized, out var jpeg)) throw new IOException("JPEG encode failed");
var preparedMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
using HttpContent body = d3BenchmarkIndex >= 0
? new StringContent(JsonSerializer.Serialize(new { state = "", images = new[] { "data:image/jpeg;base64," + Convert.ToBase64String(jpeg) }, questions = new { empty = new { type = "noul", instructions = "盒子空了没?" } } }), Encoding.UTF8, "application/json")
: new MultipartFormDataContent();
if (body is MultipartFormDataContent form)
{
form.Add(new StringContent(JsonSerializer.Serialize(new { state = new { }, questions = new { empty = new { type = "noul", instructions = "Is the open cardboard box empty inside? Empty means there are no objects inside the box. Ignore objects outside the box." } } }), Encoding.UTF8), "request");
var content = new ByteArrayContent(jpeg);
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(content, "image", "camera.jpg");
}
var endpoint = d3BenchmarkIndex >= 0 ? "http://127.0.0.1:8766/v1/systemone" : "http://127.0.0.1:8765/v1/systemone";
using var response = await http.PostAsync(endpoint, body);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
using var result = JsonDocument.Parse(json);
if (d3BenchmarkIndex >= 0)
{
var digest = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(jpeg)).ToLowerInvariant();
if (result.RootElement.GetProperty("usage").GetProperty("image_sha256")[0].GetString() != digest)
throw new InvalidOperationException("D3 server received a different image");
}
var totalMs = Stopwatch.GetElapsedTime(captured.Started).TotalMilliseconds;
if (index == 0) File.WriteAllBytes(Path.Combine(directory, "fresh-camera-input.jpg"), jpeg);
var entry = new { index, warmup = index == 0, preprocess_ms = preparedMs, frame_to_result_ms = totalMs, response = result.RootElement.Clone() };
runs.Add(entry);
File.WriteAllText(Path.Combine(directory, "camera-e2e.json"), JsonSerializer.Serialize(new { camera = device.Name, scope = "From decoded BGR frame callback before clone, resize and JPEG encode through HTTP response parsing; excludes exposure, sensor readout, camera transport and camera startup", runs }, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"CAMERA AI: {index}, preprocess={preparedMs:F1}ms, frame_to_result={totalMs:F1}ms");
}
camera.Disconnect();
return 0;
}
var snapshotIndex = Array.IndexOf(args, "--snapshot");
if (snapshotIndex >= 0)
{
if (snapshotIndex + 1 >= args.Length) throw new ArgumentException("--snapshot requires an output path");
var path = Path.GetFullPath(args[snapshotIndex + 1]);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var device = cameras.FirstOrDefault() ?? throw new Exception("No Hikvision camera found");
var ready = new TaskCompletionSource<Mat>(TaskCreationOptions.RunContinuationsAsynchronously);
var frames = 0;
camera.FrameArrived += frame =>
{
if (Interlocked.Increment(ref frames) == 5) ready.TrySetResult(frame.Bgr.Clone());
};
var watch = System.Diagnostics.Stopwatch.StartNew();
if (!await camera.ConnectAsync(device) || !await camera.StartAsync()) throw new Exception("Open/start failed");
using var captured = await ready.Task.WaitAsync(TimeSpan.FromSeconds(15));
watch.Stop();
camera.Disconnect();
if (!Cv2.ImWrite(path, captured)) throw new IOException("Snapshot write failed");
Console.WriteLine($"SNAPSHOT: {path}; {captured.Width}x{captured.Height}; camera={device.Name}; open/start/5 frames={watch.Elapsed.TotalMilliseconds:F1}ms");
return 0;
}
if(args.Contains("--inspect-timing"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
if(device.Open()!=MvError.MV_OK)throw new Exception("Open failed");
try
{
foreach(var node in new[]{"ExposureTime","AcquisitionFrameRate","ResultingFrameRate"})
if(device.Parameters.GetFloatValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TIMING: {node}={value.CurValue} (max={value.Max})");
foreach(var node in new[]{"PayloadSize","DeviceLinkThroughputLimit","GevSCPSPacketSize","GevSCPD"})
if(device.Parameters.GetIntValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TRANSPORT: {node}={value.CurValue}");
}
finally { device.Close(); }
}
if(args.Contains("--inspect-frame"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
Console.WriteLine($"OPEN: 0x{device.Open():X8}");
device.Parameters.SetEnumValueByString("TriggerMode","Off");
try
{
Console.WriteLine($"START: 0x{device.StreamGrabber.StartGrabbing():X8}");
result=device.StreamGrabber.GetImageBuffer(3000,out var buffer);
Console.WriteLine($"GET: 0x{result:X8}");
if(result==MvError.MV_OK)
{
try
{
foreach(var p in typeof(IImage).GetProperties().Where(p=>p.Name!="PixelData"))Console.WriteLine($"IMAGE {p.Name}: {p.GetValue(buffer.Image)}");
result=device.PixelTypeConverter.ConvertPixelType(buffer.Image,out var converted,MvGvspPixelType.PixelType_Gvsp_BGR8_Packed);
using(converted)Console.WriteLine($"CONVERT: 0x{result:X8}");
}
finally{device.StreamGrabber.FreeImageBuffer(buffer);}
}
}
finally{device.StreamGrabber.StopGrabbing();device.Close();}
}
if(args.Contains("--hardware"))
{
var device=cameras.FirstOrDefault()??throw new Exception("No camera found");
var ready=new TaskCompletionSource<(int W,int H)>(TaskCreationOptions.RunContinuationsAsynchronously);
var frames=0;
camera.FrameArrived+=frame=>{if(Interlocked.Increment(ref frames)>=5)ready.TrySetResult((frame.Bgr.Width,frame.Bgr.Height));};
if(!await camera.ConnectAsync(device)||!await camera.StartAsync())throw new Exception("Open/start failed");
var frame=await ready.Task.WaitAsync(TimeSpan.FromSeconds(10));
camera.Disconnect();
Console.WriteLine($"PASS: acquired {frames} {frame.W}x{frame.H} BGR frames and released camera");
if(!await camera.ConnectAsync(device))throw new Exception("Camera could not reopen after disconnect");
camera.Disconnect();Console.WriteLine("PASS: camera reopened after release");
}
return 0;
}
catch(Exception error){Console.Error.WriteLine(error);return 1;}