首页 > 后端开发 > Python教程 > 构建 Python 相机 SDK 并使用它进行多条码扫描

构建 Python 相机 SDK 并使用它进行多条码扫描

Linda Hamilton
发布: 2025-01-05 01:35:40
原创
310 人浏览过

现在轻量级 C 相机 SDK 已经完成,适用于 WindowsLinuxmacOS,我们可以将其集成到其他高级编程语言中。在本文中,我们将探讨如何基于 C 相机库构建 Python 相机 SDK,并使用它与 Dynamsoft Barcode Reader SDK 进行多条码扫描。

Python 多条码扫描仪演示视频

搭建 CPython 扩展项目的脚手架

CPython 扩展是一个共享库(例如,Windows 上的 DLL、Linux 上的 .so 或 macOS 上的 .dylib)可以在运行时加载到Python解释器中并用于扩展其功能。 lite相机CPython扩展项目的结构如下:

python-lite-camera
│
│── include
│   ├── Camera.h
│   ├── CameraPreview.h
│   ├── stb_image_write.h
│── lib
│   ├── linux
│   │   ├── liblitecam.so
│   ├── macos
│   │   ├── liblitecam.dylib
│   ├── windows
│   │   ├── litecam.dll
│   │   ├── litecam.lib
├── src
│   ├── litecam.cpp
│   ├── pycamera.h
│   ├── pywindow.h
│── litecam
│   ├── __init__.py
│── setup.py
│── MANIFEST.in
│── README.md
登录后复制
登录后复制
登录后复制

说明

  • include:C相机库的头文件。
  • lib:C 相机库的共享库。
  • src:Python相机SDK的源代码。
  • litecam:Python 扩展的入口点。
  • setup.py:构建脚本。
  • MANIFEST.in:包含非Python文件的清单文件。
  • README.md:文档。

为 Python 扩展编写构建脚本 setup.py

在setup.py中添加以下内容:

from setuptools.command import build_ext
from setuptools import setup, Extension
import sys
import os
import io
from setuptools.command.install import install
import shutil
from pathlib import Path

lib_dir = ''

sources = [
    "src/litecam.cpp",
]

include_dirs = [os.path.join(os.path.dirname(__file__), "include")]

libraries = ['litecam']

extra_compile_args = []

if sys.platform == "linux" or sys.platform == "linux2":
    lib_dir = 'lib/linux'
    extra_compile_args = ['-std=c++11']
    extra_link_args = ["-Wl,-rpath=$ORIGIN"]
elif sys.platform == "darwin":
    lib_dir = 'lib/macos'
    extra_compile_args = ['-std=c++11']
    extra_link_args = ["-Wl,-rpath,@loader_path"]
elif sys.platform == "win32":
    lib_dir = 'lib/windows'
    extra_link_args = []

else:
    raise RuntimeError("Unsupported platform")


long_description = io.open("README.md", encoding="utf-8").read()

module_litecam = Extension(
    "litecam",
    sources=sources,
    include_dirs=include_dirs,
    library_dirs=[lib_dir],
    libraries=libraries,
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
)

def copyfiles(src, dst):
    if os.path.isdir(src):
        filelist = os.listdir(src)
        for file in filelist:
            libpath = os.path.join(src, file)
            shutil.copy2(libpath, dst)
    else:
        shutil.copy2(src, dst)


class CustomBuildExt(build_ext.build_ext):
    def run(self):
        build_ext.build_ext.run(self)
        dst = os.path.join(self.build_lib, "litecam")
        copyfiles(lib_dir, dst)
        filelist = os.listdir(self.build_lib)
        for file in filelist:
            filePath = os.path.join(self.build_lib, file)
            if not os.path.isdir(file):
                copyfiles(filePath, dst)
                os.remove(filePath)


class CustomBuildExtDev(build_ext.build_ext):
    def run(self):
        build_ext.build_ext.run(self)
        dev_folder = os.path.join(Path(__file__).parent, 'litecam')
        copyfiles(lib_dir, dev_folder)
        filelist = os.listdir(self.build_lib)
        for file in filelist:
            filePath = os.path.join(self.build_lib, file)
            if not os.path.isdir(file):
                copyfiles(filePath, dev_folder)


class CustomInstall(install):
    def run(self):
        install.run(self)


