cari
Rumahpembangunan bahagian belakangTutorial PythonMembina SDK Kamera Python dan Menggunakannya untuk Pengimbasan Berbilang Kod Bar

Sekarang SDK kamera C ringan telah lengkap untuk Windows, Linux dan macOS, kami boleh menyepadukannya ke dalam bahasa pengaturcaraan peringkat tinggi yang lain. Dalam artikel ini, kami akan meneroka cara membina SDK kamera Python berdasarkan pustaka kamera C dan menggunakannya untuk pengimbasan berbilang kod bar dengan SDK Pembaca Kod Bar Dynamsoft.

Video Demo Pengimbas Berbilang Kod Bar Python

Perancah Projek Sambungan CPython

Sambungan CPython ialah pustaka kongsi (cth., DLL pada Windows, .so pada Linux atau .dylib pada macOS) yang boleh dimuatkan ke dalam penterjemah Python semasa runtime dan digunakan untuk melanjutkan fungsinya. Struktur projek sambungan CPython kamera ringan adalah seperti berikut:

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

Penjelasan:

  • termasuk: Fail pengepala pustaka kamera C.
  • lib: Pustaka kongsi pustaka kamera C.
  • src: Kod sumber SDK kamera Python.
  • litecam: Titik masuk sambungan Python.
  • setup.py: Skrip binaan.
  • MANIFEST.in: Fail manifes untuk memasukkan fail bukan Python.
  • README.md: Dokumentasi.

Menulis Build Script setup.py untuk Sambungan Python

Tambah kandungan berikut pada 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},
      )

Penjelasan:

  • lite-camera: Nama pakej Python.
  • ext_modules: Senarai sambungan CPython. Ia menentukan fail sumber, termasuk direktori, direktori perpustakaan, pustaka dan bendera kompil/pautan untuk platform yang berbeza.
  • membangunkan: Perintah tersuai untuk pembangunan. Ia menyalin perpustakaan kongsi ke folder litecam untuk ujian mudah.
  • build_ext: Menyesuaikan proses binaan untuk membungkus perpustakaan kongsi ke dalam pakej roda.

Melaksanakan API SDK Kamera Python dalam C

Fail pycamera.h mentakrifkan kelas Python PyCamera untuk menangkap bingkai daripada kamera, manakala fail pywindow.h mentakrifkan kelas Python PyWindow untuk memaparkan bingkai dalam tetingkap. Fail litecam.cpp berfungsi sebagai titik masuk untuk sambungan Python, di mana beberapa kaedah global ditakrifkan, dan kelas PyCamera dan PyWindow didaftarkan.

pycamera.h

Termasuk

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: Disertakan untuk menggunakan API Python C.
  • structmember.h: Menyediakan makro dan pembantu untuk mengurus ahli objek.
  • Camera.h: Mentakrifkan kelas Kamera, yang dibungkus oleh sambungan PyCamera.

Definisi Struktur 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},
      )

Struktur PyCamera mewakili objek Python yang melilit objek C Camera. Pengendali ialah penunjuk kepada contoh kelas Kamera.

Kaedah

  • PyCamera_dealloc

    #include <python.h>
    #include <structmember.h>
    #include "Camera.h"
    </structmember.h></python.h>

    Mengagihkan objek Kamera dan melepaskan memori yang berkaitan.

  • PyCamera_new

    typedef struct
    {
        PyObject_HEAD Camera *handler;
    } PyCamera;
    

    Mencipta contoh baharu PyCamera. Ia memperuntukkan memori untuk objek Python, mencipta objek Kamera baharu dan menyerahkannya kepada pengendali sendiri.

  • terbuka

    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);
    }
    
    

    Membuka kamera dengan indeks yang ditentukan.

  • listMediaTypes

    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;
    }
    
    

    Mengembalikan senarai jenis media yang disokong. Untuk Windows, ia menukar rentetan aksara lebar kepada objek Unicode Python.

  • lepaskan

    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);
    }
    

    Melepaskan kamera.

  • setResolution

    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 
    
    
    <p>Menetapkan resolusi kamera.</p>
    </mediatypeinfo>
  • captureFrame

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

    Merakam bingkai daripada kamera dan mengembalikan data RGB sebagai tatasusunan bait Python.

  • getWidth dan 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);
    }
    

    Mengembalikan lebar dan ketinggian bingkai yang ditangkap.

contoh_kaedah

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;
    }
}

Mentakrifkan kaedah yang tersedia pada objek PyCamera Python. Kaedah ini dikaitkan dengan fungsi C sepadan yang ditakrifkan di atas.

