-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path_lib.py
More file actions
191 lines (145 loc) · 4.98 KB
/
_lib.py
File metadata and controls
191 lines (145 loc) · 4.98 KB
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
import ctypes
import platform
from pathlib import Path
from ctypes import c_byte, c_char_p, c_void_p, c_int32, POINTER
from PIL import Image
class Error(Exception):
pass
def _image_format_to_string(format: int):
match format:
case 0:
return "RGBA"
case 3:
return "RGB"
case 4:
return "L"
case _:
raise ValueError(f"Unsupported image format: {format}")
def _image_mode_from_string(mode: str):
match mode:
case "RGBA":
return 0, 4 # visp::image_format, bytes per pixel
case "RGB":
return 3, 3
case "L":
return 4, 1
case _:
raise ValueError(f"Unsupported image mode: {mode}")
class ImageView(ctypes.Structure):
_fields_ = [
("width", c_int32),
("height", c_int32),
("stride", c_int32),
("format", c_int32),
("data", c_void_p),
]
@staticmethod
def from_bytes(width: int, height: int, stride: int, format: int, data: bytes):
ptr = (c_byte * len(data)).from_buffer_copy(data)
return ImageView(width, height, stride, format, ctypes.cast(ptr, ctypes.c_void_p))
@staticmethod
def from_pil_image(image):
assert isinstance(image, Image.Image), "Expected a PIL Image"
data = image.tobytes()
w, h = image.size
format, bpp = _image_mode_from_string(image.mode)
return ImageView.from_bytes(w, h, w * bpp, format, data)
def to_pil_image(self):
mode = _image_format_to_string(self.format)
size = self.height * self.stride
data = memoryview((c_byte * size).from_address(self.data))
return Image.frombytes(mode, (self.width, self.height), data, "raw", mode, self.stride)
class _ImageData(ctypes.Structure):
pass
class _Device(ctypes.Structure):
pass
class _Model(ctypes.Structure):
pass
ImageData = POINTER(_ImageData)
Device = POINTER(_Device)
Model = POINTER(_Model)
Handle = ctypes._Pointer
def _load():
cur_dir = Path(__file__).parent
system = platform.system().lower()
if system == "windows":
prefix = ""
suffix = ".dll"
libdir = "bin"
elif system == "darwin":
prefix = "lib"
suffix = ".dylib"
libdir = "lib"
else: # assume Linux / Unix
prefix = "lib"
suffix = ".so"
libdir = "lib"
libname = f"{prefix}visioncpp{suffix}"
paths = [
cur_dir / libname,
cur_dir.parent.parent / libdir / libname,
cur_dir.parent.parent.parent / "build" / libdir / libname,
cur_dir.parent.parent.parent / "build" / libdir / "Release" / libname,
]
error = f"Library {libname} not found in any of the following paths: {paths}"
for path in paths:
if path.exists():
try:
lib = ctypes.CDLL(str(path))
return lib, path
except OSError as e:
error = e
continue
raise OSError(f"Could not load vision.cpp library: {error}")
def init():
lib, path = _load()
lib.visp_get_last_error.restype = c_char_p
lib.visp_backend_load_all.argtypes = [c_char_p]
lib.visp_backend_load_all.restype = c_int32
lib.visp_image_destroy.argtypes = [ImageData]
lib.visp_image_destroy.restype = None
lib.visp_device_init.argtypes = [c_int32, POINTER(Device)]
lib.visp_device_init.restype = c_int32
lib.visp_device_destroy.argtypes = [Device]
lib.visp_device_destroy.restype = None
lib.visp_device_type.argtypes = [Device]
lib.visp_device_type.restype = c_int32
lib.visp_device_name.argtypes = [Device]
lib.visp_device_name.restype = c_char_p
lib.visp_device_description.argtypes = [Device]
lib.visp_device_description.restype = c_char_p
lib.visp_model_detect_family.argtypes = [c_char_p, POINTER(c_int32)]
lib.visp_model_detect_family.restype = c_int32
lib.visp_model_load.argtypes = [c_char_p, Device, c_int32, POINTER(Model)]
lib.visp_model_load.restype = c_int32
lib.visp_model_destroy.argtypes = [Model, c_int32]
lib.visp_model_destroy.restype = None
lib.visp_model_compute.argtypes = [
Model,
c_int32,
POINTER(ImageView),
c_int32,
POINTER(c_int32),
c_int32,
POINTER(ImageView),
POINTER(ImageData),
]
lib.visp_model_compute.restype = c_int32
# On Linux, libvisioncpp might be in lib/ and ggml backends in bin/
if path.parent.name == "lib":
bin_dir = path.parent.parent / "bin"
if bin_dir.exists():
lib.visp_backend_load_all(str(bin_dir).encode())
return lib
_lib: ctypes.CDLL | None = None
def get_lib() -> ctypes.CDLL:
global _lib
if _lib is None:
_lib = init()
return _lib
def check(return_value: int):
if return_value == 0:
assert _lib is not None, "Library not initialized"
raise Error(_lib.visp_get_last_error().decode())
def path_to_char_p(p: str | Path):
return str(p).encode()