찾다
백엔드 개발파이썬 튜토리얼Python 카메라 SDK 구축 및 다중 바코드 스캐닝에 사용

이제 Windows, LinuxmacOS용 경량 C 카메라 SDK가 완성되었으므로 이를 다른 고급 프로그래밍 언어에 통합할 수 있습니다. 이 글에서는 C 카메라 라이브러리를 기반으로 Python 카메라 SDK를 구축하고 Dynamsoft Barcode Reader SDK

를 사용하여 다중 바코드 스캐닝에 사용하는 방법을 살펴보겠습니다.

Python 다중 바코드 스캐너 데모 비디오

CPython 확장 프로젝트 스캐폴딩

CPython 확장은 공유 라이브러리(예: Windows의 DLL, Linux의 .so, macOS의 .dylib)입니다. 런타임 시 Python 인터프리터에 로드되어 기능을 확장하는 데 사용할 수 있습니다. 라이트 카메라 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: 공유 라이브러리를 휠 패키지로 패키징하기 위한 빌드 프로세스를 사용자 정의합니다.

C에서 Python 카메라 SDK API 구현

pycamera.h 파일은 카메라에서 프레임을 캡처하기 위한 PyCamera Python 클래스를 정의하고, pywindow.h 파일은 창에 프레임을 표시하기 위한 PyWindow Python 클래스를 정의합니다. litecam.cpp 파일은 일부 전역 메소드가 정의되고 PyCamera 및 PyWindow 클래스가 등록되는 Python 확장의 진입점 역할을 합니다.

파이카메라.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: PyCamera 확장이 래핑하는 Camera 클래스를 정의합니다.

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"
    </structmember.h></python.h>

    카메라 개체 할당을 해제하고 관련 메모리를 해제합니다.

  • 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 유니코드 객체로 변환합니다.

  • 출시

    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 
    
    
    <p>카메라의 해상도를 설정합니다.</p>
    </mediatypeinfo>
  • 캡처프레임

    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 함수와 연관되어 있습니다.

파이카메라 유형

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 구조체를 정의합니다. 핸들러 멤버는 CameraWindow의 인스턴스를 가리킵니다.

PyWindow 객체에 대한 메서드

  • PyWindow_dealloc

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

    CameraWindow 객체 할당을 해제하고 메모리를 해제합니다.

  • PyWindow_new

    typedef struct
    {
        PyObject_HEAD CameraWindow *handler;
    } PyWindow;
    
    

    PyWindow의 새 인스턴스를 생성합니다. Python 객체에 메모리를 할당하고 새 CameraWindow 객체를 생성한 다음 이를 자체>핸들러에 할당합니다.

  • 잠깐키

    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는 애플리케이션이 종료되어야 함을 의미합니다.

  • 쇼프레임

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

    창에 프레임을 표시합니다.

  • drawContour

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

    프레임에 윤곽선(일련의 점)을 그립니다.

  • drawText

    typedef struct
    {
        PyObject_HEAD Camera *handler;
    } PyCamera;
    

    프레임에 텍스트를 그립니다.

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

PyWindow Python 객체에서 사용할 수 있는 메서드를 정의합니다.

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

메서드, 메모리 할당, 할당 해제 및 기타 동작을 포함하여 PyWindow 유형을 정의합니다.

라이트캠.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 
    
    </mediatypeinfo>
  • 휠 패키지

    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 바코드 리더 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까?HTML을 구문 분석하기 위해 아름다운 수프를 어떻게 사용합니까?Mar 10, 2025 pm 06:54 PM