PyCameraType

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);
}

Mentakrifkan jenis PyCamera, termasuk kaedahnya, peruntukan memori, deallocation dan gelagat lain.

pywindow.h

Termasuk

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: Diperlukan untuk menggunakan Python C API.
  • structmember.h: Menyediakan makro untuk mengurus ahli objek.
  • CameraPreview.h: Mentakrifkan kelas CameraWindow, yang digunakan untuk memaparkan pratonton kamera dan berinteraksi dengannya.

Definisi Struktur 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 */
};

Mentakrifkan struct PyWindow yang membalut objek C CameraWindow. Ahli pengendali menunjuk pada contoh CameraWindow.

Kaedah untuk Objek PyWindow

  • PyWindow_dealloc

    #include <python.h>
    #include <structmember.h>
    #include "CameraPreview.h"
    </structmember.h></python.h>

    Mengagihkan objek CameraWindow dan melepaskan memori.

  • PyWindow_new

    typedef struct
    {
        PyObject_HEAD CameraWindow *handler;
    } PyWindow;
    
    

    Mencipta tika baharu PyWindow. Ia memperuntukkan memori untuk objek Python, mencipta objek CameraWindow baharu dan menugaskannya kepada pengendali diri>.

  • Kunci tunggu

    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
    

    Menunggu acara tekan kekunci dan mengembalikan False jika kekunci sepadan dengan aksara yang ditentukan. False bermaksud aplikasi harus keluar.

  • Rangka persembahan

    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},
          )
    

    Memaparkan bingkai dalam tetingkap.

  • drawContour

    #include <python.h>
    #include <structmember.h>
    #include "Camera.h"
    </structmember.h></python.h>

    Melukis kontur (siri titik) pada bingkai.

  • drawTeks

    typedef struct
    {
        PyObject_HEAD Camera *handler;
    } PyCamera;
    

    Melukis teks pada bingkai.

window_instance_methods

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);
}

Mentakrifkan kaedah yang tersedia pada objek Python PyWindow.

PyWindowType

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;
}

Mentakrifkan jenis PyWindow, termasuk kaedahnya, peruntukan memori, deallocation dan gelagat lain.

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);
}

Penjelasan:

  • getDeviceList: Mengembalikan senarai kamera yang tersedia.
  • saveJpeg: Menyimpan bingkai sebagai imej JPEG.
  • PyInit_litecam: Memulakan modul litecam dan mendaftarkan jenis PyCamera dan PyWindow.

Membina SDK Kamera Python

  • Mod Pembangunan

    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 
    
    </mediatypeinfo>
  • Pakej Roda

    static PyObject *release(PyObject *obj, PyObject *args)
    {
        PyCamera *self = (PyCamera *)obj;
    
        self->handler->Release();
        Py_RETURN_NONE;
    }
    
  • Pengagihan Sumber

    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);
    }
    

Langkah-langkah untuk Melaksanakan Pengimbas Berbilang Kod Bar Python

  1. Pasang SDK kamera Python dan SDK Pembaca Kod Bar Dynamsoft:

    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. Dapatkan lesen percubaan percuma selama 30 hari untuk Pembaca Kod Bar Dynamsoft.

  3. Buat skrip Python untuk pengimbasan berbilang kod bar:

    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);
    }
    

    Ganti LESEN-KUNCI dengan kunci lesen Pembaca Kod Bar Dynamsoft anda.

  4. Jalankan skrip:

    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

Kod Sumber

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

Atas ialah kandungan terperinci Membina SDK Kamera Python dan Menggunakannya untuk Pengimbasan Berbilang Kod Bar. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Bagaimana anda membuat tatasusunan pelbagai dimensi menggunakan numpy?Bagaimana anda membuat tatasusunan pelbagai dimensi menggunakan numpy?Apr 29, 2025 am 12:27 AM

Buat tatasusunan pelbagai dimensi dengan numpy dapat dicapai melalui langkah-langkah berikut: 1) Gunakan fungsi numpy.array () untuk membuat array, seperti Np.Array ([[1,2,3], [4,5,6]]) untuk membuat array 2D; 2) Gunakan np.zeros (), np.ones (), np.random.random () dan fungsi lain untuk membuat array yang diisi dengan nilai tertentu; 3) Memahami sifat bentuk dan saiz array untuk memastikan bahawa panjang sub-array adalah konsisten dan mengelakkan kesilapan; 4) Gunakan fungsi np.reshape () untuk mengubah bentuk array; 5) Perhatikan penggunaan memori untuk memastikan bahawa kod itu jelas dan cekap.

