cogmatplot 0.1.0__py3-none-any.whl
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.
- cogmatplot/__init__.py +46 -0
- cogmatplot/api.py +43 -0
- cogmatplot/client.py +151 -0
- cogmatplot/debug_views.py +222 -0
- cogmatplot/images.py +54 -0
- cogmatplot/layout.py +88 -0
- cogmatplot/matplot.py +967 -0
- cogmatplot/mode.py +77 -0
- cogmatplot/place.py +65 -0
- cogmatplot/ply.py +325 -0
- cogmatplot/server.py +124 -0
- cogmatplot/view3.py +353 -0
- cogmatplot/wire.py +93 -0
- cogmatplot-0.1.0.dist-info/METADATA +217 -0
- cogmatplot-0.1.0.dist-info/RECORD +19 -0
- cogmatplot-0.1.0.dist-info/WHEEL +5 -0
- cogmatplot-0.1.0.dist-info/entry_points.txt +2 -0
- cogmatplot-0.1.0.dist-info/licenses/LICENSE +21 -0
- cogmatplot-0.1.0.dist-info/top_level.txt +1 -0
cogmatplot/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""MATLAB-style figures for notebooks, pop-out monitors, and a debug server.
|
|
2
|
+
|
|
3
|
+
Pick the display before importing the plotting classes when you can::
|
|
4
|
+
|
|
5
|
+
import cogmatplot
|
|
6
|
+
cogmatplot.use("inline") # static figures in the interactive viewer
|
|
7
|
+
cogmatplot.use("qt") # interactive windows on a monitor
|
|
8
|
+
|
|
9
|
+
``FigureManager`` is loaded lazily so ``use`` can select the backend first.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from cogmatplot.mode import current_mode, use
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"use",
|
|
16
|
+
"current_mode",
|
|
17
|
+
"FigureManager",
|
|
18
|
+
"closeAll",
|
|
19
|
+
"drawnow",
|
|
20
|
+
"Fig3d",
|
|
21
|
+
"PlotClient",
|
|
22
|
+
"Ply",
|
|
23
|
+
"load_ply",
|
|
24
|
+
"save_ply",
|
|
25
|
+
"rectangular_prism",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def __getattr__(name):
|
|
30
|
+
if name in ("FigureManager", "closeAll", "drawnow"):
|
|
31
|
+
from cogmatplot import matplot
|
|
32
|
+
|
|
33
|
+
return getattr(matplot, name)
|
|
34
|
+
if name == "Fig3d":
|
|
35
|
+
from cogmatplot.view3 import Fig3d
|
|
36
|
+
|
|
37
|
+
return Fig3d
|
|
38
|
+
if name == "PlotClient":
|
|
39
|
+
from cogmatplot.client import PlotClient
|
|
40
|
+
|
|
41
|
+
return PlotClient
|
|
42
|
+
if name in ("Ply", "load_ply", "save_ply", "rectangular_prism"):
|
|
43
|
+
from cogmatplot import ply
|
|
44
|
+
|
|
45
|
+
return getattr(ply, name)
|
|
46
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
cogmatplot/api.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Method names shared by FigureManager and the remote client.
|
|
2
|
+
|
|
3
|
+
The server calls ``getattr(figure, method)(*args, **kwargs)``. A new plotting
|
|
4
|
+
helper is added here and on ``FigureManager`` once.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
STREAM_METHODS = ("imshow", "imagesc")
|
|
8
|
+
|
|
9
|
+
METHODS = (
|
|
10
|
+
"imshow",
|
|
11
|
+
"imagesc",
|
|
12
|
+
"plot",
|
|
13
|
+
"plot3",
|
|
14
|
+
"scatter3",
|
|
15
|
+
"plot_mesh",
|
|
16
|
+
"figure3",
|
|
17
|
+
"title",
|
|
18
|
+
"xlabel",
|
|
19
|
+
"ylabel",
|
|
20
|
+
"axis",
|
|
21
|
+
"hold",
|
|
22
|
+
"grid",
|
|
23
|
+
"xlim",
|
|
24
|
+
"ylim",
|
|
25
|
+
"zlim",
|
|
26
|
+
"legend",
|
|
27
|
+
"colorbar",
|
|
28
|
+
"text",
|
|
29
|
+
"box",
|
|
30
|
+
"rectangle",
|
|
31
|
+
"clf",
|
|
32
|
+
"cla",
|
|
33
|
+
"close",
|
|
34
|
+
"closeAll",
|
|
35
|
+
"clfAll",
|
|
36
|
+
"reset",
|
|
37
|
+
"drawnow",
|
|
38
|
+
"pause",
|
|
39
|
+
"interactive",
|
|
40
|
+
"view3",
|
|
41
|
+
"grid3",
|
|
42
|
+
"clear3",
|
|
43
|
+
)
|
cogmatplot/client.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Send FigureManager calls to a cogmatplot server.
|
|
2
|
+
|
|
3
|
+
Method names match the in-process manager. ``figure3`` returns a proxy whose
|
|
4
|
+
``scatter3``, ``view_xy``, and ``show_grid`` calls are forwarded.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
import zmq
|
|
12
|
+
|
|
13
|
+
from cogmatplot.api import METHODS, STREAM_METHODS
|
|
14
|
+
from cogmatplot.wire import encode
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _remote(name):
|
|
18
|
+
def method(self, *args, **kwargs):
|
|
19
|
+
return self._call(name, *args, **kwargs)
|
|
20
|
+
|
|
21
|
+
method.__name__ = name
|
|
22
|
+
method.__doc__ = f"Forward {name} to the figure server."
|
|
23
|
+
return method
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class RemoteCloud:
|
|
27
|
+
"""Stand-in for :class:`cogmatplot.view3.Fig3d` on the client side."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, client, row, col):
|
|
30
|
+
self._client = client
|
|
31
|
+
self.row = row
|
|
32
|
+
self.col = col
|
|
33
|
+
|
|
34
|
+
def scatter3(self, points, color=None, colors=None, point_size=3, cmap=None, hold=True, **kwargs):
|
|
35
|
+
self._client.scatter3(
|
|
36
|
+
self.row, self.col, points,
|
|
37
|
+
color=color, colors=colors, point_size=point_size, cmap=cmap, hold=hold, **kwargs,
|
|
38
|
+
)
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
def view(self, which="xy"):
|
|
42
|
+
self._client.view3(self.row, self.col, which)
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def view_xy(self):
|
|
46
|
+
return self.view("xy")
|
|
47
|
+
|
|
48
|
+
def view_xz(self):
|
|
49
|
+
return self.view("xz")
|
|
50
|
+
|
|
51
|
+
def view_yz(self):
|
|
52
|
+
return self.view("yz")
|
|
53
|
+
|
|
54
|
+
def view_isometric(self):
|
|
55
|
+
return self.view("iso")
|
|
56
|
+
|
|
57
|
+
def grid(self, on=True):
|
|
58
|
+
self._client.grid3(self.row, self.col, on)
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def show_grid(self):
|
|
62
|
+
return self.grid(True)
|
|
63
|
+
|
|
64
|
+
def clear(self):
|
|
65
|
+
self._client.clear3(self.row, self.col)
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
def plot_mesh(self, points, faces, color=None, colors=None, style="surface", hold=True, **kwargs):
|
|
69
|
+
self._client.plot_mesh(
|
|
70
|
+
self.row, self.col, points, faces,
|
|
71
|
+
color=color, colors=colors, style=style, hold=hold, **kwargs,
|
|
72
|
+
)
|
|
73
|
+
return self
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class PlotClient:
|
|
77
|
+
"""Debugger-side handle. Construct with ``FigureManager.connect`` too."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, host="localhost", port=5555):
|
|
80
|
+
self.host = host
|
|
81
|
+
self.port = int(port)
|
|
82
|
+
self._context = zmq.Context()
|
|
83
|
+
self._socket = self._context.socket(zmq.PUSH)
|
|
84
|
+
self._socket.setsockopt(zmq.LINGER, 0)
|
|
85
|
+
self._socket.setsockopt(zmq.SNDHWM, 16)
|
|
86
|
+
self._socket.connect(f"tcp://{host}:{self.port}")
|
|
87
|
+
self._events = None
|
|
88
|
+
|
|
89
|
+
def _call(self, method, *args, **kwargs):
|
|
90
|
+
kwargs.pop("flush", None)
|
|
91
|
+
frames = encode(method, args, kwargs)
|
|
92
|
+
wait = 0.25 if method in STREAM_METHODS else 2.0
|
|
93
|
+
deadline = time.perf_counter() + wait
|
|
94
|
+
while True:
|
|
95
|
+
try:
|
|
96
|
+
self._socket.send_multipart(frames, flags=zmq.NOBLOCK)
|
|
97
|
+
return
|
|
98
|
+
except zmq.Again:
|
|
99
|
+
if time.perf_counter() > deadline:
|
|
100
|
+
if method not in STREAM_METHODS:
|
|
101
|
+
self._socket.send_multipart(frames)
|
|
102
|
+
return
|
|
103
|
+
time.sleep(0.01)
|
|
104
|
+
|
|
105
|
+
def plot(self, row, col, x, y, fmt=None, hold=False, flush=True, **kwargs):
|
|
106
|
+
"""``fmt`` defaults to ``'.'`` so existing debugger scripts keep their markers."""
|
|
107
|
+
del flush
|
|
108
|
+
self._call("plot", row, col, x, y, "." if fmt is None else fmt, hold=hold, **kwargs)
|
|
109
|
+
|
|
110
|
+
def figure3(self, row, col, title="Fig3d", **kwargs):
|
|
111
|
+
self._call("figure3", row, col, title=title, **kwargs)
|
|
112
|
+
return RemoteCloud(self, row, col)
|
|
113
|
+
|
|
114
|
+
def close_all(self, rows=None, cols=None, mon=None):
|
|
115
|
+
self.reset(rows, cols, mon)
|
|
116
|
+
|
|
117
|
+
def clf_all(self):
|
|
118
|
+
self.clfAll()
|
|
119
|
+
|
|
120
|
+
def inter(self, val=1):
|
|
121
|
+
self.interactive(bool(val))
|
|
122
|
+
|
|
123
|
+
def poll_event(self, timeout=0):
|
|
124
|
+
"""Return the newest key event from the server, or ``None``."""
|
|
125
|
+
if self._events is None:
|
|
126
|
+
self._events = self._context.socket(zmq.SUB)
|
|
127
|
+
self._events.setsockopt(zmq.LINGER, 0)
|
|
128
|
+
self._events.setsockopt(zmq.SUBSCRIBE, b"")
|
|
129
|
+
self._events.setsockopt(zmq.CONFLATE, 1)
|
|
130
|
+
self._events.connect(f"tcp://{self.host}:{self.port + 1}")
|
|
131
|
+
if self._events.poll(int(timeout)):
|
|
132
|
+
return self._events.recv_json()
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
def close(self):
|
|
136
|
+
for sock in (self._socket, self._events):
|
|
137
|
+
if sock is None:
|
|
138
|
+
continue
|
|
139
|
+
try:
|
|
140
|
+
sock.close(0)
|
|
141
|
+
except Exception:
|
|
142
|
+
pass
|
|
143
|
+
try:
|
|
144
|
+
self._context.term()
|
|
145
|
+
except Exception:
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
for _name in METHODS:
|
|
150
|
+
if not hasattr(PlotClient, _name):
|
|
151
|
+
setattr(PlotClient, _name, _remote(_name))
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""OpenCV named-window grid for live debug images.
|
|
2
|
+
|
|
3
|
+
Pop-out only. Inline notebooks should use ``FigureManager.imshow``.
|
|
4
|
+
Publish calls are no-ops until :func:`init_debug_views`.
|
|
5
|
+
|
|
6
|
+
from cogmatplot.debug_views import init_debug_views, debug_image, render_debug_views
|
|
7
|
+
|
|
8
|
+
init_debug_views(cols=4, monitor=1)
|
|
9
|
+
debug_image("people.mask", mask)
|
|
10
|
+
debug_image("people.depth", depth)
|
|
11
|
+
render_debug_views()
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from collections import OrderedDict
|
|
18
|
+
from typing import Any, Optional, Tuple
|
|
19
|
+
|
|
20
|
+
from cogmatplot.images import prepare_bgr
|
|
21
|
+
from cogmatplot.layout import grid_positions
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
_viewer: Optional["DebugViews"] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DebugViews:
|
|
29
|
+
"""OpenCV namedWindow grid for named debug image feeds."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
cols: int = 4,
|
|
34
|
+
monitor: int = 0,
|
|
35
|
+
size: Optional[Tuple[int, int]] = None,
|
|
36
|
+
title_offset: int = 30,
|
|
37
|
+
taskbar_offset: int = 45,
|
|
38
|
+
enabled: bool = True,
|
|
39
|
+
wait_key_ms: int = 1,
|
|
40
|
+
):
|
|
41
|
+
self.cols = max(1, int(cols))
|
|
42
|
+
self.monitor = int(monitor)
|
|
43
|
+
self.size = size
|
|
44
|
+
self.title_offset = int(title_offset)
|
|
45
|
+
self.taskbar_offset = int(taskbar_offset)
|
|
46
|
+
self.enabled = bool(enabled)
|
|
47
|
+
self.wait_key_ms = int(wait_key_ms)
|
|
48
|
+
self._feeds: OrderedDict[str, Optional[Tuple[Any, dict]]] = OrderedDict()
|
|
49
|
+
self._is_setup = False
|
|
50
|
+
|
|
51
|
+
def configure(
|
|
52
|
+
self,
|
|
53
|
+
cols: Optional[int] = None,
|
|
54
|
+
monitor: Optional[int] = None,
|
|
55
|
+
size: Optional[Tuple[int, int]] = None,
|
|
56
|
+
title_offset: Optional[int] = None,
|
|
57
|
+
taskbar_offset: Optional[int] = None,
|
|
58
|
+
enabled: Optional[bool] = None,
|
|
59
|
+
wait_key_ms: Optional[int] = None,
|
|
60
|
+
relayout: bool = True,
|
|
61
|
+
) -> None:
|
|
62
|
+
if cols is not None:
|
|
63
|
+
self.cols = max(1, int(cols))
|
|
64
|
+
if monitor is not None:
|
|
65
|
+
self.monitor = int(monitor)
|
|
66
|
+
if size is not None:
|
|
67
|
+
self.size = size
|
|
68
|
+
if title_offset is not None:
|
|
69
|
+
self.title_offset = int(title_offset)
|
|
70
|
+
if taskbar_offset is not None:
|
|
71
|
+
self.taskbar_offset = int(taskbar_offset)
|
|
72
|
+
if enabled is not None:
|
|
73
|
+
self.enabled = bool(enabled)
|
|
74
|
+
if wait_key_ms is not None:
|
|
75
|
+
self.wait_key_ms = int(wait_key_ms)
|
|
76
|
+
if relayout:
|
|
77
|
+
self._is_setup = False
|
|
78
|
+
|
|
79
|
+
def publish(self, name: str, image, **kwargs) -> None:
|
|
80
|
+
if not self.enabled:
|
|
81
|
+
return
|
|
82
|
+
if not name:
|
|
83
|
+
raise ValueError("debug feed name must be non-empty")
|
|
84
|
+
if name not in self._feeds:
|
|
85
|
+
self._is_setup = False
|
|
86
|
+
self._feeds[name] = (image, kwargs)
|
|
87
|
+
|
|
88
|
+
def clear_images(self) -> None:
|
|
89
|
+
for name in list(self._feeds.keys()):
|
|
90
|
+
self._feeds[name] = None
|
|
91
|
+
|
|
92
|
+
def clear(self) -> None:
|
|
93
|
+
self._feeds.clear()
|
|
94
|
+
self._is_setup = False
|
|
95
|
+
|
|
96
|
+
def feed_names(self):
|
|
97
|
+
return list(self._feeds.keys())
|
|
98
|
+
|
|
99
|
+
def render(self, wait_key_ms: Optional[int] = None) -> None:
|
|
100
|
+
if not self.enabled or not self._feeds:
|
|
101
|
+
return
|
|
102
|
+
import cv2
|
|
103
|
+
|
|
104
|
+
if not self._is_setup:
|
|
105
|
+
self._setup_windows()
|
|
106
|
+
delay = self.wait_key_ms if wait_key_ms is None else int(wait_key_ms)
|
|
107
|
+
try:
|
|
108
|
+
for name, payload in self._feeds.items():
|
|
109
|
+
if payload is None:
|
|
110
|
+
continue
|
|
111
|
+
image, kwargs = payload
|
|
112
|
+
display = prepare_bgr(image, **kwargs)
|
|
113
|
+
if display is None:
|
|
114
|
+
continue
|
|
115
|
+
cv2.imshow(name, display)
|
|
116
|
+
cv2.waitKey(delay)
|
|
117
|
+
except Exception:
|
|
118
|
+
log.debug("debug view render failed", exc_info=True)
|
|
119
|
+
|
|
120
|
+
def close(self) -> None:
|
|
121
|
+
import cv2
|
|
122
|
+
|
|
123
|
+
for name in list(self._feeds.keys()):
|
|
124
|
+
try:
|
|
125
|
+
cv2.destroyWindow(name)
|
|
126
|
+
except Exception:
|
|
127
|
+
pass
|
|
128
|
+
self._feeds.clear()
|
|
129
|
+
self._is_setup = False
|
|
130
|
+
|
|
131
|
+
def _setup_windows(self) -> None:
|
|
132
|
+
import cv2
|
|
133
|
+
|
|
134
|
+
positions = grid_positions(
|
|
135
|
+
len(self._feeds),
|
|
136
|
+
self.cols,
|
|
137
|
+
self.monitor,
|
|
138
|
+
cell_size=self.size,
|
|
139
|
+
title=self.title_offset,
|
|
140
|
+
taskbar=self.taskbar_offset,
|
|
141
|
+
)
|
|
142
|
+
from cogmatplot.place import place_cv_window
|
|
143
|
+
|
|
144
|
+
for name, (xpos, ypos, dw, dh) in zip(self._feeds, positions):
|
|
145
|
+
cv2.namedWindow(name, cv2.WINDOW_NORMAL)
|
|
146
|
+
place_cv_window(name, xpos, ypos, dw, dh)
|
|
147
|
+
self._is_setup = True
|
|
148
|
+
if positions:
|
|
149
|
+
_x, _y, dw, dh = positions[0]
|
|
150
|
+
else:
|
|
151
|
+
dw = dh = 0
|
|
152
|
+
log.info(
|
|
153
|
+
"DebugViews ready: %d feeds, cols=%d, monitor=%d, cell=%dx%d",
|
|
154
|
+
len(self._feeds), self.cols, self.monitor, dh, dw,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def init_debug_views(
|
|
159
|
+
cols: int = 4,
|
|
160
|
+
monitor: int = 0,
|
|
161
|
+
size: Optional[Tuple[int, int]] = None,
|
|
162
|
+
title_offset: int = 30,
|
|
163
|
+
taskbar_offset: int = 45,
|
|
164
|
+
enabled: bool = True,
|
|
165
|
+
wait_key_ms: int = 1,
|
|
166
|
+
recreate: bool = False,
|
|
167
|
+
) -> DebugViews:
|
|
168
|
+
"""Bootstrap the process-wide debug viewer. Pass ``recreate=True`` to replace it."""
|
|
169
|
+
global _viewer
|
|
170
|
+
if _viewer is not None and not recreate:
|
|
171
|
+
_viewer.configure(
|
|
172
|
+
cols=cols, monitor=monitor, size=size, title_offset=title_offset,
|
|
173
|
+
taskbar_offset=taskbar_offset, enabled=enabled, wait_key_ms=wait_key_ms,
|
|
174
|
+
)
|
|
175
|
+
return _viewer
|
|
176
|
+
if _viewer is not None and recreate:
|
|
177
|
+
try:
|
|
178
|
+
_viewer.close()
|
|
179
|
+
except Exception:
|
|
180
|
+
pass
|
|
181
|
+
_viewer = DebugViews(
|
|
182
|
+
cols=cols, monitor=monitor, size=size, title_offset=title_offset,
|
|
183
|
+
taskbar_offset=taskbar_offset, enabled=enabled, wait_key_ms=wait_key_ms,
|
|
184
|
+
)
|
|
185
|
+
return _viewer
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def get_debug_views() -> Optional[DebugViews]:
|
|
189
|
+
return _viewer
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def is_debug_views_active() -> bool:
|
|
193
|
+
return _viewer is not None and _viewer.enabled
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def debug_image(name: str, image, auto_render: bool = False, **kwargs) -> None:
|
|
197
|
+
"""Publish ``image`` on the singleton. No-op until :func:`init_debug_views`."""
|
|
198
|
+
if _viewer is None or not _viewer.enabled:
|
|
199
|
+
return
|
|
200
|
+
_viewer.publish(name, image, **kwargs)
|
|
201
|
+
if auto_render:
|
|
202
|
+
_viewer.render()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def render_debug_views(wait_key_ms: Optional[int] = None) -> None:
|
|
206
|
+
if _viewer is None or not _viewer.enabled:
|
|
207
|
+
return
|
|
208
|
+
_viewer.render(wait_key_ms=wait_key_ms)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def clear_debug_images() -> None:
|
|
212
|
+
if _viewer is not None:
|
|
213
|
+
_viewer.clear_images()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def close_debug_views() -> None:
|
|
217
|
+
global _viewer
|
|
218
|
+
if _viewer is not None:
|
|
219
|
+
try:
|
|
220
|
+
_viewer.close()
|
|
221
|
+
finally:
|
|
222
|
+
_viewer = None
|
cogmatplot/images.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Convert arrays into the BGR uint8 images OpenCV shows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def prepare_bgr(image, normalize: bool = True, colormap: Optional[int] = None, rgb: bool = False):
|
|
11
|
+
"""Return a BGR ``uint8`` image, or ``None`` when the array cannot be shown."""
|
|
12
|
+
import cv2
|
|
13
|
+
|
|
14
|
+
if image is None:
|
|
15
|
+
return None
|
|
16
|
+
if not isinstance(image, np.ndarray):
|
|
17
|
+
if hasattr(image, "__array__"):
|
|
18
|
+
image = np.asarray(image)
|
|
19
|
+
else:
|
|
20
|
+
return None
|
|
21
|
+
if image.size == 0:
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
im = image
|
|
25
|
+
if im.ndim == 2:
|
|
26
|
+
im = _to_uint8(im, normalize)
|
|
27
|
+
if colormap is not None:
|
|
28
|
+
return cv2.applyColorMap(im, colormap)
|
|
29
|
+
return cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)
|
|
30
|
+
|
|
31
|
+
if im.ndim == 3 and im.shape[2] == 3:
|
|
32
|
+
im = _to_uint8(im, normalize)
|
|
33
|
+
return cv2.cvtColor(im, cv2.COLOR_RGB2BGR) if rgb else im
|
|
34
|
+
|
|
35
|
+
if im.ndim == 3 and im.shape[2] == 4:
|
|
36
|
+
bgr = im[:, :, :3]
|
|
37
|
+
if bgr.dtype != np.uint8:
|
|
38
|
+
bgr = np.clip(bgr, 0, 255).astype(np.uint8)
|
|
39
|
+
return cv2.cvtColor(bgr, cv2.COLOR_RGB2BGR) if rgb else bgr
|
|
40
|
+
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _to_uint8(im, normalize: bool):
|
|
45
|
+
if im.dtype == np.uint8:
|
|
46
|
+
return im
|
|
47
|
+
if normalize:
|
|
48
|
+
imf = im.astype(np.float64)
|
|
49
|
+
lo = np.nanmin(imf)
|
|
50
|
+
hi = np.nanmax(imf)
|
|
51
|
+
if hi > lo:
|
|
52
|
+
return ((imf - lo) / (hi - lo) * 255.0).astype(np.uint8)
|
|
53
|
+
return np.zeros(im.shape, dtype=np.uint8)
|
|
54
|
+
return np.clip(im, 0, 255).astype(np.uint8)
|
cogmatplot/layout.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Monitor grids shared by matplotlib, OpenCV, and PyVista windows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from types import SimpleNamespace
|
|
7
|
+
from typing import List, Optional, Sequence, Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _monitors():
|
|
11
|
+
from screeninfo import get_monitors
|
|
12
|
+
|
|
13
|
+
return get_monitors()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def pick_monitor(index: int = 0):
|
|
17
|
+
try:
|
|
18
|
+
monitors = list(_monitors() or [])
|
|
19
|
+
except Exception:
|
|
20
|
+
monitors = []
|
|
21
|
+
if not monitors:
|
|
22
|
+
return SimpleNamespace(x=0, y=0, width=1600, height=900, name="default")
|
|
23
|
+
i = min(max(int(index), 0), len(monitors) - 1)
|
|
24
|
+
return monitors[i]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def gridfig_box(
|
|
28
|
+
row: int,
|
|
29
|
+
col: int,
|
|
30
|
+
rows: int,
|
|
31
|
+
cols: int,
|
|
32
|
+
monitor: int = 0,
|
|
33
|
+
colpad: int = 50,
|
|
34
|
+
rowpad: int = 50,
|
|
35
|
+
rowend: int = 35,
|
|
36
|
+
barpad: int = 30,
|
|
37
|
+
) -> Tuple[int, int, int, int]:
|
|
38
|
+
"""Cell rectangle for one tile. Returns ``(x, y, w, h)`` in screen pixels."""
|
|
39
|
+
screen = pick_monitor(monitor)
|
|
40
|
+
rows = max(1, int(rows))
|
|
41
|
+
cols = max(1, int(cols))
|
|
42
|
+
row = int(max(0, min(rows - 1, row)))
|
|
43
|
+
col = int(max(0, min(cols - 1, col)))
|
|
44
|
+
fw = (screen.width // cols) - colpad
|
|
45
|
+
fh = ((screen.height - rowend) // rows) - rowpad
|
|
46
|
+
x = int(screen.x + col * fw + (col + 1) * colpad / 2)
|
|
47
|
+
y = int(screen.y + row * fh + (row + 1) * rowpad / 2)
|
|
48
|
+
return x, y, int(max(fw, 80)), int(max(fh - barpad, 80))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def grid_positions(
|
|
52
|
+
count: int,
|
|
53
|
+
cols: int,
|
|
54
|
+
monitor: int = 0,
|
|
55
|
+
cell_size: Optional[Sequence[int]] = None,
|
|
56
|
+
title: int = 30,
|
|
57
|
+
taskbar: int = 45,
|
|
58
|
+
) -> List[Tuple[int, int, int, int]]:
|
|
59
|
+
"""Named-window packing for debug streams.
|
|
60
|
+
|
|
61
|
+
``cell_size`` is ``(height, width)`` when cells are fixed.
|
|
62
|
+
Each item is ``(x, y, w, h)``.
|
|
63
|
+
"""
|
|
64
|
+
screen = pick_monitor(monitor)
|
|
65
|
+
width = int(screen.width)
|
|
66
|
+
height = int(screen.height) - int(taskbar)
|
|
67
|
+
num_cols = max(1, int(cols))
|
|
68
|
+
n = max(1, int(count))
|
|
69
|
+
if cell_size is not None:
|
|
70
|
+
dh, dw = int(cell_size[0]), int(cell_size[1])
|
|
71
|
+
else:
|
|
72
|
+
dw = math.floor(width / float(num_cols))
|
|
73
|
+
num_rows = max(1, math.ceil(n / float(num_cols)))
|
|
74
|
+
if num_rows * dw > height:
|
|
75
|
+
dw = math.floor(height / float(num_rows))
|
|
76
|
+
dh = math.floor((height - title * num_rows) / float(num_rows))
|
|
77
|
+
else:
|
|
78
|
+
dh = dw
|
|
79
|
+
positions = []
|
|
80
|
+
for i in range(int(count)):
|
|
81
|
+
r, c = divmod(i, num_cols)
|
|
82
|
+
positions.append((
|
|
83
|
+
int(dw * c + screen.x),
|
|
84
|
+
int((dh + title) * r + screen.y),
|
|
85
|
+
int(dw),
|
|
86
|
+
int(dh),
|
|
87
|
+
))
|
|
88
|
+
return positions
|