setup(name='lite-camera',
      version='2.0.1',
      description='LiteCam is a lightweight, cross-platform library for capturing RGB frames from cameras and displaying them. Designed with simplicity and ease of integration in mind, LiteCam supports Windows, Linux and macOS platforms.',
      long_description=long_description,
      long_description_content_type="text/markdown",
      author='yushulx',
      url='https://github.com/yushulx/python-lite-camera',
      license='MIT',
      packages=['litecam'],
      ext_modules=[module_litecam],
      classifiers=[
           "Development Status :: 5 - Production/Stable",
           "Environment :: Console",
           "Intended Audience :: Developers",
          "Intended Audience :: Education",
          "Intended Audience :: Information Technology",
          "Intended Audience :: Science/Research",
          "License :: OSI Approved :: MIT License",
          "Operating System :: Microsoft :: Windows",
          "Operating System :: MacOS",
          "Operating System :: POSIX :: Linux",
          "Programming Language :: Python",
          "Programming Language :: Python :: 3",
          "Programming Language :: Python :: 3 :: Only",
          "Programming Language :: Python :: 3.6",
          "Programming Language :: Python :: 3.7",
          "Programming Language :: Python :: 3.8",
          "Programming Language :: Python :: 3.9",
          "Programming Language :: Python :: 3.10",
          "Programming Language :: Python :: 3.11",
          "Programming Language :: Python :: 3.12",
          "Programming Language :: C++",
          "Programming Language :: Python :: Implementation :: CPython",
          "Topic :: Scientific/Engineering",
          "Topic :: Software Development",
      ],
      cmdclass={
          'install': CustomInstall,
          'build_ext': CustomBuildExt,
          'develop': CustomBuildExtDev},
      )
登录后复制
登录后复制
登录后复制

说明

  • lite-camera:Python 包的名称。
  • ext_modules:CPython 扩展列表。它指定不同平台的源文件、包含目录、库目录、库以及编译/链接标志。
  • 开发:用于开发的自定义命令。它将共享库复制到 litecam 文件夹以方便测试。
  • build_ext:自定义构建过程,将共享库打包到wheel包中。

用 C 语言实现 Python Camera SDK API

pycamera.h 文件定义了用于从相机捕获帧的 PyCamera Python 类,而 pywindow.h 文件定义了用于在窗口中显示帧的 PyWindow Python 类。 litecam.cpp 文件作为 Python 扩展的入口点,其中定义了一些全局方法,并注册了 PyCamera 和 PyWindow 类。

pycamera.h

包括

python-lite-camera
│
│── include
│   ├── Camera.h
│   ├── CameraPreview.h
│   ├── stb_image_write.h
│── lib
│   ├── linux
│   │   ├── liblitecam.so
│   ├── macos
│   │   ├── liblitecam.dylib
│   ├── windows
│   │   ├── litecam.dll
│   │   ├── litecam.lib
├── src
│   ├── litecam.cpp
│   ├── pycamera.h
│   ├── pywindow.h
│── litecam
│   ├── __init__.py
│── setup.py
│── MANIFEST.in
│── README.md
登录后复制
登录后复制
登录后复制
  • Python.h:包含使用 Python C API。
  • structmember.h:提供用于管理对象成员的宏和帮助器。
  • Camera.h:定义 Camera 类,PyCamera 扩展对其进行包装。

PyCamera 结构体定义

from setuptools.command import build_ext
from setuptools import setup, Extension
import sys
import os
import io
from setuptools.command.install import install
import shutil
from pathlib import Path

lib_dir = ''

sources = [
    "src/litecam.cpp",
]

include_dirs = [os.path.join(os.path.dirname(__file__), "include")]

libraries = ['litecam']

extra_compile_args = []

if sys.platform == "linux" or sys.platform == "linux2":
    lib_dir = 'lib/linux'
    extra_compile_args = ['-std=c++11']
    extra_link_args = ["-Wl,-rpath=$ORIGIN"]
elif sys.platform == "darwin":
    lib_dir = 'lib/macos'
    extra_compile_args = ['-std=c++11']
    extra_link_args = ["-Wl,-rpath,@loader_path"]
elif sys.platform == "win32":
    lib_dir = 'lib/windows'
    extra_link_args = []

else:
    raise RuntimeError("Unsupported platform")


long_description = io.open("README.md", encoding="utf-8").read()

module_litecam = Extension(
    "litecam",
    sources=sources,
    include_dirs=include_dirs,
    library_dirs=[lib_dir],
    libraries=libraries,
    extra_compile_args=extra_compile_args,
    extra_link_args=extra_link_args,
)

