diff --git a/tests/Mvs.Smoke/Program.cs b/tests/Mvs.Smoke/Program.cs index 238b1b7..7df833e 100644 --- a/tests/Mvs.Smoke/Program.cs +++ b/tests/Mvs.Smoke/Program.cs @@ -1,5 +1,6 @@ using MvCameraControl; using SopHelper.Engine.Camera; +using OpenCvSharp; try { @@ -11,6 +12,28 @@ try 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 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(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); diff --git a/tools/benchmark_laya_vision.py b/tools/benchmark_laya_vision.py new file mode 100644 index 0000000..81bdcfb --- /dev/null +++ b/tools/benchmark_laya_vision.py @@ -0,0 +1,68 @@ +"""Repeat one Laya vision question against the same captured image.""" +import argparse +import datetime +import hashlib +import json +from pathlib import Path +import statistics +import time +import urllib.request +import uuid + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("image", type=Path) + parser.add_argument("--count", type=int, default=5) + parser.add_argument("--endpoint", default="http://127.0.0.1:8000/v1/vision/decide") + parser.add_argument("--question", default="图中打开的棕色纸盒里面是否为空?只检查纸盒内部,不考虑盒子外的物体。空表示盒内没有任何物品。") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.count < 1: + parser.error("count must be positive") + image = args.image.read_bytes() + if not 0 < len(image) <= 10 * 1024 * 1024: + parser.error("image must be between 1 byte and 10MB") + questions = {"box_empty": {"type": "noul", "instructions": args.question}} + boundary = uuid.uuid4().hex + body = ( + f'--{boundary}\r\nContent-Disposition: form-data; name="questions"\r\n\r\n'.encode() + + json.dumps(questions, ensure_ascii=False).encode("utf-8") + + f'\r\n--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="capture.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'.encode() + + image + + f"\r\n--{boundary}--\r\n".encode() + ) + report = { + "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "endpoint": args.endpoint, "image": str(args.image.resolve()), + "image_bytes": len(image), "image_sha256": hashlib.sha256(image).hexdigest(), + "questions": questions, "timing_scope": "HTTP request through complete response read; excludes capture and multipart preparation", + "runs": [], + } + args.output.parent.mkdir(parents=True, exist_ok=True) + for index in range(1, args.count + 1): + request = urllib.request.Request(args.endpoint, data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) + started = time.perf_counter() + with urllib.request.urlopen(request, timeout=180) as response: + payload = response.read() + http_ms = (time.perf_counter() - started) * 1000 + result = json.loads(payload) + answer = result["answers"]["box_empty"] + probability = answer["noul"] + run = {"run": index, "http_ms": round(http_ms, 2), "server_ms": result["latency_ms"], + "inference_ms": result["inference_ms"], "empty_probability": probability, + "prediction": "空" if probability >= .5 else "非空", "response": result} + report["runs"].append(run) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps({key: value for key, value in run.items() if key != "response"}, ensure_ascii=False), flush=True) + report["summary"] = { + key: {"mean": round(statistics.mean(run[key] for run in report["runs"]), 2), + "min": min(run[key] for run in report["runs"]), "max": max(run[key] for run in report["runs"])} + for key in ("http_ms", "server_ms", "inference_ms") + } + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps(report["summary"], ensure_ascii=False), flush=True) + + +if __name__ == "__main__": + main()