Terangkan konsep 'penyiaran' dalam array Numpy.Terangkan konsep 'penyiaran' dalam array Numpy.Apr 29, 2025 am 12:23 AM

Broadcastinginginnumpyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.itsImplifiescode, enhancesreadability, andboostsperformance.here'showitworks: 1) smallerarraysarepaddedwithonestomatchdimensions.2) CompatibeSt

Terangkan cara memilih antara senarai, array.array, dan array numpy untuk penyimpanan data.Terangkan cara memilih antara senarai, array.array, dan array numpy untuk penyimpanan data.Apr 29, 2025 am 12:20 AM

Forpythondatastorage, chooselistsforflexabilityWithMixedDatatypes, array.arrayformemory-efficienthomogeneousnumericaldata, andnumpyarraysforadvancednumericalcomputing.listsareversatileButlessefficefientfientfientfientfientfientfientfientfientfientfientfientforydodeSforayDataSetSetShiSforayDataSetSetShiSforayDataSetSetShiSforayDataSetSetShoFficeSforaydataSetShoSforayDataSetsforayDataSetsforayDataSetsforaydataSetShiSforayDodeSforayDodeSforaydataSetRaydataSetRaydataSetRaydataSet

Berikan contoh senario di mana menggunakan senarai python akan lebih sesuai daripada menggunakan array.Berikan contoh senario di mana menggunakan senarai python akan lebih sesuai daripada menggunakan array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1) listscanholdelementsofdifferenttypes, 2) thearedynamic, membolehkanEaseasyAdditionsandremoVals, 3) theofferintuitiitiveoperationslikeslicing, tetapi4).

Bagaimana anda mengakses elemen dalam pelbagai python?Bagaimana anda mengakses elemen dalam pelbagai python?Apr 29, 2025 am 12:11 AM

ToAccessElementsInapyThonArray, useIndexing: my_array [2] AccessestHeTheRdeLement, returning3.pythonuseszero-berasaskanIndexing.1) USE sitiveandnegativeindexing: my_list [0] forthefirstelement, my_list [-1] forthelast.2) menggunakanSlicingForarangange: my_list [1: 5] ekstrakSelemen

Adakah pemahaman tuple mungkin di Python? Jika ya, bagaimana dan jika tidak mengapa?Adakah pemahaman tuple mungkin di Python? Jika ya, bagaimana dan jika tidak mengapa?Apr 28, 2025 pm 04:34 PM

Artikel membincangkan kemustahilan pemahaman tuple di Python kerana kekaburan sintaks. Alternatif seperti menggunakan tuple () dengan ekspresi penjana dicadangkan untuk mencipta tupel dengan cekap. (159 aksara)

Apakah modul dan pakej dalam Python?Apakah modul dan pakej dalam Python?Apr 28, 2025 pm 04:33 PM

Artikel ini menerangkan modul dan pakej dalam Python, perbezaan, dan penggunaannya. Modul adalah fail tunggal, manakala pakej adalah direktori dengan fail __init__.py, menganjurkan modul yang berkaitan secara hierarki.

Apa itu Docstring dalam Python?Apa itu Docstring dalam Python?Apr 28, 2025 pm 04:30 PM

Artikel membincangkan docstrings dalam python, penggunaan, dan faedah mereka. Isu Utama: Kepentingan Docstrings untuk Dokumentasi Kod dan Kebolehcapaian.

See all articles

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

Video Face Swap

Video Face Swap

Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Alat panas

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Penyesuai Pelayan SAP NetWeaver untuk Eclipse

Penyesuai Pelayan SAP NetWeaver untuk Eclipse

Integrasikan Eclipse dengan pelayan aplikasi SAP NetWeaver.

Muat turun versi mac editor Atom

Muat turun versi mac editor Atom

Editor sumber terbuka yang paling popular

SecLists

SecLists

SecLists ialah rakan penguji keselamatan muktamad. Ia ialah koleksi pelbagai jenis senarai yang kerap digunakan semasa penilaian keselamatan, semuanya di satu tempat. SecLists membantu menjadikan ujian keselamatan lebih cekap dan produktif dengan menyediakan semua senarai yang mungkin diperlukan oleh penguji keselamatan dengan mudah. Jenis senarai termasuk nama pengguna, kata laluan, URL, muatan kabur, corak data sensitif, cangkerang web dan banyak lagi. Penguji hanya boleh menarik repositori ini ke mesin ujian baharu dan dia akan mempunyai akses kepada setiap jenis senarai yang dia perlukan.

SublimeText3 Linux versi baharu

SublimeText3 Linux versi baharu

SublimeText3 Linux versi terkini