def copyfiles(src, dst):
    if os.path.isdir(src):
        filelist = os.listdir(src)
        for file in filelist:
            libpath = os.path.join(src, file)
            shutil.copy2(libpath, dst)
    else:
        shutil.copy2(src, dst)


class CustomBuildExt(build_ext.build_ext):
    def run(self):
        build_ext.build_ext.run(self)
        dst = os.path.join(self.build_lib, "litecam")
        copyfiles(lib_dir, dst)
        filelist = os.listdir(self.build_lib)
        for file in filelist:
            filePath = os.path.join(self.build_lib, file)
            if not os.path.isdir(file):
                copyfiles(filePath, dst)
                os.remove(filePath)


class CustomBuildExtDev(build_ext.build_ext):
    def run(self):
        build_ext.build_ext.run(self)
        dev_folder = os.path.join(Path(__file__).parent, 'litecam')
        copyfiles(lib_dir, dev_folder)
        filelist = os.listdir(self.build_lib)
        for file in filelist:
            filePath = os.path.join(self.build_lib, file)
            if not os.path.isdir(file):
                copyfiles(filePath, dev_folder)


class CustomInstall(install):
    def run(self):
        install.run(self)


setup(name='lite-camera',
      version='2.0.1',
      description='LiteCam is a lightweight, cross-platform library for capturing RGB frames from cameras and displaying them. Designed with simplicity and ease of integration in mind, LiteCam supports Windows, Linux and macOS platforms.',
      long_description=long_description,
      long_description_content_type="text/markdown",
      author='yushulx',
      url='https://github.com/yushulx/python-lite-camera',
      license='MIT',
      packages=['litecam'],
      ext_modules=[module_litecam],
      classifiers=[
           "Development Status :: 5 - Production/Stable",
           "Environment :: Console",
           "Intended Audience :: Developers",
          "Intended Audience :: Education",
          "Intended Audience :: Information Technology",
          "Intended Audience :: Science/Research",
          "License :: OSI Approved :: MIT License",
          "Operating System :: Microsoft :: Windows",
          "Operating System :: MacOS",
          "Operating System :: POSIX :: Linux",
          "Programming Language :: Python",
          "Programming Language :: Python :: 3",
          "Programming Language :: Python :: 3 :: Only",
          "Programming Language :: Python :: 3.6",
          "Programming Language :: Python :: 3.7",
          "Programming Language :: Python :: 3.8",
          "Programming Language :: Python :: 3.9",
          "Programming Language :: Python :: 3.10",
          "Programming Language :: Python :: 3.11",
          "Programming Language :: Python :: 3.12",
          "Programming Language :: C++",
          "Programming Language :: Python :: Implementation :: CPython",
          "Topic :: Scientific/Engineering",
          "Topic :: Software Development",
      ],
      cmdclass={
          'install': CustomInstall,
          'build_ext': CustomBuildExt,
          'develop': CustomBuildExtDev},
      )
登录后复制
登录后复制
登录后复制

PyCamera 结构体表示包裹 C Camera 对象的 Python 对象。该处理程序是一个指向 Camera 类实例的指针。

