image-server-kit 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- image_server_kit-0.0.1/LICENSE +201 -0
- image_server_kit-0.0.1/PKG-INFO +76 -0
- image_server_kit-0.0.1/README.md +54 -0
- image_server_kit-0.0.1/pyproject.toml +42 -0
- image_server_kit-0.0.1/setup.cfg +4 -0
- image_server_kit-0.0.1/src/image_server/__init__.py +3 -0
- image_server_kit-0.0.1/src/image_server/image_stream_ctrl.py +382 -0
- image_server_kit-0.0.1/src/image_server/server_grpc/__init__.py +7 -0
- image_server_kit-0.0.1/src/image_server/server_grpc/client.py +88 -0
- image_server_kit-0.0.1/src/image_server/server_grpc/client.pyi +21 -0
- image_server_kit-0.0.1/src/image_server/server_grpc/image_stream_grpc_service.py +272 -0
- image_server_kit-0.0.1/src/image_server/server_grpc/make_pyi.py +37 -0
- image_server_kit-0.0.1/src/image_server_kit.egg-info/PKG-INFO +76 -0
- image_server_kit-0.0.1/src/image_server_kit.egg-info/SOURCES.txt +15 -0
- image_server_kit-0.0.1/src/image_server_kit.egg-info/dependency_links.txt +1 -0
- image_server_kit-0.0.1/src/image_server_kit.egg-info/requires.txt +12 -0
- image_server_kit-0.0.1/src/image_server_kit.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: image-server-kit
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: image_server (Template)
|
|
5
|
+
Author-email: Kengo NAKADA <kengo.nakada@email.com>
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: xlogger-py
|
|
10
|
+
Requires-Dist: pyserial
|
|
11
|
+
Requires-Dist: nest_asyncio
|
|
12
|
+
Requires-Dist: pydantic
|
|
13
|
+
Requires-Dist: pyyaml
|
|
14
|
+
Requires-Dist: pytest
|
|
15
|
+
Requires-Dist: sphinx
|
|
16
|
+
Requires-Dist: myst-parser
|
|
17
|
+
Requires-Dist: sphinx-autobuild
|
|
18
|
+
Requires-Dist: sphinx-rtd-theme
|
|
19
|
+
Requires-Dist: sphinxcontrib-napoleon
|
|
20
|
+
Requires-Dist: linkify-it-py
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# image_server
|
|
24
|
+
|
|
25
|
+
image_server は「USBカメラを扱うライブラリ」ではありません。
|
|
26
|
+
|
|
27
|
+
本ライブラリは **画像転送機能を既存プログラムへ組み込むためのテンプレート** です。
|
|
28
|
+
OpenCV・gRPC・Viewer を毎回実装するのではなく、画像取得部分だけを書き換えることで
|
|
29
|
+
画像転送システムを短時間で構築できることを目的としています。
|
|
30
|
+
|
|
31
|
+
## このライブラリが解決する問題
|
|
32
|
+
|
|
33
|
+
通常は次のような処理を毎回実装する必要があります。
|
|
34
|
+
|
|
35
|
+
- カメラ接続
|
|
36
|
+
- フレーム取得
|
|
37
|
+
- JPEG圧縮
|
|
38
|
+
- 通信
|
|
39
|
+
- Viewer
|
|
40
|
+
- 接続管理
|
|
41
|
+
- スレッド管理
|
|
42
|
+
|
|
43
|
+
image_server はこれらを共通化し、利用者は **画像取得部だけ** を実装します。
|
|
44
|
+
|
|
45
|
+
## レイヤ構造
|
|
46
|
+
|
|
47
|
+
Application
|
|
48
|
+
↓
|
|
49
|
+
ImageStreamGrpcService
|
|
50
|
+
↓
|
|
51
|
+
ImageStreamCtrl
|
|
52
|
+
↓
|
|
53
|
+
Camera SDK
|
|
54
|
+
|
|
55
|
+
ImageStreamCtrl は Camera SDK を抽象化する層です。
|
|
56
|
+
ImageStreamGrpcService は画像配信だけを担当します。
|
|
57
|
+
|
|
58
|
+
## 開発フロー
|
|
59
|
+
|
|
60
|
+
1. ImageStreamCtrl を OpenCV で動かす
|
|
61
|
+
2. SDK に置き換える
|
|
62
|
+
3. run_image_server.py を起動
|
|
63
|
+
4. Viewer で確認
|
|
64
|
+
5. DeviceProxy や AI システムへ組み込む
|
|
65
|
+
|
|
66
|
+
## 想定用途
|
|
67
|
+
|
|
68
|
+
- USB Camera
|
|
69
|
+
- Basler
|
|
70
|
+
- IDS
|
|
71
|
+
- HikVision
|
|
72
|
+
- GigE Vision
|
|
73
|
+
- ORiN Camera
|
|
74
|
+
- AI 推論サーバ
|
|
75
|
+
- 外観検査
|
|
76
|
+
- ロボットビジョン
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# image_server
|
|
2
|
+
|
|
3
|
+
image_server は「USBカメラを扱うライブラリ」ではありません。
|
|
4
|
+
|
|
5
|
+
本ライブラリは **画像転送機能を既存プログラムへ組み込むためのテンプレート** です。
|
|
6
|
+
OpenCV・gRPC・Viewer を毎回実装するのではなく、画像取得部分だけを書き換えることで
|
|
7
|
+
画像転送システムを短時間で構築できることを目的としています。
|
|
8
|
+
|
|
9
|
+
## このライブラリが解決する問題
|
|
10
|
+
|
|
11
|
+
通常は次のような処理を毎回実装する必要があります。
|
|
12
|
+
|
|
13
|
+
- カメラ接続
|
|
14
|
+
- フレーム取得
|
|
15
|
+
- JPEG圧縮
|
|
16
|
+
- 通信
|
|
17
|
+
- Viewer
|
|
18
|
+
- 接続管理
|
|
19
|
+
- スレッド管理
|
|
20
|
+
|
|
21
|
+
image_server はこれらを共通化し、利用者は **画像取得部だけ** を実装します。
|
|
22
|
+
|
|
23
|
+
## レイヤ構造
|
|
24
|
+
|
|
25
|
+
Application
|
|
26
|
+
↓
|
|
27
|
+
ImageStreamGrpcService
|
|
28
|
+
↓
|
|
29
|
+
ImageStreamCtrl
|
|
30
|
+
↓
|
|
31
|
+
Camera SDK
|
|
32
|
+
|
|
33
|
+
ImageStreamCtrl は Camera SDK を抽象化する層です。
|
|
34
|
+
ImageStreamGrpcService は画像配信だけを担当します。
|
|
35
|
+
|
|
36
|
+
## 開発フロー
|
|
37
|
+
|
|
38
|
+
1. ImageStreamCtrl を OpenCV で動かす
|
|
39
|
+
2. SDK に置き換える
|
|
40
|
+
3. run_image_server.py を起動
|
|
41
|
+
4. Viewer で確認
|
|
42
|
+
5. DeviceProxy や AI システムへ組み込む
|
|
43
|
+
|
|
44
|
+
## 想定用途
|
|
45
|
+
|
|
46
|
+
- USB Camera
|
|
47
|
+
- Basler
|
|
48
|
+
- IDS
|
|
49
|
+
- HikVision
|
|
50
|
+
- GigE Vision
|
|
51
|
+
- ORiN Camera
|
|
52
|
+
- AI 推論サーバ
|
|
53
|
+
- 外観検査
|
|
54
|
+
- ロボットビジョン
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "image-server-kit"
|
|
7
|
+
|
|
8
|
+
version = "0.0.1"
|
|
9
|
+
|
|
10
|
+
description = "image_server (Template)"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name="Kengo NAKADA", email="kengo.nakada@email.com" }
|
|
13
|
+
]
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
requires-python = ">=3.8"
|
|
16
|
+
dependencies = [
|
|
17
|
+
"xlogger-py",
|
|
18
|
+
#
|
|
19
|
+
"pyserial",
|
|
20
|
+
"nest_asyncio",
|
|
21
|
+
"pydantic",
|
|
22
|
+
"pyyaml",
|
|
23
|
+
"pytest",
|
|
24
|
+
"sphinx",
|
|
25
|
+
"myst-parser",
|
|
26
|
+
"sphinx-autobuild",
|
|
27
|
+
"sphinx-rtd-theme",
|
|
28
|
+
"sphinxcontrib-napoleon",
|
|
29
|
+
"linkify-it-py"
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[tool.pytest.ini_options]
|
|
33
|
+
pythonpath = ["src"]
|
|
34
|
+
|
|
35
|
+
# ここでpytestのiniと同じようにオプションが書ける
|
|
36
|
+
# 例えばテストマーク、フィルタ、カバレッジなども追記可能
|
|
37
|
+
|
|
38
|
+
[tool.black]
|
|
39
|
+
line-length = 88
|
|
40
|
+
|
|
41
|
+
[tool.isort]
|
|
42
|
+
profile = "black"
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
"""OpenCVを使用したローカル画像取得制御。"""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ImageStreamDeviceClass:
|
|
11
|
+
"""gRPCに依存しないOpenCVカメラ制御クラス。"""
|
|
12
|
+
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
camera_id=0,
|
|
16
|
+
interval_sec=0.03,
|
|
17
|
+
width=None,
|
|
18
|
+
height=None,
|
|
19
|
+
fps=None,
|
|
20
|
+
backend=None,
|
|
21
|
+
reconnect_interval_sec=1.0,
|
|
22
|
+
logger=None,
|
|
23
|
+
):
|
|
24
|
+
# type: (int, float, Optional[int], Optional[int], Optional[float], Optional[int], float, Optional[Any]) -> None
|
|
25
|
+
self._logger = logger
|
|
26
|
+
self._camera_id = int(camera_id)
|
|
27
|
+
self._interval_sec = max(0.001, float(interval_sec))
|
|
28
|
+
self._width = self._optional_positive_int(width)
|
|
29
|
+
self._height = self._optional_positive_int(height)
|
|
30
|
+
self._fps = self._optional_positive_float(fps)
|
|
31
|
+
self._backend = backend
|
|
32
|
+
self._reconnect_interval_sec = max(0.1, float(reconnect_interval_sec))
|
|
33
|
+
|
|
34
|
+
self._capture = None # type: Optional[cv2.VideoCapture]
|
|
35
|
+
self._thread = None # type: Optional[threading.Thread]
|
|
36
|
+
self._stop_event = threading.Event()
|
|
37
|
+
self._capture_lock = threading.RLock()
|
|
38
|
+
self._frame_lock = threading.RLock()
|
|
39
|
+
|
|
40
|
+
self._running = False
|
|
41
|
+
self._frame_id = 0
|
|
42
|
+
self._read_error_count = 0
|
|
43
|
+
self._last_error = None # type: Optional[str]
|
|
44
|
+
self._last_frame_time_ns = None # type: Optional[int]
|
|
45
|
+
self._latest_frame = None
|
|
46
|
+
self._started_time_ns = None # type: Optional[int]
|
|
47
|
+
|
|
48
|
+
def connect(self):
|
|
49
|
+
# type: () -> bool
|
|
50
|
+
"""カメラを開き、ローカル画像取得ループを開始する。"""
|
|
51
|
+
with self._capture_lock:
|
|
52
|
+
if self._capture is None or not self._capture.isOpened():
|
|
53
|
+
if not self._open_capture_unlocked():
|
|
54
|
+
return False
|
|
55
|
+
|
|
56
|
+
return self.start_capture()
|
|
57
|
+
|
|
58
|
+
def disconnect(self):
|
|
59
|
+
# type: () -> bool
|
|
60
|
+
"""画像取得ループを停止し、カメラを解放する。"""
|
|
61
|
+
self.stop_capture()
|
|
62
|
+
with self._capture_lock:
|
|
63
|
+
self._release_capture_unlocked()
|
|
64
|
+
self._log("info", "camera disconnected")
|
|
65
|
+
return True
|
|
66
|
+
|
|
67
|
+
def is_connected(self):
|
|
68
|
+
# type: () -> bool
|
|
69
|
+
"""カメラが開かれているかを返す。"""
|
|
70
|
+
with self._capture_lock:
|
|
71
|
+
if self._capture is None:
|
|
72
|
+
return False
|
|
73
|
+
return bool(self._capture.isOpened())
|
|
74
|
+
|
|
75
|
+
def start_capture(self):
|
|
76
|
+
# type: () -> bool
|
|
77
|
+
"""ローカル画像取得スレッドを開始する。"""
|
|
78
|
+
if self._running:
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
with self._capture_lock:
|
|
82
|
+
if self._capture is None or not self._capture.isOpened():
|
|
83
|
+
if not self._open_capture_unlocked():
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
self._stop_event.clear()
|
|
87
|
+
self._running = True
|
|
88
|
+
self._started_time_ns = self._time_ns()
|
|
89
|
+
self._thread = threading.Thread(
|
|
90
|
+
target=self._capture_loop,
|
|
91
|
+
name="ImageStreamDeviceClass",
|
|
92
|
+
)
|
|
93
|
+
self._thread.daemon = True
|
|
94
|
+
self._thread.start()
|
|
95
|
+
self._log("info", "local image capture started")
|
|
96
|
+
return True
|
|
97
|
+
|
|
98
|
+
def stop_capture(self):
|
|
99
|
+
# type: () -> bool
|
|
100
|
+
"""ローカル画像取得スレッドを停止する。"""
|
|
101
|
+
self._stop_event.set()
|
|
102
|
+
thread = self._thread
|
|
103
|
+
if thread is not None and thread.is_alive():
|
|
104
|
+
if thread is not threading.current_thread():
|
|
105
|
+
thread.join(3.0)
|
|
106
|
+
self._thread = None
|
|
107
|
+
self._running = False
|
|
108
|
+
self._log("info", "local image capture stopped")
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
def read_once(self):
|
|
112
|
+
# type: () -> Any
|
|
113
|
+
"""カメラから画像を1枚同期取得する。"""
|
|
114
|
+
if not self.is_connected():
|
|
115
|
+
with self._capture_lock:
|
|
116
|
+
if not self._open_capture_unlocked():
|
|
117
|
+
raise RuntimeError(str(self._last_error))
|
|
118
|
+
return self._read_frame()
|
|
119
|
+
|
|
120
|
+
def get_latest_frame(self, copy_frame=True):
|
|
121
|
+
# type: (bool) -> Any
|
|
122
|
+
"""取得済みの最新画像を返す。"""
|
|
123
|
+
with self._frame_lock:
|
|
124
|
+
if self._latest_frame is None:
|
|
125
|
+
return None
|
|
126
|
+
if copy_frame:
|
|
127
|
+
return self._latest_frame.copy()
|
|
128
|
+
return self._latest_frame
|
|
129
|
+
|
|
130
|
+
def get_status(self):
|
|
131
|
+
# type: () -> Dict[str, Any]
|
|
132
|
+
"""ローカル画像取得状態を返す。"""
|
|
133
|
+
actual_width = None
|
|
134
|
+
actual_height = None
|
|
135
|
+
actual_fps = None
|
|
136
|
+
|
|
137
|
+
with self._capture_lock:
|
|
138
|
+
if self._capture is not None and self._capture.isOpened():
|
|
139
|
+
actual_width = int(self._capture.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
140
|
+
actual_height = int(self._capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
|
141
|
+
actual_fps = float(self._capture.get(cv2.CAP_PROP_FPS))
|
|
142
|
+
|
|
143
|
+
uptime_sec = 0.0
|
|
144
|
+
if self._started_time_ns is not None:
|
|
145
|
+
uptime_sec = (
|
|
146
|
+
self._time_ns() - self._started_time_ns
|
|
147
|
+
) / 1000000000.0
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
"running": self._running,
|
|
151
|
+
"camera_id": self._camera_id,
|
|
152
|
+
"capture_opened": self.is_connected(),
|
|
153
|
+
"interval_sec": self._interval_sec,
|
|
154
|
+
"requested_width": self._width,
|
|
155
|
+
"requested_height": self._height,
|
|
156
|
+
"requested_fps": self._fps,
|
|
157
|
+
"actual_width": actual_width,
|
|
158
|
+
"actual_height": actual_height,
|
|
159
|
+
"actual_fps": actual_fps,
|
|
160
|
+
"frame_id": self._frame_id,
|
|
161
|
+
"read_error_count": self._read_error_count,
|
|
162
|
+
"last_frame_time_ns": self._last_frame_time_ns,
|
|
163
|
+
"uptime_sec": uptime_sec,
|
|
164
|
+
"last_error": self._last_error,
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
def get_config(self):
|
|
168
|
+
# type: () -> Dict[str, Any]
|
|
169
|
+
"""ローカルカメラ設定を返す。"""
|
|
170
|
+
return {
|
|
171
|
+
"camera_id": self._camera_id,
|
|
172
|
+
"interval_sec": self._interval_sec,
|
|
173
|
+
"width": self._width,
|
|
174
|
+
"height": self._height,
|
|
175
|
+
"fps": self._fps,
|
|
176
|
+
"backend": self._backend,
|
|
177
|
+
"reconnect_interval_sec": self._reconnect_interval_sec,
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
def set_camera_config(self, width=None, height=None, fps=None):
|
|
181
|
+
# type: (Optional[int], Optional[int], Optional[float]) -> Dict[str, Any]
|
|
182
|
+
"""解像度およびFPSの要求値を更新する。"""
|
|
183
|
+
self._width = self._optional_positive_int(width)
|
|
184
|
+
self._height = self._optional_positive_int(height)
|
|
185
|
+
self._fps = self._optional_positive_float(fps)
|
|
186
|
+
|
|
187
|
+
with self._capture_lock:
|
|
188
|
+
if self._capture is not None and self._capture.isOpened():
|
|
189
|
+
self._apply_capture_settings_unlocked()
|
|
190
|
+
|
|
191
|
+
return self.get_status()
|
|
192
|
+
|
|
193
|
+
def set_camera_id(self, camera_id):
|
|
194
|
+
# type: (int) -> bool
|
|
195
|
+
"""カメラIDを変更して再接続する。"""
|
|
196
|
+
self.stop_capture()
|
|
197
|
+
with self._capture_lock:
|
|
198
|
+
self._release_capture_unlocked()
|
|
199
|
+
self._camera_id = int(camera_id)
|
|
200
|
+
return self.connect()
|
|
201
|
+
|
|
202
|
+
def clear_error(self):
|
|
203
|
+
# type: () -> bool
|
|
204
|
+
"""直近のエラー文字列を消去する。"""
|
|
205
|
+
self._last_error = None
|
|
206
|
+
return True
|
|
207
|
+
|
|
208
|
+
def _capture_loop(self):
|
|
209
|
+
# type: () -> None
|
|
210
|
+
next_time = time.monotonic()
|
|
211
|
+
|
|
212
|
+
try:
|
|
213
|
+
while not self._stop_event.is_set():
|
|
214
|
+
try:
|
|
215
|
+
self._read_frame()
|
|
216
|
+
except Exception as exc:
|
|
217
|
+
self._set_error(str(exc))
|
|
218
|
+
self._stop_event.wait(self._reconnect_interval_sec)
|
|
219
|
+
with self._capture_lock:
|
|
220
|
+
self._open_capture_unlocked()
|
|
221
|
+
|
|
222
|
+
next_time += self._interval_sec
|
|
223
|
+
delay = next_time - time.monotonic()
|
|
224
|
+
if delay > 0.0:
|
|
225
|
+
self._stop_event.wait(delay)
|
|
226
|
+
else:
|
|
227
|
+
next_time = time.monotonic()
|
|
228
|
+
finally:
|
|
229
|
+
self._running = False
|
|
230
|
+
|
|
231
|
+
def _read_frame(self):
|
|
232
|
+
# type: () -> Any
|
|
233
|
+
with self._capture_lock:
|
|
234
|
+
if self._capture is None or not self._capture.isOpened():
|
|
235
|
+
raise RuntimeError("Camera is not connected.")
|
|
236
|
+
ok, frame = self._capture.read()
|
|
237
|
+
|
|
238
|
+
if not ok or frame is None:
|
|
239
|
+
self._read_error_count += 1
|
|
240
|
+
with self._capture_lock:
|
|
241
|
+
self._release_capture_unlocked()
|
|
242
|
+
raise RuntimeError("Failed to read frame.")
|
|
243
|
+
|
|
244
|
+
with self._frame_lock:
|
|
245
|
+
self._latest_frame = frame.copy()
|
|
246
|
+
self._frame_id += 1
|
|
247
|
+
self._last_frame_time_ns = self._time_ns()
|
|
248
|
+
|
|
249
|
+
self._last_error = None
|
|
250
|
+
return frame
|
|
251
|
+
|
|
252
|
+
def _open_capture_unlocked(self):
|
|
253
|
+
# type: () -> bool
|
|
254
|
+
self._release_capture_unlocked()
|
|
255
|
+
|
|
256
|
+
try:
|
|
257
|
+
if self._backend is None:
|
|
258
|
+
capture = cv2.VideoCapture(self._camera_id)
|
|
259
|
+
else:
|
|
260
|
+
capture = cv2.VideoCapture(
|
|
261
|
+
self._camera_id,
|
|
262
|
+
int(self._backend),
|
|
263
|
+
)
|
|
264
|
+
except Exception as exc:
|
|
265
|
+
self._set_error(
|
|
266
|
+
"Failed to create VideoCapture: {}".format(exc)
|
|
267
|
+
)
|
|
268
|
+
return False
|
|
269
|
+
|
|
270
|
+
self._capture = capture
|
|
271
|
+
if not capture.isOpened():
|
|
272
|
+
self._set_error(
|
|
273
|
+
"Failed to open camera: {}".format(self._camera_id)
|
|
274
|
+
)
|
|
275
|
+
self._release_capture_unlocked()
|
|
276
|
+
return False
|
|
277
|
+
|
|
278
|
+
self._apply_capture_settings_unlocked()
|
|
279
|
+
self._last_error = None
|
|
280
|
+
self._log(
|
|
281
|
+
"info",
|
|
282
|
+
"camera connected: camera_id={}".format(self._camera_id),
|
|
283
|
+
)
|
|
284
|
+
return True
|
|
285
|
+
|
|
286
|
+
def _apply_capture_settings_unlocked(self):
|
|
287
|
+
# type: () -> None
|
|
288
|
+
if self._capture is None:
|
|
289
|
+
return
|
|
290
|
+
if self._width is not None:
|
|
291
|
+
self._capture.set(cv2.CAP_PROP_FRAME_WIDTH, self._width)
|
|
292
|
+
if self._height is not None:
|
|
293
|
+
self._capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self._height)
|
|
294
|
+
if self._fps is not None:
|
|
295
|
+
self._capture.set(cv2.CAP_PROP_FPS, self._fps)
|
|
296
|
+
|
|
297
|
+
def _release_capture_unlocked(self):
|
|
298
|
+
# type: () -> None
|
|
299
|
+
if self._capture is not None:
|
|
300
|
+
try:
|
|
301
|
+
self._capture.release()
|
|
302
|
+
except Exception:
|
|
303
|
+
pass
|
|
304
|
+
self._capture = None
|
|
305
|
+
|
|
306
|
+
def _set_error(self, message):
|
|
307
|
+
# type: (str) -> None
|
|
308
|
+
self._last_error = str(message)
|
|
309
|
+
self._log("error", self._last_error)
|
|
310
|
+
|
|
311
|
+
def _log(self, level, message):
|
|
312
|
+
# type: (str, str) -> None
|
|
313
|
+
if self._logger is None:
|
|
314
|
+
return
|
|
315
|
+
method = getattr(self._logger, level, None)
|
|
316
|
+
if callable(method):
|
|
317
|
+
method(message)
|
|
318
|
+
|
|
319
|
+
@staticmethod
|
|
320
|
+
def _optional_positive_int(value):
|
|
321
|
+
# type: (Optional[int]) -> Optional[int]
|
|
322
|
+
if value is None:
|
|
323
|
+
return None
|
|
324
|
+
converted = int(value)
|
|
325
|
+
if converted <= 0:
|
|
326
|
+
raise ValueError("value must be greater than zero.")
|
|
327
|
+
return converted
|
|
328
|
+
|
|
329
|
+
@staticmethod
|
|
330
|
+
def _optional_positive_float(value):
|
|
331
|
+
# type: (Optional[float]) -> Optional[float]
|
|
332
|
+
if value is None:
|
|
333
|
+
return None
|
|
334
|
+
converted = float(value)
|
|
335
|
+
if converted <= 0.0:
|
|
336
|
+
raise ValueError("value must be greater than zero.")
|
|
337
|
+
return converted
|
|
338
|
+
|
|
339
|
+
@staticmethod
|
|
340
|
+
def _time_ns():
|
|
341
|
+
# type: () -> int
|
|
342
|
+
return int(time.time() * 1000000000)
|
|
343
|
+
|
|
344
|
+
CAMERA_ID = 0
|
|
345
|
+
CAPTURE_INTERVAL_SEC = 0.03
|
|
346
|
+
CAMERA_WIDTH = None
|
|
347
|
+
CAMERA_HEIGHT = None
|
|
348
|
+
CAMERA_FPS = None
|
|
349
|
+
WINDOW_NAME = "ImageStreamDeviceClass"
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def main():
|
|
353
|
+
"""ローカルカメラへ接続し、取得画像をOpenCVウィンドウへ表示する。"""
|
|
354
|
+
image_stream = ImageStreamDeviceClass(
|
|
355
|
+
camera_id=CAMERA_ID,
|
|
356
|
+
interval_sec=CAPTURE_INTERVAL_SEC,
|
|
357
|
+
width=CAMERA_WIDTH,
|
|
358
|
+
height=CAMERA_HEIGHT,
|
|
359
|
+
fps=CAMERA_FPS,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
if not image_stream.connect():
|
|
363
|
+
raise RuntimeError(str(image_stream.get_status()))
|
|
364
|
+
|
|
365
|
+
try:
|
|
366
|
+
while True:
|
|
367
|
+
frame = image_stream.get_latest_frame()
|
|
368
|
+
if frame is None:
|
|
369
|
+
time.sleep(0.01)
|
|
370
|
+
continue
|
|
371
|
+
|
|
372
|
+
cv2.imshow(WINDOW_NAME, frame)
|
|
373
|
+
key = cv2.waitKey(1) & 0xFF
|
|
374
|
+
if key == 27 or key == ord("q"):
|
|
375
|
+
break
|
|
376
|
+
finally:
|
|
377
|
+
image_stream.disconnect()
|
|
378
|
+
cv2.destroyAllWindows()
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
if __name__ == "__main__":
|
|
382
|
+
main()
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""grpc_frame用同期画像クライアント。"""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, Iterator, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
import cv2
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from grpc_frame.grpc_client import SyncGrpcClient
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ImageStreamClient(SyncGrpcClient):
|
|
12
|
+
"""ImageStreamGrpcService用同期クライアント。"""
|
|
13
|
+
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
server_ip,
|
|
17
|
+
server_port,
|
|
18
|
+
timeout_sec=None,
|
|
19
|
+
logger=None,
|
|
20
|
+
max_message_mb=64,
|
|
21
|
+
):
|
|
22
|
+
# type: (str, int, Optional[float], Optional[Any], int) -> None
|
|
23
|
+
kwargs = {
|
|
24
|
+
"server_ip": server_ip,
|
|
25
|
+
"server_port": server_port,
|
|
26
|
+
"timeout_sec": timeout_sec,
|
|
27
|
+
"logger": logger,
|
|
28
|
+
}
|
|
29
|
+
try:
|
|
30
|
+
SyncGrpcClient.__init__(
|
|
31
|
+
self,
|
|
32
|
+
max_message_mb=max_message_mb,
|
|
33
|
+
**kwargs
|
|
34
|
+
)
|
|
35
|
+
except TypeError:
|
|
36
|
+
SyncGrpcClient.__init__(self, **kwargs)
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def decode_payload(payload):
|
|
40
|
+
# type: (Dict[str, Any]) -> Any
|
|
41
|
+
image_bytes = payload.get("image")
|
|
42
|
+
if not isinstance(
|
|
43
|
+
image_bytes,
|
|
44
|
+
(bytes, bytearray, memoryview),
|
|
45
|
+
):
|
|
46
|
+
raise ValueError(
|
|
47
|
+
"payload does not contain JPEG bytes."
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
image_array = np.frombuffer(
|
|
51
|
+
image_bytes,
|
|
52
|
+
dtype=np.uint8,
|
|
53
|
+
)
|
|
54
|
+
frame = cv2.imdecode(
|
|
55
|
+
image_array,
|
|
56
|
+
cv2.IMREAD_COLOR,
|
|
57
|
+
)
|
|
58
|
+
if frame is None:
|
|
59
|
+
raise ValueError("Failed to decode JPEG payload.")
|
|
60
|
+
return frame
|
|
61
|
+
|
|
62
|
+
def iter_frames(self, topic="camera.frame"):
|
|
63
|
+
# type: (str) -> Iterator[Tuple[Dict[str, Any], Any]]
|
|
64
|
+
for payload in self.subscribe(topic=topic):
|
|
65
|
+
try:
|
|
66
|
+
frame = self.decode_payload(payload)
|
|
67
|
+
except ValueError:
|
|
68
|
+
continue
|
|
69
|
+
yield payload, frame
|
|
70
|
+
|
|
71
|
+
def show_camera_frame_stream(
|
|
72
|
+
self,
|
|
73
|
+
topic="camera.frame",
|
|
74
|
+
window_name="camera.frame",
|
|
75
|
+
):
|
|
76
|
+
# type: (str, str) -> None
|
|
77
|
+
self.start_stream()
|
|
78
|
+
try:
|
|
79
|
+
for _payload, frame in self.iter_frames(topic=topic):
|
|
80
|
+
cv2.imshow(window_name, frame)
|
|
81
|
+
key = cv2.waitKey(1) & 0xFF
|
|
82
|
+
if key == 27 or key == ord("q"):
|
|
83
|
+
break
|
|
84
|
+
finally:
|
|
85
|
+
try:
|
|
86
|
+
self.stop_stream()
|
|
87
|
+
finally:
|
|
88
|
+
cv2.destroyAllWindows()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from typing import Any, Optional, Union, Dict, List, Tuple, Callable, Sequence
|
|
2
|
+
|
|
3
|
+
class ImageStreamClient:
|
|
4
|
+
def __init__(self, server_ip: Any, server_port: Any, timeout_sec: Any = ..., logger: Any = ..., max_message_mb: Any = ...) -> None: ...
|
|
5
|
+
def decode_payload(self, payload: Any) -> Any: ...
|
|
6
|
+
def iter_frames(self, topic: Any = ...) -> Any: ...
|
|
7
|
+
def show_camera_frame_stream(self, topic: Any = ..., window_name: Any = ...) -> Any: ...
|
|
8
|
+
def connect(self) -> Any: ...
|
|
9
|
+
def disconnect(self) -> Any: ...
|
|
10
|
+
def is_connected(self) -> Any: ...
|
|
11
|
+
def start_stream(self) -> Any: ...
|
|
12
|
+
def stop_stream(self) -> Any: ...
|
|
13
|
+
def capture_once(self) -> Any: ...
|
|
14
|
+
def publish_once(self) -> Any: ...
|
|
15
|
+
def save_snapshot(self, file_path: Any) -> Any: ...
|
|
16
|
+
def get_status(self) -> Any: ...
|
|
17
|
+
def get_config(self) -> Any: ...
|
|
18
|
+
def set_stream_config(self, interval_sec: Any = ..., jpeg_quality: Any = ..., topic_name: Any = ...) -> Any: ...
|
|
19
|
+
def set_camera_config(self, width: Any = ..., height: Any = ..., fps: Any = ...) -> Any: ...
|
|
20
|
+
def set_camera_id(self, camera_id: Any) -> Any: ...
|
|
21
|
+
def clear_error(self) -> Any: ...
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""ImageStreamDeviceClassをgrpc_frameへ公開するサービス層。"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Dict, Optional
|
|
7
|
+
|
|
8
|
+
import cv2
|
|
9
|
+
|
|
10
|
+
from image_server.image_stream_ctrl import ImageStreamDeviceClass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ImageStreamGrpcService:
|
|
14
|
+
"""ローカル画像制御をgRPC公開およびEventBus配信へ接続する。"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
image_stream=None,
|
|
19
|
+
topic_name="camera.frame",
|
|
20
|
+
publish_interval_sec=0.1,
|
|
21
|
+
jpeg_quality=85,
|
|
22
|
+
logger=None,
|
|
23
|
+
):
|
|
24
|
+
# type: (Optional[ImageStreamDeviceClass], str, float, int, Optional[Any]) -> None
|
|
25
|
+
self._logger = logger
|
|
26
|
+
self._image_stream = image_stream
|
|
27
|
+
if self._image_stream is None:
|
|
28
|
+
self._image_stream = ImageStreamDeviceClass(logger=logger)
|
|
29
|
+
|
|
30
|
+
self._topic_name = str(topic_name)
|
|
31
|
+
self._publish_interval_sec = max(
|
|
32
|
+
0.001,
|
|
33
|
+
float(publish_interval_sec),
|
|
34
|
+
)
|
|
35
|
+
self._jpeg_quality = self._validate_jpeg_quality(jpeg_quality)
|
|
36
|
+
self._event_bus = None
|
|
37
|
+
self._thread = None # type: Optional[threading.Thread]
|
|
38
|
+
self._stop_event = threading.Event()
|
|
39
|
+
self._running = False
|
|
40
|
+
self._published_count = 0
|
|
41
|
+
self._encode_error_count = 0
|
|
42
|
+
self._last_publish_time_ns = None # type: Optional[int]
|
|
43
|
+
self._last_error = None # type: Optional[str]
|
|
44
|
+
|
|
45
|
+
def _set_event_bus(self, event_bus):
|
|
46
|
+
# type: (Any) -> None
|
|
47
|
+
"""grpc_frameからEventBusを設定する。"""
|
|
48
|
+
self._event_bus = event_bus
|
|
49
|
+
|
|
50
|
+
def connect(self):
|
|
51
|
+
# type: () -> bool
|
|
52
|
+
"""ローカル画像取得デバイスへ接続する。"""
|
|
53
|
+
return self._image_stream.connect()
|
|
54
|
+
|
|
55
|
+
def disconnect(self):
|
|
56
|
+
# type: () -> bool
|
|
57
|
+
"""配信を停止し、ローカル画像取得デバイスを切断する。"""
|
|
58
|
+
self.stop_stream()
|
|
59
|
+
return self._image_stream.disconnect()
|
|
60
|
+
|
|
61
|
+
def is_connected(self):
|
|
62
|
+
# type: () -> bool
|
|
63
|
+
return self._image_stream.is_connected()
|
|
64
|
+
|
|
65
|
+
def start_stream(self):
|
|
66
|
+
# type: () -> bool
|
|
67
|
+
"""EventBusへのJPEG画像配信を開始する。"""
|
|
68
|
+
if self._event_bus is None:
|
|
69
|
+
raise RuntimeError("EventBus is not set.")
|
|
70
|
+
if not self._image_stream.connect():
|
|
71
|
+
return False
|
|
72
|
+
if self._running:
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
self._stop_event.clear()
|
|
76
|
+
self._running = True
|
|
77
|
+
self._thread = threading.Thread(
|
|
78
|
+
target=self._publish_loop,
|
|
79
|
+
name="ImageStreamGrpcService",
|
|
80
|
+
)
|
|
81
|
+
self._thread.daemon = True
|
|
82
|
+
self._thread.start()
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
def stop_stream(self):
|
|
86
|
+
# type: () -> bool
|
|
87
|
+
"""EventBusへの画像配信を停止する。"""
|
|
88
|
+
self._stop_event.set()
|
|
89
|
+
thread = self._thread
|
|
90
|
+
if thread is not None and thread.is_alive():
|
|
91
|
+
if thread is not threading.current_thread():
|
|
92
|
+
thread.join(3.0)
|
|
93
|
+
self._thread = None
|
|
94
|
+
self._running = False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
def capture_once(self):
|
|
98
|
+
# type: () -> Dict[str, Any]
|
|
99
|
+
"""最新画像をJPEGペイロードとして返す。"""
|
|
100
|
+
frame = self._image_stream.get_latest_frame()
|
|
101
|
+
if frame is None:
|
|
102
|
+
frame = self._image_stream.read_once()
|
|
103
|
+
return self._encode_frame(frame)
|
|
104
|
+
|
|
105
|
+
def publish_once(self):
|
|
106
|
+
# type: () -> bool
|
|
107
|
+
"""最新画像をEventBusへ1回配信する。"""
|
|
108
|
+
if self._event_bus is None:
|
|
109
|
+
raise RuntimeError("EventBus is not set.")
|
|
110
|
+
|
|
111
|
+
payload = self.capture_once()
|
|
112
|
+
self._event_bus.publish(
|
|
113
|
+
self._topic_name,
|
|
114
|
+
payload,
|
|
115
|
+
source="image_stream_grpc_service",
|
|
116
|
+
)
|
|
117
|
+
self._published_count += 1
|
|
118
|
+
self._last_publish_time_ns = self._time_ns()
|
|
119
|
+
return True
|
|
120
|
+
|
|
121
|
+
def save_snapshot(self, file_path):
|
|
122
|
+
# type: (str) -> Dict[str, Any]
|
|
123
|
+
"""サーバー側ファイルへ最新画像を保存する。"""
|
|
124
|
+
if not file_path:
|
|
125
|
+
raise ValueError("file_path is required.")
|
|
126
|
+
|
|
127
|
+
frame = self._image_stream.get_latest_frame()
|
|
128
|
+
if frame is None:
|
|
129
|
+
frame = self._image_stream.read_once()
|
|
130
|
+
|
|
131
|
+
directory = os.path.dirname(os.path.abspath(file_path))
|
|
132
|
+
if directory and not os.path.isdir(directory):
|
|
133
|
+
os.makedirs(directory)
|
|
134
|
+
|
|
135
|
+
if not cv2.imwrite(file_path, frame):
|
|
136
|
+
raise RuntimeError(
|
|
137
|
+
"Failed to save snapshot: {}".format(file_path)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"file_path": os.path.abspath(file_path),
|
|
142
|
+
"width": int(frame.shape[1]),
|
|
143
|
+
"height": int(frame.shape[0]),
|
|
144
|
+
"timestamp_ns": self._time_ns(),
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
def get_status(self):
|
|
148
|
+
# type: () -> Dict[str, Any]
|
|
149
|
+
"""ローカル取得状態とgRPC配信状態を統合して返す。"""
|
|
150
|
+
status = self._image_stream.get_status()
|
|
151
|
+
status.update(
|
|
152
|
+
{
|
|
153
|
+
"stream_running": self._running,
|
|
154
|
+
"topic_name": self._topic_name,
|
|
155
|
+
"publish_interval_sec": self._publish_interval_sec,
|
|
156
|
+
"jpeg_quality": self._jpeg_quality,
|
|
157
|
+
"published_count": self._published_count,
|
|
158
|
+
"encode_error_count": self._encode_error_count,
|
|
159
|
+
"last_publish_time_ns": self._last_publish_time_ns,
|
|
160
|
+
"grpc_last_error": self._last_error,
|
|
161
|
+
}
|
|
162
|
+
)
|
|
163
|
+
return status
|
|
164
|
+
|
|
165
|
+
def get_config(self):
|
|
166
|
+
# type: () -> Dict[str, Any]
|
|
167
|
+
"""ローカル設定と配信設定を返す。"""
|
|
168
|
+
return {
|
|
169
|
+
"camera": self._image_stream.get_config(),
|
|
170
|
+
"stream": {
|
|
171
|
+
"topic_name": self._topic_name,
|
|
172
|
+
"publish_interval_sec": self._publish_interval_sec,
|
|
173
|
+
"jpeg_quality": self._jpeg_quality,
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
def set_stream_config(
|
|
178
|
+
self,
|
|
179
|
+
interval_sec=None,
|
|
180
|
+
jpeg_quality=None,
|
|
181
|
+
topic_name=None,
|
|
182
|
+
):
|
|
183
|
+
# type: (Optional[float], Optional[int], Optional[str]) -> Dict[str, Any]
|
|
184
|
+
"""gRPC配信設定を変更する。"""
|
|
185
|
+
if interval_sec is not None:
|
|
186
|
+
self._publish_interval_sec = max(
|
|
187
|
+
0.001,
|
|
188
|
+
float(interval_sec),
|
|
189
|
+
)
|
|
190
|
+
if jpeg_quality is not None:
|
|
191
|
+
self._jpeg_quality = self._validate_jpeg_quality(
|
|
192
|
+
jpeg_quality
|
|
193
|
+
)
|
|
194
|
+
if topic_name is not None:
|
|
195
|
+
if not str(topic_name).strip():
|
|
196
|
+
raise ValueError("topic_name must not be empty.")
|
|
197
|
+
self._topic_name = str(topic_name)
|
|
198
|
+
return self.get_config()
|
|
199
|
+
|
|
200
|
+
def set_camera_config(self, width=None, height=None, fps=None):
|
|
201
|
+
# type: (Optional[int], Optional[int], Optional[float]) -> Dict[str, Any]
|
|
202
|
+
return self._image_stream.set_camera_config(
|
|
203
|
+
width,
|
|
204
|
+
height,
|
|
205
|
+
fps,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
def set_camera_id(self, camera_id):
|
|
209
|
+
# type: (int) -> bool
|
|
210
|
+
return self._image_stream.set_camera_id(camera_id)
|
|
211
|
+
|
|
212
|
+
def clear_error(self):
|
|
213
|
+
# type: () -> bool
|
|
214
|
+
self._last_error = None
|
|
215
|
+
self._image_stream.clear_error()
|
|
216
|
+
return True
|
|
217
|
+
|
|
218
|
+
def _publish_loop(self):
|
|
219
|
+
# type: () -> None
|
|
220
|
+
next_time = time.monotonic()
|
|
221
|
+
|
|
222
|
+
try:
|
|
223
|
+
while not self._stop_event.is_set():
|
|
224
|
+
try:
|
|
225
|
+
self.publish_once()
|
|
226
|
+
self._last_error = None
|
|
227
|
+
except Exception as exc:
|
|
228
|
+
self._last_error = str(exc)
|
|
229
|
+
|
|
230
|
+
next_time += self._publish_interval_sec
|
|
231
|
+
delay = next_time - time.monotonic()
|
|
232
|
+
if delay > 0.0:
|
|
233
|
+
self._stop_event.wait(delay)
|
|
234
|
+
else:
|
|
235
|
+
next_time = time.monotonic()
|
|
236
|
+
finally:
|
|
237
|
+
self._running = False
|
|
238
|
+
|
|
239
|
+
def _encode_frame(self, frame):
|
|
240
|
+
# type: (Any) -> Dict[str, Any]
|
|
241
|
+
params = [
|
|
242
|
+
int(cv2.IMWRITE_JPEG_QUALITY),
|
|
243
|
+
self._jpeg_quality,
|
|
244
|
+
]
|
|
245
|
+
ok, encoded = cv2.imencode(".jpg", frame, params)
|
|
246
|
+
if not ok:
|
|
247
|
+
self._encode_error_count += 1
|
|
248
|
+
raise RuntimeError("Failed to encode frame.")
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
"frame_id": self._image_stream.get_status().get("frame_id"),
|
|
252
|
+
"timestamp_ns": self._time_ns(),
|
|
253
|
+
"encoding": "jpg",
|
|
254
|
+
"width": int(frame.shape[1]),
|
|
255
|
+
"height": int(frame.shape[0]),
|
|
256
|
+
"image": encoded.tobytes(),
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
@staticmethod
|
|
260
|
+
def _validate_jpeg_quality(value):
|
|
261
|
+
# type: (int) -> int
|
|
262
|
+
quality = int(value)
|
|
263
|
+
if quality < 1 or quality > 100:
|
|
264
|
+
raise ValueError(
|
|
265
|
+
"jpeg_quality must be between 1 and 100."
|
|
266
|
+
)
|
|
267
|
+
return quality
|
|
268
|
+
|
|
269
|
+
@staticmethod
|
|
270
|
+
def _time_ns():
|
|
271
|
+
# type: () -> int
|
|
272
|
+
return int(time.time() * 1000000000)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
|
|
4
|
+
"""ImageStreamClientの型スタブを生成する。"""
|
|
5
|
+
|
|
6
|
+
import inspect
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from grpc_frame.grpc_client import SyncGrpcClient
|
|
10
|
+
from grpc_frame.make_pyi import generate_client_pyi
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
CLIENT_CLASS_NAME = "ImageStreamClient"
|
|
14
|
+
CTRL_CLASS_NAME = "ImageStreamGrpcService"
|
|
15
|
+
BASE_CLASS_NAME = "SyncGrpcClient"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main():
|
|
19
|
+
"""grpc_frameのgenerate_client_pyi()でclient.pyiを生成する。"""
|
|
20
|
+
current_dir = Path(__file__).resolve().parent
|
|
21
|
+
grpc_client_file = Path(inspect.getfile(SyncGrpcClient)).resolve()
|
|
22
|
+
|
|
23
|
+
generate_client_pyi(
|
|
24
|
+
client_py=current_dir / "client.py",
|
|
25
|
+
client_class=CLIENT_CLASS_NAME,
|
|
26
|
+
ctrl_py=current_dir / "image_stream_grpc_service.py",
|
|
27
|
+
ctrl_class=CTRL_CLASS_NAME,
|
|
28
|
+
base_py=grpc_client_file,
|
|
29
|
+
base_class=BASE_CLASS_NAME,
|
|
30
|
+
out_path=current_dir / "client.pyi",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
print("generated: {}".format(current_dir / "client.pyi"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
main()
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: image-server-kit
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: image_server (Template)
|
|
5
|
+
Author-email: Kengo NAKADA <kengo.nakada@email.com>
|
|
6
|
+
Requires-Python: >=3.8
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: xlogger-py
|
|
10
|
+
Requires-Dist: pyserial
|
|
11
|
+
Requires-Dist: nest_asyncio
|
|
12
|
+
Requires-Dist: pydantic
|
|
13
|
+
Requires-Dist: pyyaml
|
|
14
|
+
Requires-Dist: pytest
|
|
15
|
+
Requires-Dist: sphinx
|
|
16
|
+
Requires-Dist: myst-parser
|
|
17
|
+
Requires-Dist: sphinx-autobuild
|
|
18
|
+
Requires-Dist: sphinx-rtd-theme
|
|
19
|
+
Requires-Dist: sphinxcontrib-napoleon
|
|
20
|
+
Requires-Dist: linkify-it-py
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# image_server
|
|
24
|
+
|
|
25
|
+
image_server は「USBカメラを扱うライブラリ」ではありません。
|
|
26
|
+
|
|
27
|
+
本ライブラリは **画像転送機能を既存プログラムへ組み込むためのテンプレート** です。
|
|
28
|
+
OpenCV・gRPC・Viewer を毎回実装するのではなく、画像取得部分だけを書き換えることで
|
|
29
|
+
画像転送システムを短時間で構築できることを目的としています。
|
|
30
|
+
|
|
31
|
+
## このライブラリが解決する問題
|
|
32
|
+
|
|
33
|
+
通常は次のような処理を毎回実装する必要があります。
|
|
34
|
+
|
|
35
|
+
- カメラ接続
|
|
36
|
+
- フレーム取得
|
|
37
|
+
- JPEG圧縮
|
|
38
|
+
- 通信
|
|
39
|
+
- Viewer
|
|
40
|
+
- 接続管理
|
|
41
|
+
- スレッド管理
|
|
42
|
+
|
|
43
|
+
image_server はこれらを共通化し、利用者は **画像取得部だけ** を実装します。
|
|
44
|
+
|
|
45
|
+
## レイヤ構造
|
|
46
|
+
|
|
47
|
+
Application
|
|
48
|
+
↓
|
|
49
|
+
ImageStreamGrpcService
|
|
50
|
+
↓
|
|
51
|
+
ImageStreamCtrl
|
|
52
|
+
↓
|
|
53
|
+
Camera SDK
|
|
54
|
+
|
|
55
|
+
ImageStreamCtrl は Camera SDK を抽象化する層です。
|
|
56
|
+
ImageStreamGrpcService は画像配信だけを担当します。
|
|
57
|
+
|
|
58
|
+
## 開発フロー
|
|
59
|
+
|
|
60
|
+
1. ImageStreamCtrl を OpenCV で動かす
|
|
61
|
+
2. SDK に置き換える
|
|
62
|
+
3. run_image_server.py を起動
|
|
63
|
+
4. Viewer で確認
|
|
64
|
+
5. DeviceProxy や AI システムへ組み込む
|
|
65
|
+
|
|
66
|
+
## 想定用途
|
|
67
|
+
|
|
68
|
+
- USB Camera
|
|
69
|
+
- Basler
|
|
70
|
+
- IDS
|
|
71
|
+
- HikVision
|
|
72
|
+
- GigE Vision
|
|
73
|
+
- ORiN Camera
|
|
74
|
+
- AI 推論サーバ
|
|
75
|
+
- 外観検査
|
|
76
|
+
- ロボットビジョン
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/image_server/__init__.py
|
|
5
|
+
src/image_server/image_stream_ctrl.py
|
|
6
|
+
src/image_server/server_grpc/__init__.py
|
|
7
|
+
src/image_server/server_grpc/client.py
|
|
8
|
+
src/image_server/server_grpc/client.pyi
|
|
9
|
+
src/image_server/server_grpc/image_stream_grpc_service.py
|
|
10
|
+
src/image_server/server_grpc/make_pyi.py
|
|
11
|
+
src/image_server_kit.egg-info/PKG-INFO
|
|
12
|
+
src/image_server_kit.egg-info/SOURCES.txt
|
|
13
|
+
src/image_server_kit.egg-info/dependency_links.txt
|
|
14
|
+
src/image_server_kit.egg-info/requires.txt
|
|
15
|
+
src/image_server_kit.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
image_server
|