C#

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Text.Json;
    using System.Threading;
    using System.Threading.Tasks;
    using HalconDotNet;

    public sealed class PythonImageWorker : IDisposable
    {
        private readonly Process _process;
        private readonly Stream _stdin;
        private readonly Stream _stdout;
        private int _frameId = 0;
        private bool _disposed = false;

        public PythonImageWorker(string pythonExePath, string workerPyPath)
        {
            var psi = new ProcessStartInfo
            {
                FileName = pythonExePath,
                Arguments = $"\"{workerPyPath}\"",
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            _process = new Process
            {
                StartInfo = psi,
                EnableRaisingEvents = true
            };

            _process.Start();

            _stdin = _process.StandardInput.BaseStream;
            _stdout = _process.StandardOutput.BaseStream;

            // stderrを読み続けないと、ログが溜まってPython側が詰まる可能性がある
            _ = Task.Run(async () =>
            {
                try
                {
                    while (!_process.HasExited)
                    {
                        string? line = await _process.StandardError.ReadLineAsync();
                        if (line == null)
                            break;

                        Debug.WriteLine("[Python stderr] " + line);
                        Console.Error.WriteLine("[Python stderr] " + line);
                    }
                }
                catch
                {
                    // 終了時などは握りつぶす
                }
            });
        }

        /// <summary>
        /// HALCONのMono8 HObject画像をPythonへ送り、
        /// Pythonから返ってきたMono8画像をHObjectとして返す。
        /// </summary>
        public async Task<HObject> ProcessMono8Async(
            HObject inputImage,
            int timeoutMs = 5000,
            CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();

            if (_process.HasExited)
                throw new InvalidOperationException("Python worker has already exited.");

            int frameId = Interlocked.Increment(ref _frameId);

            // HObject -> byte[]
            byte[] imageBytes = HObjectMono8ToBytes(inputImage, out int width, out int height);

            var requestHeader = new PacketHeader
            {
                frame_id = frameId,
                ok = true,
                width = width,
                height = height,
                pixel_type = "mono8",
                byte_length = imageBytes.Length,
                message = "request"
            };

            using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            cts.CancelAfter(timeoutMs);

            // C# -> Python
            await WritePacketAsync(_stdin, requestHeader, imageBytes, cts.Token);

            // Python -> C#
            var response = await ReadPacketAsync(_stdout, cts.Token);

            if (!response.Header.ok)
            {
                throw new InvalidOperationException(
                    $"Python worker error: {response.Header.message}");
            }

            if (response.Header.pixel_type != "mono8")
            {
                throw new InvalidOperationException(
                    $"Unsupported response pixel_type: {response.Header.pixel_type}");
            }

            if (response.Header.width != width || response.Header.height != height)
            {
                throw new InvalidOperationException(
                    $"Response image size mismatch. " +
                    $"request={width}x{height}, response={response.Header.width}x{response.Header.height}");
            }

            int expectedLength = response.Header.width * response.Header.height;
            if (response.ImageBytes.Length != expectedLength)
            {
                throw new InvalidOperationException(
                    $"Response byte length mismatch. expected={expectedLength}, actual={response.ImageBytes.Length}");
            }

            // byte[] -> HObject
            HObject outputImage = BytesToHObjectMono8(
                response.ImageBytes,
                response.Header.width,
                response.Header.height);

            return outputImage;
        }

        private static byte[] HObjectMono8ToBytes(HObject image, out int width, out int height)
        {
            // HALCON画像のポインタを取得
            HOperatorSet.GetImagePointer1(
                image,
                out HTuple pointer,
                out HTuple type,
                out HTuple widthTuple,
                out HTuple heightTuple);

            string halconType = type.S;

            if (halconType != "byte")
            {
                throw new InvalidOperationException(
                    $"This sample supports only Mono8 HALCON image. Actual type: {halconType}");
            }

            width = widthTuple.I;
            height = heightTuple.I;

            int byteLength = checked(width * height);
            byte[] bytes = new byte[byteLength];

            IntPtr srcPtr = new IntPtr(pointer.L);

            Marshal.Copy(srcPtr, bytes, 0, byteLength);

            return bytes;
        }

        private static HObject BytesToHObjectMono8(byte[] bytes, int width, int height)
        {
            if (bytes.Length != width * height)
            {
                throw new ArgumentException(
                    $"Invalid byte length. expected={width * height}, actual={bytes.Length}");
            }

            HObject image;

            // byte[]を一時的に固定してHALCONへ渡す
            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                IntPtr ptr = handle.AddrOfPinnedObject();

                HOperatorSet.GenImage1(
                    out image,
                    "byte",
                    width,
                    height,
                    ptr);
            }
            finally
            {
                handle.Free();
            }

            return image;
        }

        private static async Task WritePacketAsync(
            Stream stream,
            PacketHeader header,
            byte[] imageBytes,
            CancellationToken cancellationToken)
        {
            header.byte_length = imageBytes.Length;

            byte[] headerBytes = JsonSerializer.SerializeToUtf8Bytes(header);

            if (headerBytes.Length > int.MaxValue)
                throw new InvalidOperationException("Header is too large.");

            // little-endian 4byte
            byte[] headerLengthBytes = BitConverter.GetBytes((uint)headerBytes.Length);

            if (!BitConverter.IsLittleEndian)
                Array.Reverse(headerLengthBytes);

            await stream.WriteAsync(headerLengthBytes, 0, headerLengthBytes.Length, cancellationToken);
            await stream.WriteAsync(headerBytes, 0, headerBytes.Length, cancellationToken);
            await stream.WriteAsync(imageBytes, 0, imageBytes.Length, cancellationToken);
            await stream.FlushAsync(cancellationToken);
        }

        private static async Task<Packet> ReadPacketAsync(
            Stream stream,
            CancellationToken cancellationToken)
        {
            byte[] headerLengthBytes = await ReadExactAsync(stream, 4, cancellationToken);

            if (!BitConverter.IsLittleEndian)
                Array.Reverse(headerLengthBytes);

            uint headerLength = BitConverter.ToUInt32(headerLengthBytes, 0);

            if (headerLength == 0 || headerLength > 1024 * 1024)
            {
                throw new InvalidOperationException($"Invalid header length: {headerLength}");
            }

            byte[] headerBytes = await ReadExactAsync(stream, checked((int)headerLength), cancellationToken);

            PacketHeader? header = JsonSerializer.Deserialize<PacketHeader>(headerBytes);

            if (header == null)
                throw new InvalidOperationException("Failed to deserialize response header.");

            if (header.byte_length < 0)
                throw new InvalidOperationException($"Invalid byte_length: {header.byte_length}");

            byte[] imageBytes = await ReadExactAsync(stream, header.byte_length, cancellationToken);

            return new Packet(header, imageBytes);
        }

        private static async Task<byte[]> ReadExactAsync(
            Stream stream,
            int size,
            CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[size];
            int offset = 0;

            while (offset < size)
            {
                int read = await stream.ReadAsync(
                    buffer,
                    offset,
                    size - offset,
                    cancellationToken);

                if (read == 0)
                    throw new EndOfStreamException("Stream closed while reading packet.");

                offset += read;
            }

            return buffer;
        }

        private void ThrowIfDisposed()
        {
            if (_disposed)
                throw new ObjectDisposedException(nameof(PythonImageWorker));
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            _disposed = true;

            try
            {
                _stdin.Close();
            }
            catch
            {
            }

            try
            {
                if (!_process.HasExited)
                {
                    _process.Kill(entireProcessTree: true);
                    _process.WaitForExit(1000);
                }
            }
            catch
            {
            }

            _process.Dispose();
        }

        private sealed class PacketHeader
        {
            public int? frame_id { get; set; }
            public bool ok { get; set; }
            public int width { get; set; }
            public int height { get; set; }
            public string pixel_type { get; set; } = "mono8";
            public int byte_length { get; set; }
            public string message { get; set; } = "";
        }

        private sealed record Packet(PacketHeader Header, byte[] ImageBytes);
    }




    //使用例
    using System;
    using System.Threading.Tasks;
    using HalconDotNet;

    internal class Program
    {
        private static async Task Main()
        {
            // 環境に合わせて変更してください
            string pythonExePath = "python";
            string workerPyPath = @"C:\work\worker.py";

            using var worker = new PythonImageWorker(pythonExePath, workerPyPath);

            // --------------------------------------------
            // 本来はここでカメラ撮像したHObjectを使う
            // 例:
            // HOperatorSet.GrabImage(out HObject inputImage, hv_AcqHandle);
            // --------------------------------------------

            HObject inputImage = CreateDummyMono8Image(640, 480);

            HObject outputImage = await worker.ProcessMono8Async(inputImage);

            Console.WriteLine("Python round-trip completed.");

            // 結果画像を確認したい場合
            HOperatorSet.WriteImage(outputImage, "png", 0, @"C:\work\result_from_python.png");

            inputImage.Dispose();
            outputImage.Dispose();

            Console.WriteLine("Saved: C:\\work\\result_from_python.png");
        }

        private static HObject CreateDummyMono8Image(int width, int height)
        {
            byte[] bytes = new byte[width * height];

            // 適当なグラデーション画像を作成
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    bytes[y * width + x] = (byte)(x % 256);
                }
            }

            HObject image;

            var handle = System.Runtime.InteropServices.GCHandle.Alloc(
                bytes,
                System.Runtime.InteropServices.GCHandleType.Pinned);

            try
            {
                IntPtr ptr = handle.AddrOfPinnedObject();

                HOperatorSet.GenImage1(
                    out image,
                    "byte",
                    width,
                    height,
                    ptr);
            }
            finally
            {
                handle.Free();
            }

            return image;
        }
    }

    \\----------------

    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text.Json;
    using System.Threading;
    using HalconDotNet;

    public sealed class PythonImageWorkerSync : IDisposable
    {
        private readonly Process _process;
        private readonly Stream _stdin;
        private readonly Stream _stdout;
        private readonly object _lockObj = new object();

        private Thread? _stderrThread;
        private volatile bool _disposed = false;
        private int _frameId = 0;

        public PythonImageWorkerSync(string pythonExePath, string workerPyPath)
        {
            var psi = new ProcessStartInfo
            {
                FileName = pythonExePath,
                Arguments = $"\"{workerPyPath}\"",
                UseShellExecute = false,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            _process = new Process
            {
                StartInfo = psi,
                EnableRaisingEvents = true
            };

            bool started = _process.Start();

            if (!started)
                throw new InvalidOperationException("Failed to start Python worker.");

            _stdin = _process.StandardInput.BaseStream;
            _stdout = _process.StandardOutput.BaseStream;

            StartStderrReadThread();
        }

        public HObject ProcessMono8(HObject inputImage)
        {
            ThrowIfDisposed();

            if (_process.HasExited)
                throw new InvalidOperationException("Python worker has already exited.");

            lock (_lockObj)
            {
                int frameId = Interlocked.Increment(ref _frameId);

                byte[] imageBytes = HObjectMono8ToBytes(
                    inputImage,
                    out int width,
                    out int height);

                var requestHeader = new PacketHeader
                {
                    frame_id = frameId,
                    ok = true,
                    width = width,
                    height = height,
                    pixel_type = "mono8",
                    byte_length = imageBytes.Length,
                    message = "request"
                };

                WritePacket(_stdin, requestHeader, imageBytes);

                Packet response = ReadPacket(_stdout);

                if (!response.Header.ok)
                {
                    throw new InvalidOperationException(
                        $"Python worker error: {response.Header.message}");
                }

                if (response.Header.pixel_type != "mono8")
                {
                    throw new InvalidOperationException(
                        $"Unsupported response pixel_type: {response.Header.pixel_type}");
                }

                if (response.Header.width != width || response.Header.height != height)
                {
                    throw new InvalidOperationException(
                        $"Response image size mismatch. " +
                        $"request={width}x{height}, " +
                        $"response={response.Header.width}x{response.Header.height}");
                }

                int expectedLength = response.Header.width * response.Header.height;

                if (response.ImageBytes.Length != expectedLength)
                {
                    throw new InvalidOperationException(
                        $"Response byte length mismatch. " +
                        $"expected={expectedLength}, actual={response.ImageBytes.Length}");
                }

                HObject outputImage = BytesToHObjectMono8(
                    response.ImageBytes,
                    response.Header.width,
                    response.Header.height);

                return outputImage;
            }
        }

        private void StartStderrReadThread()
        {
            _stderrThread = new Thread(() =>
            {
                try
                {
                    while (!_disposed && !_process.HasExited)
                    {
                        string? line = _process.StandardError.ReadLine();

                        if (line == null)
                            break;

                        Debug.WriteLine("[Python stderr] " + line);
                        Console.Error.WriteLine("[Python stderr] " + line);
                    }
                }
                catch
                {
                    // 終了時の例外は握りつぶす
                }
            });

            _stderrThread.IsBackground = true;
            _stderrThread.Name = "Python stderr reader";
            _stderrThread.Start();
        }

        private static byte[] HObjectMono8ToBytes(
            HObject image,
            out int width,
            out int height)
        {
            HOperatorSet.GetImagePointer1(
                image,
                out HTuple pointer,
                out HTuple type,
                out HTuple widthTuple,
                out HTuple heightTuple);

            string halconType = type.S;

            if (halconType != "byte")
            {
                throw new InvalidOperationException(
                    $"This sample supports only Mono8 HALCON image. Actual type: {halconType}");
            }

            width = widthTuple.I;
            height = heightTuple.I;

            int byteLength = checked(width * height);
            byte[] bytes = new byte[byteLength];

            IntPtr srcPtr = HTuplePointerToIntPtr(pointer);

            Marshal.Copy(srcPtr, bytes, 0, byteLength);

            return bytes;
        }

        private static HObject BytesToHObjectMono8(
            byte[] bytes,
            int width,
            int height)
        {
            if (bytes.Length != width * height)
            {
                throw new ArgumentException(
                    $"Invalid byte length. expected={width * height}, actual={bytes.Length}");
            }

            HObject image;

            GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);

            try
            {
                IntPtr ptr = handle.AddrOfPinnedObject();

                HOperatorSet.GenImage1(
                    out image,
                    "byte",
                    width,
                    height,
                    ptr);
            }
            finally
            {
                handle.Free();
            }

            return image;
        }

        private static IntPtr HTuplePointerToIntPtr(HTuple pointer)
        {
            if (IntPtr.Size == 8)
                return new IntPtr(pointer.L);

            return new IntPtr(pointer.I);
        }

        private static void WritePacket(
            Stream stream,
            PacketHeader header,
            byte[] imageBytes)
        {
            header.byte_length = imageBytes.Length;

            byte[] headerBytes = JsonSerializer.SerializeToUtf8Bytes(header);

            if (headerBytes.Length <= 0)
                throw new InvalidOperationException("Header is empty.");

            byte[] headerLengthBytes = BitConverter.GetBytes((uint)headerBytes.Length);

            if (!BitConverter.IsLittleEndian)
                Array.Reverse(headerLengthBytes);

            stream.Write(headerLengthBytes, 0, headerLengthBytes.Length);
            stream.Write(headerBytes, 0, headerBytes.Length);
            stream.Write(imageBytes, 0, imageBytes.Length);
            stream.Flush();
        }

        private static Packet ReadPacket(Stream stream)
        {
            byte[] headerLengthBytes = ReadExact(stream, 4);

            if (!BitConverter.IsLittleEndian)
                Array.Reverse(headerLengthBytes);

            uint headerLength = BitConverter.ToUInt32(headerLengthBytes, 0);

            if (headerLength == 0 || headerLength > 1024 * 1024)
            {
                throw new InvalidOperationException(
                    $"Invalid response header length: {headerLength}");
            }

            byte[] headerBytes = ReadExact(stream, checked((int)headerLength));

            PacketHeader? header = JsonSerializer.Deserialize<PacketHeader>(headerBytes);

            if (header == null)
                throw new InvalidOperationException("Failed to deserialize response header.");

            if (header.byte_length < 0)
                throw new InvalidOperationException($"Invalid byte_length: {header.byte_length}");

            byte[] imageBytes = ReadExact(stream, header.byte_length);

            return new Packet(header, imageBytes);
        }

        private static byte[] ReadExact(Stream stream, int size)
        {
            byte[] buffer = new byte[size];
            int offset = 0;

            while (offset < size)
            {
                int read = stream.Read(buffer, offset, size - offset);

                if (read == 0)
                    throw new EndOfStreamException("Stream closed while reading packet.");

                offset += read;
            }

            return buffer;
        }

        private void ThrowIfDisposed()
        {
            if (_disposed)
                throw new ObjectDisposedException(nameof(PythonImageWorkerSync));
        }

        public void Dispose()
        {
            if (_disposed)
                return;

            _disposed = true;

            try
            {
                _stdin.Close();
            }
            catch
            {
            }

            try
            {
                if (!_process.HasExited)
                {
                    _process.Kill(entireProcessTree: true);
                    _process.WaitForExit(1000);
                }
            }
            catch
            {
            }

            try
            {
                _process.Dispose();
            }
            catch
            {
            }
        }

        private sealed class PacketHeader
        {
            public int? frame_id { get; set; }
            public bool ok { get; set; }
            public int width { get; set; }
            public int height { get; set; }
            public string pixel_type { get; set; } = "mono8";
            public int byte_length { get; set; }
            public string message { get; set; } = "";
        }

        private sealed class Packet
        {
            public PacketHeader Header { get; }
            public byte[] ImageBytes { get; }

            public Packet(PacketHeader header, byte[] imageBytes)
            {
                Header = header;
                ImageBytes = imageBytes;
            }
        }
    }

    //動作確認用
    using System;
    using System.Threading;
    using HalconDotNet;

    internal class Program
    {
        private static void Main()
        {
            string pythonExePath = "python";
            string workerPyPath = @"C:\work\worker.py";

            using var pythonWorker = new PythonImageWorkerSync(
                pythonExePath,
                workerPyPath);

            using var processingThread = new ImageProcessingThread(
                pythonWorker,
                onProcessed: OnProcessed,
                onError: OnError);

            processingThread.Start();

            try
            {
                // ============================================
                // ダミー撮像ループ
                // 実際にはここをGrabImageなどに置き換える
                // ============================================
                for (int i = 1; i <= 10; i++)
                {
                    HObject grabbedImage = CreateDummyMono8Image(640, 480, i);

                    try
                    {
                        Console.WriteLine($"Enqueue frame {i}");

                        processingThread.EnqueueFrame(i, grabbedImage);
                    }
                    finally
                    {
                        // EnqueueFrame内部でCopyImageしているので、
                        // 撮像側の画像はここで破棄してよい
                        grabbedImage.Dispose();
                    }

                    Thread.Sleep(100);
                }

                // 撮像終了フラグ
                Console.WriteLine("Capture finished.");
                processingThread.SetCaptureFinished();

                // 処理キューが空になるまで待つ
                processingThread.Join();

                Console.WriteLine("Processing thread finished.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Main error:");
                Console.WriteLine(ex);

                processingThread.RequestStop();
                processingThread.Join();
            }
        }

        private static void OnProcessed(int frameNo, HObject processedImage)
        {
            try
            {
                Console.WriteLine($"Processed frame {frameNo}");

                string savePath = $@"C:\work\result_{frameNo:000}.png";

                HOperatorSet.WriteImage(
                    processedImage,
                    "png",
                    0,
                    savePath);

                Console.WriteLine($"Saved: {savePath}");
            }
            finally
            {
                // ImageProcessingThread側から所有権を受け取ったので、
                // ここでDisposeする。
                processedImage.Dispose();
            }
        }

        private static void OnError(Exception ex)
        {
            Console.WriteLine("Processing error:");
            Console.WriteLine(ex);
        }

        private static HObject CreateDummyMono8Image(
            int width,
            int height,
            int frameNo)
        {
            byte[] bytes = new byte[width * height];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    bytes[y * width + x] = (byte)((x + frameNo * 10) % 256);
                }
            }

            HObject image;

            var handle = System.Runtime.InteropServices.GCHandle.Alloc(
                bytes,
                System.Runtime.InteropServices.GCHandleType.Pinned);

            try
            {
                IntPtr ptr = handle.AddrOfPinnedObject();

                HOperatorSet.GenImage1(
                    out image,
                    "byte",
                    width,
                    height,
                    ptr);
            }
            finally
            {
                handle.Free();
            }

            return image;
        }
    }