方法

  • PyCamera_dealloc

    #include <Python.h>
    #include <structmember.h>
    #include "Camera.h"
    
    登录后复制
    登录后复制

    解除分配 Camera 对象并释放关联的内存。

  • PyCamera_new

    typedef struct
    {
        PyObject_HEAD Camera *handler;
    } PyCamera;
    
    登录后复制
    登录后复制

    创建 PyCamera 的新实例。它为Python对象分配内存,创建一个新的Camera对象,并将其分配给self->handler。

  • 开放

    static int PyCamera_clear(PyCamera *self)
    {
        if (self->handler)
        {
            delete self->handler;
        }
        return 0;
    }
    
    static void PyCamera_dealloc(PyCamera *self)
    {
        PyCamera_clear(self);
        Py_TYPE(self)->tp_free((PyObject *)self);
    }
    
    
    登录后复制
    登录后复制

    打开指定索引的相机。

  • 列表媒体类型

    static PyObject *PyCamera_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    {
        PyCamera *self;
    
        self = (PyCamera *)type->tp_alloc(type, 0);
        if (self != NULL)
        {
            self->handler = new Camera();
        }
    
        return (PyObject *)self;
    }
    
    
    登录后复制
    登录后复制

    返回支持的媒体类型列表。对于 Windows,它将宽字符串转换为 Python Unicode 对象。

  • 发布

    static PyObject *open(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        int index = 0;
        if (!PyArg_ParseTuple(args, "i", &index))
        {
            return NULL;
        }
    
        bool ret = self->handler->Open(index);
        return Py_BuildValue("i", ret);
    }
    
    登录后复制
    登录后复制

    释放相机。

  • 设置分辨率

    static PyObject *listMediaTypes(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        std::vector<MediaTypeInfo> mediaTypes = self->handler->ListSupportedMediaTypes();
    
        PyObject *pyList = PyList_New(0);
    
        for (size_t i = 0; i < mediaTypes.size(); i++)
        {
            MediaTypeInfo &mediaType = mediaTypes[i];
    
    #ifdef _WIN32
            PyObject *subtypeName = PyUnicode_FromWideChar(mediaType.subtypeName, wcslen(mediaType.subtypeName));
            PyObject *pyMediaType = Py_BuildValue("{s:i,s:i,s:O}",
                                                  "width", mediaType.width,
                                                  "height", mediaType.height,
                                                  "subtypeName", subtypeName);
            if (subtypeName != NULL)
            {
                Py_DECREF(subtypeName);
            }
    
    #else
            PyObject *pyMediaType = Py_BuildValue("{s:i,s:i,s:s}",
                                                  "width", mediaType.width,
                                                  "height", mediaType.height,
                                                  "subtypeName", mediaType.subtypeName);
    #endif
    
            PyList_Append(pyList, pyMediaType);
        }
    
        return pyList;
    }
    
    
    登录后复制
    登录后复制

    设置相机的分辨率。

  • 捕获帧

    static PyObject *release(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        self->handler->Release();
        Py_RETURN_NONE;
    }
    
    登录后复制
    登录后复制

    从相机捕获帧并将 RGB 数据作为 Python 字节数组返回。

  • getWidth 和 getHeight

    static PyObject *setResolution(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
        int width = 0, height = 0;
        if (!PyArg_ParseTuple(args, "ii", &width, &height))
        {
            return NULL;
        }
        int ret = self->handler->SetResolution(width, height);
        return Py_BuildValue("i", ret);
    }
    
    登录后复制
    登录后复制

    返回捕获帧的宽度和高度。

实例方法

static PyObject *captureFrame(PyObject *obj, PyObject *args)
{
    PyCamera *self = (PyCamera *)obj;

    FrameData frame = self->handler->CaptureFrame();
    if (frame.rgbData)
    {
        PyObject *rgbData = PyByteArray_FromStringAndSize((const char *)frame.rgbData, frame.size);
        PyObject *pyFrame = Py_BuildValue("iiiO", frame.width, frame.height, frame.size, rgbData);
        ReleaseFrame(frame);

        return pyFrame;
    }
    else
    {
        Py_RETURN_NONE;
    }
}
登录后复制
登录后复制

定义 PyCamera Python 对象上可用的方法。这些方法与上面定义的相应 C 函数相关联。

PyCamera类型

static PyObject *getWidth(PyObject *obj, PyObject *args)
{
    PyCamera *self = (PyCamera *)obj;

    int width = self->handler->frameWidth;
    return Py_BuildValue("i", width);
}

static PyObject *getHeight(PyObject *obj, PyObject *args)
{
    PyCamera *self = (PyCamera *)obj;

    int height = self->handler->frameHeight;
    return Py_BuildValue("i", height);
}
登录后复制
登录后复制

定义 PyCamera 类型,包括其方法、内存分配、释放和其他行为。

pywindow.h

包括

static PyMethodDef instance_methods[] = {
    {"open", open, METH_VARARGS, NULL},
    {"listMediaTypes", listMediaTypes, METH_VARARGS, NULL},
    {"release", release, METH_VARARGS, NULL},
    {"setResolution", setResolution, METH_VARARGS, NULL},
    {"captureFrame", captureFrame, METH_VARARGS, NULL},
    {"getWidth", getWidth, METH_VARARGS, NULL},
    {"getHeight", getHeight, METH_VARARGS, NULL},
    {NULL, NULL, 0, NULL}};

登录后复制
登录后复制
  • Python.h:使用 Python C API 所需的。
  • structmember.h:提供管理对象成员的宏。
  • CameraPreview.h:定义CameraWindow类,用于显示相机预览并与其交互。

PyWindow 结构体定义