이 기사에서는 HTML을 구문 분석하기 위해 파이썬 라이브러리 인 아름다운 수프를 사용하는 방법을 설명합니다. 데이터 추출, 다양한 HTML 구조 및 오류 처리 및 대안 (SEL과 같은 Find (), find_all (), select () 및 get_text ()와 같은 일반적인 방법을 자세히 설명합니다.

파이썬의 수학 모듈 : 통계파이썬의 수학 모듈 : 통계Mar 09, 2025 am 11:40 AM

Python의 통계 모듈은 강력한 데이터 통계 분석 기능을 제공하여 생물 통계 및 비즈니스 분석과 같은 데이터의 전반적인 특성을 빠르게 이해할 수 있도록 도와줍니다. 데이터 포인트를 하나씩 보는 대신 평균 또는 분산과 같은 통계를보고 무시할 수있는 원래 데이터에서 트렌드와 기능을 발견하고 대형 데이터 세트를보다 쉽고 효과적으로 비교하십시오. 이 튜토리얼은 평균을 계산하고 데이터 세트의 분산 정도를 측정하는 방법을 설명합니다. 달리 명시되지 않는 한,이 모듈의 모든 함수는 단순히 평균을 합산하는 대신 평균 () 함수의 계산을 지원합니다. 부동 소수점 번호도 사용할 수 있습니다. 무작위로 가져옵니다 수입 통계 Fracti에서

Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까?Tensorflow 또는 Pytorch로 딥 러닝을 수행하는 방법은 무엇입니까?Mar 10, 2025 pm 06:52 PM

이 기사는 딥 러닝을 위해 텐서 플로와 Pytorch를 비교합니다. 데이터 준비, 모델 구축, 교육, 평가 및 배포와 관련된 단계에 대해 자세히 설명합니다. 프레임 워크, 특히 계산 포도와 관련하여 주요 차이점

파이썬 객체의 직렬화 및 사제화 : 1 부파이썬 객체의 직렬화 및 사제화 : 1 부Mar 08, 2025 am 09:39 AM

파이썬 객체의 직렬화 및 사막화는 사소한 프로그램의 주요 측면입니다. 무언가를 Python 파일에 저장하면 구성 파일을 읽거나 HTTP 요청에 응답하는 경우 객체 직렬화 및 사태화를 수행합니다. 어떤 의미에서, 직렬화와 사제화는 세계에서 가장 지루한 것들입니다. 이 모든 형식과 프로토콜에 대해 누가 걱정합니까? 일부 파이썬 객체를 지속하거나 스트리밍하여 나중에 완전히 검색하려고합니다. 이것은 세상을 개념적 차원에서 볼 수있는 좋은 방법입니다. 그러나 실제 수준에서 선택한 직렬화 체계, 형식 또는 프로토콜은 속도, 보안, 유지 보수 상태 및 프로그램의 기타 측면을 결정할 수 있습니다.

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까?Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까?Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

아름다운 수프로 파이썬에서 웹 페이지를 긁어 내기 : 검색 및 DOM 수정아름다운 수프로 파이썬에서 웹 페이지를 긁어 내기 : 검색 및 DOM 수정Mar 08, 2025 am 10:36 AM

이 튜토리얼은 간단한 나무 탐색을 넘어서 DOM 조작에 중점을 둔 아름다운 수프에 대한 이전 소개를 바탕으로합니다. HTML 구조를 수정하기위한 효율적인 검색 방법과 기술을 탐색하겠습니다. 일반적인 DOM 검색 방법 중 하나는 EX입니다

인기있는 파이썬 라이브러리와 그 용도는 무엇입니까?인기있는 파이썬 라이브러리와 그 용도는 무엇입니까?Mar 21, 2025 pm 06:46 PM

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

Python으로 명령 줄 인터페이스 (CLI)를 만드는 방법은 무엇입니까?Python으로 명령 줄 인터페이스 (CLI)를 만드는 방법은 무엇입니까?Mar 10, 2025 pm 06:48 PM

이 기사는 Python 개발자가 CLIS (Command-Line Interfaces) 구축을 안내합니다. Typer, Click 및 Argparse와 같은 라이브러리를 사용하여 입력/출력 처리를 강조하고 CLI 유용성을 향상시키기 위해 사용자 친화적 인 디자인 패턴을 홍보하는 세부 정보.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.