GPU 访问教程
To access Zivid data on the GPU without copying it to CPU memory: capture as usual, retrieve a DeviceArray from the resulting point cloud or 2D frame, then pass its device pointer to your GPU framework (CUDA, OpenCL, PyTorch, CuPy, or OpenCV).
简介
Zivid SDK 在整个处理流程中将所有捕获的数据(点云、彩色图像、深度图和 SNR)保存在 GPU 设备内存中。GPU 访问 API 让您可以直接在 GPU 上处理这些数据,而无需先将其传输到 CPU 内存,从而实现与 CUDA、OpenCL、PyTorch、CuPy 或 OpenCV 等框架的零拷贝集成。
核心类型是 DeviceArray。它是一个带引用计数的 GPU 缓冲区智能指针,当不再使用时会自动释放 GPU 内存。捕获后,您可以从 PointCloud 或 Frame2D 获取一个 DeviceArray,然后将其底层的设备指针传递给您的 GPU 框架。
有关每种格式的内存布局的更深入参考,请参阅 DeviceArray 参考 参考文章,以及其配套文章 DeviceArray — Stream、Queue 和 Context,了解流/队列排序和上下文共享模型。
前提条件
安装 Zivid Software,并为您的 GPU 选择 GPU 计算后端(CUDA 或 OpenCL)。
对于 Python:安装 zivid-python
初始化、连接和捕获
这些是标准的 Zivid 步骤,并非 GPU 访问特有的操作:初始化应用程序(在程序运行期间保持其存活)、连接相机,然后进行捕获。有关详细信息,请参阅 捕获教程。返回的 PointCloud 和 Frame2D 对象始终将其数据保存在 GPU 设备内存中。
SDK 根据 Config.yml 中配置的计算设备来选择 GPU。如果未指定设备,它会选择计算核心数量最多的 GPU。有关如何选择特定 GPU 的信息,请参阅 Selecting Compute Device。
高级:指定 GPU 上下文
对于大多数 CUDA 使用场景,无需进行显式的上下文设置。SDK 会自动与 CUDA 运行时上下文集成。如果您需要共享特定的 CUDA 或 OpenCL 上下文(例如,使用与 PyTorch 或您自己的 OpenCL 代码相同的上下文),请将其传递给 Application 构造函数:
// Share an existing CUDA context
CUcontext cuContext = ...;
Zivid::Application zivid{ Zivid::CUDAContextPtr{ cuContext } };
// Or share an existing OpenCL context
cl_context clContext = ...;
Zivid::Application zivid{ Zivid::OpenCLContextPtr{ clContext } };
import zivid
# Share an existing CUDA context
app = zivid.Application(cuda_context=zivid.CUDAContextPtr(cu_context))
您还可以通过 ComputeDevice::nativeContext() 和 ComputeDevice::nativeStreamHandle() 获取 SDK 自身的计算上下文和流句柄,以便与您自己的代码共享,而无需预先传入上下文。
有关何时需要共享上下文以及 CUDA 和 OpenCL 在这方面的区别,请参阅 GPU Context 共享。
从 3D 点云获取 GPU 数据
3D 捕获后,可直接从 GPU 内存检索点云缓冲区的 DeviceArray 对象。所有缓冲区都保留在 GPU 上。除非您明确请求,否则不会将任何数据传输到 CPU。名称中包含 copy 一词的任何函数都恰好执行此操作:将数据从 GPU 复制到 CPU。
所有返回 DeviceArray 的函数都会接受一个 CUDA 流或 OpenCL 队列,并在返回之前将 SDK 的计算操作同步到其中,因此返回的缓冲区已经针对该流/队列排好序。您可以传入自己的 CUDA 流或 OpenCL 队列,或者在没有自己的流/队列时使用 ComputeDevice::sdkStreamOrQueue() 来使用 SDK 自身的流:
const auto streamOrQueue = zivid.computeDevice().sdkStreamOrQueue();
const auto xyzBuffer = pointCloud.devicePointsXYZ(streamOrQueue);
var streamOrQueue = zivid.ComputeDevice.SdkStreamOrQueue;
using (var xyzBuffer = pointCloud.DevicePointsXYZ(streamOrQueue))
{
stream_or_queue = app.compute_device().sdk_stream_or_queue()
xyz_buffer = point_cloud.device_points_xyz(stream_or_queue)
同样的模式适用于其他 PointCloud 缓冲区,例如 XYZW(4×float,GPU 对齐)、Z(float)、SNR(float)、法线(3×float),以及任何受支持格式的颜色:
const auto xyzwBuffer = pointCloud.devicePointsXYZW(streamOrQueue);
const auto zBuffer = pointCloud.devicePointsZ(streamOrQueue);
const auto snrBuffer = pointCloud.deviceSNRs(streamOrQueue);
const auto normalBuffer = pointCloud.deviceNormalsXYZ(streamOrQueue);
const auto rgbaBuffer = pointCloud.imageDeviceArray<Zivid::ColorRGBA_SRGB>(streamOrQueue);
using (var xyzwBuffer = pointCloud.DevicePointsXYZW(streamOrQueue))
using (var zBuffer = pointCloud.DevicePointsZ(streamOrQueue))
using (var snrBuffer = pointCloud.DeviceSNRs(streamOrQueue))
using (var normalBuffer = pointCloud.DeviceNormalsXYZ(streamOrQueue))
using (var rgbaBuffer = pointCloud.DeviceImageRGBA_SRGB(streamOrQueue))
{
Console.WriteLine("Other buffers (elements): XYZW=" + xyzwBuffer.Size + ", Z=" + zBuffer.Size + ", SNR=" + snrBuffer.Size + ", Normals=" + normalBuffer.Size + ", RGBA=" + rgbaBuffer.Size);
}
xyzw_buffer = point_cloud.device_points_xyzw(stream_or_queue)
z_buffer = point_cloud.device_points_z(stream_or_queue)
snr_buffer = point_cloud.device_snrs(stream_or_queue)
normals_buffer = point_cloud.device_normals_xyz(stream_or_queue)
rgba_buffer = point_cloud.device_image(stream_or_queue, zivid.PixelFormat.RGBA_SRGB)
从 2D 帧获取 GPU 数据
2D 捕获后,检索图像的 DeviceArray:
const auto imageBuffer = frame2D.imageDeviceArray<Zivid::ColorRGBA_SRGB>(streamOrQueue);
using (var imageBuffer = frame2D.ImageDeviceArrayRGBA_SRGB(streamOrQueue))
image_buffer = frame_2d.image_device_array(stream_or_queue, zivid.PixelFormat.RGBA_SRGB)
可用格式:
ColorRGBAColorRGBA_SRGBColorBGRAColorBGRA_SRGBColorRGBAf
检查 DeviceArray
DeviceArray 会暴露有关缓冲区的元数据:
const auto shape = xyzBuffer.shape();
std::cout << "Backend: " << Zivid::toString(xyzBuffer.backend()) << '\n';
std::cout << "Shape: [" << shape[0] << ", " << shape[1] << ", " << shape[2] << "]\n";
std::cout << "Strides (elements): [" << xyzBuffer.strides()[0] << ", " << xyzBuffer.strides()[1] << "]\n";
std::cout << "SizeInBytes: " << xyzBuffer.sizeInBytes() << '\n';
Console.WriteLine("Backend: " + xyzBuffer.Backend);
Console.WriteLine("Shape: [" + string.Join(", ", xyzBuffer.Shape()) + "]");
Console.WriteLine("Strides (elements): [" + string.Join(", ", xyzBuffer.Strides()) + "]");
Console.WriteLine("SizeInBytes: " + xyzBuffer.SizeInBytes);
print(f"Backend: {xyz_buffer.backend}")
print(f"Shape: {xyz_buffer.shape}")
print(f"Strides (elements): {xyz_buffer.strides}")
print(f"SizeInBytes: {xyz_buffer.size_bytes}")
For what DeviceArray::shape(), DeviceArray::strides(), and DeviceArray::stridesInBytes() return for each format, and how the elements are laid out in memory, see 数据布局.
使用设备指针
获得 DeviceArray 后,将其设备指针传递给您的 GPU 框架,以实现零拷贝处理。由于您在获取缓冲区时已提供了流或队列,SDK 已经将其计算操作针对该流/队列排好序。因此,DeviceArray::devicePointer() 调用只是一个纯粹的访问器:它不执行任何同步操作,会立即返回,您可以马上在同一流/队列上使用该指针。
有关 SDK 如何针对您的流或队列对其工作进行排序的具体细节,请参阅 Stream 和 Queue 排序。
CUDA
在获取缓冲区时提供您的 CUDA 流。SDK 会在其内部流上记录一个事件,并让您的流等待该事件,因此该缓冲区已针对您的流排好序,无需进行任何 CPU 端同步:
if(zivid.computeDevice().backend() == Zivid::ComputeBackend::cuda)
{
const Zivid::CUDAStreamPtr cudaStream{};
const auto cudaXyzBuffer = pointCloud.devicePointsXYZ(cudaStream);
void *const devicePtr = cudaXyzBuffer.devicePointer();
std::cout << "CUDA device pointer: " << devicePtr << '\n';
}
if (xyzBuffer.Backend == Zivid.NET.ComputeBackend.Cuda)
{
var cudaStream = new Zivid.NET.CUDAStreamPtr();
using (var cudaXyzBuffer = pointCloud.DevicePointsXYZ(cudaStream))
{
var devicePtr = cudaXyzBuffer.DevicePointer();
Console.WriteLine("CUDA device pointer: " + devicePtr);
}
}
if xyz_buffer.backend == zivid.ComputeBackend.cuda:
cuda_stream = zivid.CUDAStreamPtr()
cuda_xyz_buffer = point_cloud.device_points_xyz(cuda_stream)
device_ptr = cuda_xyz_buffer.device_pointer()
print(f"CUDA device pointer: {hex(device_ptr)}")
备注
在获取缓冲区时,传入来自您的 GPU 框架的流(例如 OpenCV 中的 stream.cudaPtr()、PyTorch 中的 pytorch_stream.cuda_stream,或 CuPy 中的 cupy_stream.ptr),以使所有操作都保持在单一流上,避免隐式同步。
OpenCL
在获取缓冲区时提供您的 OpenCL 命令队列。SDK 会向您的队列插入一个屏障(barrier),以等待所有先前的 SDK 操作完成。此后 DeviceArray::devicePointer() 直接返回原始的 cl_mem,无需进一步同步:
cl_command_queue userQueue = ...; // must share context with Application
auto buffer = frame2D.imageDeviceArray<Zivid::ColorRGBA_SRGB>(Zivid::OpenCLCommandQueuePtr{ userQueue });
void *devicePtr = buffer.devicePointer();
IntPtr userQueue = ...; // cl_command_queue; must share context with Application
using (var buffer = frame2D.ImageDeviceArrayRGBA_SRGB(new Zivid.NET.OpenCLCommandQueuePtr { CommandQueue = userQueue }))
{
var devicePtr = buffer.DevicePointer();
}
buffer = frame_2d.image_device_array(zivid.OpenCLCommandQueuePtr(user_queue), zivid.PixelFormat.RGBA_SRGB)
device_ptr = buffer.device_pointer()
框架互操作性
该设备指针是一种通用的 GPU 分配内存,不绑定于任何特定框架。对于 CUDA 后端,它是通过 cudaMallocAsync 分配的指针,因此任何可以使用 CUDA 设备指针的框架都可以直接使用它。
在 Python 中,将 DeviceArray 交给 PyTorch 最简单的方法是使用 CUDA Array Interface。zivid-python 在 DeviceArray 上实现了 __cuda_array_interface__ (仅限 CUDA 后端),因此 torch.as_tensor(device_array, device="cuda") 可以将该缓冲区以零拷贝方式导入 PyTorch,无需手动处理指针、形状或步长:
DLPack is supported directly as well.
Since zivid-python 2.18.0.2, a wrapper-only release built on SDK 2.18.0, DeviceArray implements the __dlpack__ and __dlpack_device__ protocol (CUDA backend only), so torch.from_dlpack(device_array) and cupy.from_dlpack(device_array) import the buffer zero-copy with no capsule handling of your own.
The DeviceArray is kept alive by the imported tensor, so the GPU memory stays valid for as long as the consumer holds it.
The protocol arguments behave as follows:
streamis accepted and ignored, because the buffer was already ordered against the stream or queue you passed at acquisition.max_versionselects the exchange: a consumer that accepts DLPack 1.0 or newer gets a"dltensor_versioned"capsule, and any other consumer gets the legacy"dltensor"capsule.dl_devicemay only name the CUDA device the buffer already lives on, and raisesBufferErrorfor any other device.copy=TrueraisesBufferError, because the export hands out a view of memory that other Zivid objects still read.
备注
CuPy bridges the two protocols, so cupy.asarray(device_array) also yields an object that DLPack consumers such as cupoch can import zero-copy.
That route works on older zivid-python versions too.
When you must build the DLPack capsule yourself -- in C++, or in Python against a zivid-python older than 2.18.0.2 -- construct a DLManagedTensor from the DeviceArray.
It exposes everything needed to build one: the device pointer (DeviceArray::devicePointer()), the element data type (fixed by the format), the shape (DeviceArray::shape()), the strides (DeviceArray::strides() / DeviceArray::stridesInBytes()), and the backend/device (DeviceArray::backend()).
The following wires its device pointer, shape, strides (in elements), element data type, and CUDA device into the tensor, deriving the DLPack data type generically from the format's value type so the same code path handles both float point data and 8-bit color.
The DeviceArray is kept alive by the tensor's manager context, so the GPU memory stays valid for as long as a consumer holds the tensor:
const auto shape = deviceArray.shape();
const auto strides = deviceArray.strides();
auto *context = new DLPackManagerContext<Format>{
deviceArray,
std::vector<int64_t>{ shape.begin(), shape.end() },
std::vector<int64_t>{ strides.begin(), strides.end() },
};
auto *managedTensor = new DLManagedTensor{};
managedTensor->dl_tensor.data = context->deviceArray.devicePointer();
managedTensor->dl_tensor.device =
DLDevice{ kDLCUDA, static_cast<int32_t>(cudaDeviceIdForPointer(context->deviceArray.devicePointer())) };
managedTensor->dl_tensor.ndim = static_cast<int32_t>(context->shape.size());
managedTensor->dl_tensor.dtype = dlDataType<Format>();
managedTensor->dl_tensor.shape = context->shape.data();
managedTensor->dl_tensor.strides = context->strides.data();
managedTensor->dl_tensor.byte_offset = 0;
managedTensor->manager_ctx = context;
managedTensor->deleter = &deleteDLManagedTensor<Format>;
shape = tuple(int(dimension) for dimension in device_array.shape)
strides = tuple(int(stride) for stride in device_array.strides)
shape_array = (ctypes.c_int64 * len(shape))(*shape)
strides_array = (ctypes.c_int64 * len(strides))(*strides)
managed = _DLManagedTensor()
managed.dl_tensor.data = ctypes.c_void_p(device_array.device_pointer())
managed.dl_tensor.device = _DLDevice(_KDLCUDA, device_id) # pylint: disable=no-value-for-parameter
managed.dl_tensor.ndim = len(shape)
managed.dl_tensor.dtype = _dl_data_type(device_array)
managed.dl_tensor.shape = shape_array
managed.dl_tensor.strides = strides_array
managed.dl_tensor.byte_offset = 0
managed.deleter = _release_managed_tensor # pylint: disable=attribute-defined-outside-init
_MANAGER_CONTEXTS[ctypes.addressof(managed)] = (managed, shape_array, strides_array, device_array)
生成的张量随后可以交给任何 DLPack 消费者。在 Python 中,torch.from_dlpack 会将其以零拷贝方式导入 PyTorch:
复制到 CPU
当您需要在 CPU 上使用数据时,请显式地复制它。DeviceArray::toArray2D() 方法会调度设备到主机的复制操作,并立即返回,此时复制操作不一定已经完成。在读取主机数据之前,请在您传入的同一流或队列上调用 synchronizeStream():
const auto hostPoints = xyzBuffer.toArray2D(streamOrQueue);
Zivid::synchronizeStream(streamOrQueue);
var hostPoints = xyzBuffer.ToArray2D(streamOrQueue);
Zivid.NET.Compute.SynchronizeStream(streamOrQueue);
host_points = xyz_buffer.copy_to_host_organized_array(stream_or_queue)
zivid.synchronize_stream(stream_or_queue)
集成示例
以下示例展示了如何将 GPU 访问 API 与常用框架完整地端到端集成使用:
CaptureAndConvertImageWithOpenCVOnCuda (C++、OpenCV CUDA):使用 OpenCV CUDA 在 GPU 上将 2D RGBA 图像转换为灰度图像,而无需 CPU 往返传输。
capture_and_process_image_with_cupy_on_cuda (Python、CuPy):将 Zivid GPU 缓冲区封装为 CuPy 数组,以进行零拷贝 GPU 处理。
capture_and_segment_image_with_pytorch_on_cuda (Python、PyTorch):使用共享的 CUDA 流直接在 GPU 图像数据上运行语义分割推理。
capture_and_convert_to_dlpack_tensor_on_cuda (Python、PyTorch):以两种方式将
DeviceArray交给 PyTorch——推荐使用的 CUDA Array Interface 方式(torch.as_tensor(device_array, device="cuda"))以及一种可选的、直接从缓冲区构建的显式 DLPack 胶囊方式。CaptureAndConvertToDlpackTensorOnCuda (C++、DLPack):捕获一个 2D+3D 帧,并为点云(
PointXYZ)和颜色(ColorRGBA_SRGB)分别构建DLManagedTensor,通用地根据格式推导出 DLPack 数据类型,并通过张量的管理上下文使每个缓冲区在 DLPack 消费者使用期间保持存活。capture_and_render_point_cloud_with_opengl_on_cuda (Python、OpenGL):通过将 GPU 缓冲区直接复制到 OpenGL 顶点缓冲区,交互式地渲染带颜色的点云。
结论
本教程展示了如何使用 DeviceArray 在 GPU 上访问 Zivid 数据,而不必通过 CPU 内存进行复制。要点如下:
Obtain a
DeviceArrayfromPointCloudorFrame2Dafter capture, passing your CUDA stream or OpenCL queue (orComputeDevice::sdkStreamOrQueue()).调用
DeviceArray::devicePointer()以获取原始设备指针,供您的 GPU 框架使用。由于该缓冲区在您获取时已针对您的流/队列排好序,因此无需进一步同步。Use
DeviceArray::toArray2D()followed bysynchronizeStream()when you need the data on the CPU.当您需要与其他框架进行完整的流共享时,请将您自己的 CUDA 或 OpenCL 上下文传递给
Application。