static PyTypeObject PyCameraType = {
    PyVarObject_HEAD_INIT(NULL, 0) "litecam.PyCamera", /* tp_name */
    sizeof(PyCamera),                                  /* tp_basicsize */
    0,                                                 /* tp_itemsize */
    (destructor)PyCamera_dealloc,                      /* tp_dealloc */
    0,                                                 /* tp_print */
    0,                                                 /* tp_getattr */
    0,                                                 /* tp_setattr */
    0,                                                 /* tp_reserved */
    0,                                                 /* tp_repr */
    0,                                                 /* tp_as_number */
    0,                                                 /* tp_as_sequence */
    0,                                                 /* tp_as_mapping */
    0,                                                 /* tp_hash  */
    0,                                                 /* tp_call */
    0,                                                 /* tp_str */
    PyObject_GenericGetAttr,                           /* tp_getattro */
    PyObject_GenericSetAttr,                           /* tp_setattro */
    0,                                                 /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,          /*tp_flags*/
    "PyCamera",                                        /* tp_doc */
    0,                                                 /* tp_traverse */
    0,                                                 /* tp_clear */
    0,                                                 /* tp_richcompare */
    0,                                                 /* tp_weaklistoffset */
    0,                                                 /* tp_iter */
    0,                                                 /* tp_iternext */
    instance_methods,                                  /* tp_methods */
    0,                                                 /* tp_members */
    0,                                                 /* tp_getset */
    0,                                                 /* tp_base */
    0,                                                 /* tp_dict */
    0,                                                 /* tp_descr_get */
    0,                                                 /* tp_descr_set */
    0,                                                 /* tp_dictoffset */
    0,                                                 /* tp_init */
    0,                                                 /* tp_alloc */
    PyCamera_new,                                      /* tp_new */
};

登录后复制

定义一个包装 C CameraWindow 对象的 PyWindow 结构。 handler 成员指向 CameraWindow 的一个实例。

PyWindow 对象的方法

  • PyWindow_dealloc

    #include <Python.h>
    #include <structmember.h>
    #include "CameraPreview.h"
    
    登录后复制

    取消分配CameraWindow对象并释放内存。

  • PyWindow_new

    typedef struct
    {
        PyObject_HEAD CameraWindow *handler;
    } PyWindow;
    
    
    登录后复制

    创建 PyWindow 的新实例。它为Python对象分配内存,创建一个新的CameraWindow对象,并将其分配给self->handler。

  • 等待键

    python-lite-camera
    │
    │── include
    │   ├── Camera.h
    │   ├── CameraPreview.h
    │   ├── stb_image_write.h
    │── lib
    │   ├── linux
    │   │   ├── liblitecam.so
    │   ├── macos
    │   │   ├── liblitecam.dylib
    │   ├── windows
    │   │   ├── litecam.dll
    │   │   ├── litecam.lib
    ├── src
    │   ├── litecam.cpp
    │   ├── pycamera.h
    │   ├── pywindow.h
    │── litecam
    │   ├── __init__.py
    │── setup.py
    │── MANIFEST.in
    │── README.md
    
    登录后复制
    登录后复制
    登录后复制

    等待按键事件,如果按键与指定字符匹配则返回 False。 False 意味着应用程序应该退出。

  • showFrame

    from setuptools.command import build_ext
    from setuptools import setup, Extension
    import sys
    import os
    import io
    from setuptools.command.install import install
    import shutil
    from pathlib import Path
    
    lib_dir = ''
    
    sources = [
        "src/litecam.cpp",
    ]
    
    include_dirs = [os.path.join(os.path.dirname(__file__), "include")]
    
    libraries = ['litecam']
    
    extra_compile_args = []
    
    if sys.platform == "linux" or sys.platform == "linux2":
        lib_dir = 'lib/linux'
        extra_compile_args = ['-std=c++11']
        extra_link_args = ["-Wl,-rpath=$ORIGIN"]
    elif sys.platform == "darwin":
        lib_dir = 'lib/macos'
        extra_compile_args = ['-std=c++11']
        extra_link_args = ["-Wl,-rpath,@loader_path"]
    elif sys.platform == "win32":
        lib_dir = 'lib/windows'
        extra_link_args = []
    
    else:
        raise RuntimeError("Unsupported platform")
    
    
    long_description = io.open("README.md", encoding="utf-8").read()
    
    module_litecam = Extension(
        "litecam",
        sources=sources,
        include_dirs=include_dirs,
        library_dirs=[lib_dir],
        libraries=libraries,
        extra_compile_args=extra_compile_args,
        extra_link_args=extra_link_args,
    )
    
    def copyfiles(src, dst):
        if os.path.isdir(src):
            filelist = os.listdir(src)
            for file in filelist:
                libpath = os.path.join(src, file)
                shutil.copy2(libpath, dst)
        else:
            shutil.copy2(src, dst)
    
    
    class CustomBuildExt(build_ext.build_ext):
        def run(self):
            build_ext.build_ext.run(self)
            dst = os.path.join(self.build_lib, "litecam")
            copyfiles(lib_dir, dst)
            filelist = os.listdir(self.build_lib)
            for file in filelist:
                filePath = os.path.join(self.build_lib, file)
                if not os.path.isdir(file):
                    copyfiles(filePath, dst)
                    os.remove(filePath)
    
    
    class CustomBuildExtDev(build_ext.build_ext):
        def run(self):
            build_ext.build_ext.run(self)
            dev_folder = os.path.join(Path(__file__).parent, 'litecam')
            copyfiles(lib_dir, dev_folder)
            filelist = os.listdir(self.build_lib)
            for file in filelist:
                filePath = os.path.join(self.build_lib, file)
                if not os.path.isdir(file):
                    copyfiles(filePath, dev_folder)
    
    
    class CustomInstall(install):
        def run(self):
            install.run(self)
    
    
    setup(name='lite-camera',
          version='2.0.1',
          description='LiteCam is a lightweight, cross-platform library for capturing RGB frames from cameras and displaying them. Designed with simplicity and ease of integration in mind, LiteCam supports Windows, Linux and macOS platforms.',
          long_description=long_description,
          long_description_content_type="text/markdown",
          author='yushulx',
          url='https://github.com/yushulx/python-lite-camera',
          license='MIT',
          packages=['litecam'],
          ext_modules=[module_litecam],
          classifiers=[
               "Development Status :: 5 - Production/Stable",
               "Environment :: Console",
               "Intended Audience :: Developers",
              "Intended Audience :: Education",
              "Intended Audience :: Information Technology",
              "Intended Audience :: Science/Research",
              "License :: OSI Approved :: MIT License",
              "Operating System :: Microsoft :: Windows",
              "Operating System :: MacOS",
              "Operating System :: POSIX :: Linux",
              "Programming Language :: Python",
              "Programming Language :: Python :: 3",
              "Programming Language :: Python :: 3 :: Only",
              "Programming Language :: Python :: 3.6",
              "Programming Language :: Python :: 3.7",
              "Programming Language :: Python :: 3.8",
              "Programming Language :: Python :: 3.9",
              "Programming Language :: Python :: 3.10",
              "Programming Language :: Python :: 3.11",
              "Programming Language :: Python :: 3.12",
              "Programming Language :: C++",
              "Programming Language :: Python :: Implementation :: CPython",
              "Topic :: Scientific/Engineering",
              "Topic :: Software Development",
          ],
          cmdclass={
              'install': CustomInstall,
              'build_ext': CustomBuildExt,
              'develop': CustomBuildExtDev},
          )
    
    登录后复制
    登录后复制
    登录后复制

    在窗口中显示一个框架。

  • 绘制轮廓

    #include <Python.h>
    #include <structmember.h>
    #include "Camera.h"
    
    登录后复制
    登录后复制

    在框架上绘制轮廓(一系列点)。

  • 绘制文本

    typedef struct
    {
        PyObject_HEAD Camera *handler;
    } PyCamera;
    
    登录后复制
    登录后复制

    在框架上绘制文本。

窗口实例方法

static int PyCamera_clear(PyCamera *self)
{
    if (self->handler)
    {
        delete self->handler;
    }
    return 0;
}

static void PyCamera_dealloc(PyCamera *self)
{
    PyCamera_clear(self);
    Py_TYPE(self)->tp_free((PyObject *)self);
}

登录后复制
登录后复制

定义 PyWindow Python 对象上可用的方法。

PyWindow类型

static PyObject *PyCamera_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    PyCamera *self;

    self = (PyCamera *)type->tp_alloc(type, 0);
    if (self != NULL)
    {
        self->handler = new Camera();
    }

    return (PyObject *)self;
}

登录后复制
登录后复制

定义 PyWindow 类型,包括其方法、内存分配、释放和其他行为。

litecam.cpp

static PyObject *open(PyObject *obj, PyObject *args)
{
    PyCamera *self = (PyCamera *)obj;

    int index = 0;
    if (!PyArg_ParseTuple(args, "i", &index))
    {
        return NULL;
    }

    bool ret = self->handler->Open(index);
    return Py_BuildValue("i", ret);
}
登录后复制
登录后复制

说明

  • getDeviceList:返回可用摄像头的列表。
  • saveJpeg:将帧保存为 JPEG 图像。
  • PyInit_litecam:初始化litecam模块并注册PyCamera和PyWindow类型。

构建 Python 相机 SDK

  • 开发模式

    static PyObject *listMediaTypes(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        std::vector<MediaTypeInfo> mediaTypes = self->handler->ListSupportedMediaTypes();
    
        PyObject *pyList = PyList_New(0);
    
        for (size_t i = 0; i < mediaTypes.size(); i++)
        {
            MediaTypeInfo &mediaType = mediaTypes[i];
    
    #ifdef _WIN32
            PyObject *subtypeName = PyUnicode_FromWideChar(mediaType.subtypeName, wcslen(mediaType.subtypeName));
            PyObject *pyMediaType = Py_BuildValue("{s:i,s:i,s:O}",
                                                  "width", mediaType.width,
                                                  "height", mediaType.height,
                                                  "subtypeName", subtypeName);
            if (subtypeName != NULL)
            {
                Py_DECREF(subtypeName);
            }
    
    #else
            PyObject *pyMediaType = Py_BuildValue("{s:i,s:i,s:s}",
                                                  "width", mediaType.width,
                                                  "height", mediaType.height,
                                                  "subtypeName", mediaType.subtypeName);
    #endif
    
            PyList_Append(pyList, pyMediaType);
        }
    
        return pyList;
    }
    
    
    登录后复制
    登录后复制
  • 轮组

    static PyObject *release(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        self->handler->Release();
        Py_RETURN_NONE;
    }
    
    登录后复制
    登录后复制
  • 来源分布

    static PyObject *setResolution(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
        int width = 0, height = 0;
        if (!PyArg_ParseTuple(args, "ii", &width, &height))
        {
            return NULL;
        }
        int ret = self->handler->SetResolution(width, height);
        return Py_BuildValue("i", ret);
    }
    
    登录后复制
    登录后复制

实现 Python 多条码扫描器的步骤

  1. 安装Python相机SDK和Dynamsoft Barcode Reader SDK:

    static PyObject *captureFrame(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        FrameData frame = self->handler->CaptureFrame();
        if (frame.rgbData)
        {
            PyObject *rgbData = PyByteArray_FromStringAndSize((const char *)frame.rgbData, frame.size);
            PyObject *pyFrame = Py_BuildValue("iiiO", frame.width, frame.height, frame.size, rgbData);
            ReleaseFrame(frame);
    
            return pyFrame;
        }
        else
        {
            Py_RETURN_NONE;
        }
    }
    
    登录后复制
    登录后复制
  2. 获取 Dynamsoft Barcode Reader 30 天免费试用许可证。

  3. 创建用于多条码扫描的 Python 脚本:

    static PyObject *getWidth(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        int width = self->handler->frameWidth;
        return Py_BuildValue("i", width);
    }
    
    static PyObject *getHeight(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        int height = self->handler->frameHeight;
        return Py_BuildValue("i", height);
    }
    
    登录后复制
    登录后复制

    将 LICENSE-KEY 替换为您的 Dynamsoft Barcode Reader 许可证密钥。

  4. 运行脚本:

    static PyMethodDef instance_methods[] = {
        {"open", open, METH_VARARGS, NULL},
        {"listMediaTypes", listMediaTypes, METH_VARARGS, NULL},
        {"release", release, METH_VARARGS, NULL},
        {"setResolution", setResolution, METH_VARARGS, NULL},
        {"captureFrame", captureFrame, METH_VARARGS, NULL},
        {"getWidth", getWidth, METH_VARARGS, NULL},
        {"getHeight", getHeight, METH_VARARGS, NULL},
        {NULL, NULL, 0, NULL}};
    
    
    登录后复制
    登录后复制

    Building a Python Camera SDK and Using It for Multi-Barcode Scanning

源代码

https://github.com/yushulx/python-lite-camera

以上是构建 Python 相机 SDK 并使用它进行多条码扫描的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板