轻松使用OpenCV Python控制Webcam,读取Barcode

虽然手机上Barcode应用已经非常流行,但是工作的时候还是用Webcam比较方便。比如需要检测Barcode,我只需要拿Webcam对着电脑屏幕或者纸张扫一下就可以了。今天分享下如何轻松使用OpenCV控制Webcam,以及如何获取一帧图像做Barcode检测。

参考原文:Reading Barcode with Webcam in OpenCV and Python

作者:Xiao Ling

翻译:yushulx

软件安装

  • Dynamsoft Barcode SDK: http://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx
  • Python: https://www.python.org/ftp/python/
  • NumPy: http://sourceforge.net/projects/numpy/files/NumPy/
  • SciPy: http://sourceforge.net/projects/scipy/files/scipy/
  • OpenCV: http://sourceforge.net/projects/opencvlibrary/files/opencv-win/

控制Webcam,读取Barcode

基本步骤:

  1. 拷贝<opencv_installation_dir>\build\python\2.7\x86\cv2.pyd到 <Python27>\Lib\site-packages\cv2.pyd。
  2. 创建一个工程目录。
  3. 构建Python Barcode动态链接库。
  4. 拷贝所有依赖的动态链接库到工程目录。
  5. 把Webcam连接到PC上。
  6. 创建Python脚本控制Webcam,捕捉Webcam图像,并使用Python Barcode库来读取图像中的Barcode。

使用Dynamsoft Barcode SDK创建Python Barcode动态链接库

编译Python Barcode动态链接库。

#include "Python.h"
 
#include "If_DBR.h"
#include "BarcodeFormat.h"
#include "BarcodeStructs.h"
#include "ErrorCode.h"
 
#ifdef _WIN64
#pragma comment(lib, "DBRx64.lib")
#else
#pragma comment(lib, "DBRx86.lib")
#endif
 
void SetOptions(pReaderOptions pOption, int option_iMaxBarcodesNumPerPage, int option_llBarcodeFormat){
 
    if (option_llBarcodeFormat > 0)
        pOption->llBarcodeFormat = option_llBarcodeFormat;
    else
        pOption->llBarcodeFormat = OneD;
 
    if (option_iMaxBarcodesNumPerPage > 0)
        pOption->iMaxBarcodesNumPerPage = option_iMaxBarcodesNumPerPage;
    else
        pOption->iMaxBarcodesNumPerPage = INT_MAX;
 
}
 
static PyObject *
initLicense(PyObject *self, PyObject *args)
{
    char *license;
 
    if (!PyArg_ParseTuple(args, "s", &license)) {
        return NULL;
    }
 
    printf("information: %s\n", license);
 
    int ret = DBR_InitLicense(license);
 
    printf("return value = %d", ret);
 
    return Py_None;
}
 
static PyObject *
decodeFile(PyObject *self, PyObject *args)
{
    char *pFileName;
    int option_iMaxBarcodesNumPerPage = -1;
    int option_llBarcodeFormat = -1;
 
    if (!PyArg_ParseTuple(args, "s", &pFileName)) {
        return NULL;
    }
 
    pBarcodeResultArray pResults = NULL;
    ReaderOptions option;
    SetOptions(&option, option_iMaxBarcodesNumPerPage, option_llBarcodeFormat);
 
    int ret = DBR_DecodeFile(
        pFileName,
        &option,
        &pResults
        );
 
    if (ret == DBR_OK){
        int count = pResults->iBarcodeCount;
        pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
        pBarcodeResult tmp = NULL;
 
        PyObject* list = PyList_New(count);
        PyObject* result = NULL;
 
        for (int i = 0; i < count; i++)
        {
            tmp = ppBarcodes[i];
            result = PyString_FromString(tmp->pBarcodeData);
 
            PyList_SetItem(list, i, Py_BuildValue("iN", (int)tmp->llFormat, result));
        }
 
        // release memory
        DBR_FreeBarcodeResults(&pResults);
 
        return list;
    }
 
    return Py_None;
}
 
static PyMethodDef methods[] = {
    { "initLicense", initLicense, METH_VARARGS, NULL },
    { "decodeFile", decodeFile, METH_VARARGS, NULL },
    { NULL, NULL }
};
 
PyMODINIT_FUNC
initDynamsoftBarcodeReader(void)
{
    Py_InitModule("DynamsoftBarcodeReader", methods);
}

具体请参考GitHub上的源码。编译成功之后请记得拷贝DynamsoftBarcodeReader.pydDynamsoftBarcodeReaderx64.dll /DynamsoftBarcodeReaderx86.dll到工程目录中。

使用OpenCV打开Webcam

import cv2.cv as cv
 
title = "Dynamsoft Barcode Reader"
cv.NamedWindow(title, 1)
capture = cv.CaptureFromCAM(0)
 
while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage(title, img)

使用OpenCV绘制显示结果

line_type = cv.CV_AA
font = cv.InitFont(cv.CV_FONT_HERSHEY_COMPLEX,
                          0.1, 1, 1, 1, line_type)
fileName = ‘test.jpg‘
img = cv.QueryFrame(capture)
cv.SaveImage(fileName, img)
 
results = DynamsoftBarcodeReader.decodeFile(fileName)
top = 30
increase = 20
if results:
    for result in results:
        barcode_format = "Format: " + formats[result[0]]
        barcode_value = "Value: " + result[1]
        cv.PutText(img, barcode_format, (10, top), font, (254, 142, 20))
        top += increase
        cv.PutText(img, barcode_value, (10, top), font, (254, 142, 20))
        top += increase
        cv.PutText(img, "************************", (10, top), font, (254, 142, 20))
        top += increase
 
cv.ShowImage(title, img)

源码

https://github.com/yushulx/webcam-barcode-reader

时间: 2024-08-30 11:18:33

轻松使用OpenCV Python控制Webcam,读取Barcode的相关文章

OpenCV Python教程(1、图像的载入、显示和保存)

本文转载自 OpenCV Python教程(1.图像的载入.显示和保存)     作者 Daetalus 本文是OpenCV  2 Computer Vision Application Programming Cookbook读书笔记的第一篇.在笔记中将以Python语言改写每章的代码. PythonOpenCV的配置这里就不介绍了. 注意,现在OpenCV for Python就是通过NumPy进行绑定的.所以在使用时必须掌握一些NumPy的相关知识! 图像就是一个矩阵,在OpenCV fo

python控制mysql的API手记

--------------------python控制mysql的API--------------------#import MySQLdb:引用对应的开发包#conn=MySQLdb.connect (host='localhost',user='root',passwd='root',db='test',port=3306):创建数据 库连接#cur=conn.cursor():创建游标 #cur.execute(self, query, args):执行单条sql语句,接收的参数为sq

从控制台中读取密码 - C#

Tip :    从控制台中读取密码 语言: C# ______________________________________________________________ 在登陆Linux系统的时候,体验过在Linux的shell命令行窗口中输入用户密码吗? 下面体验下在Windows控制台中输入密码的方式 Showing  Effect SourceCode /// <summary> /// Read password from console /// </summary>

12步轻松搞定python装饰器

12步轻松搞定python装饰器 呵呵!作为一名教python的老师,我发现学生们基本上一开始很难搞定python的装饰器,也许因为装饰器确实很难懂.搞定装饰器需要你了解一些函数式编程的概念,当然还有理解在python中定义和调用函数相关语法的一些特点. 我没法让装饰器变得简单,但是通过一步步的剖析,我也许能够让你在理解装饰器的时候更自信一点.因为装饰器很复杂,这篇文章将会很长(自己都说很长,还敢这么多废话blablabla...前戏就不继续翻译直接省略了) 1. 函数 在python中,函数通

深入浅出 Python 装饰器:16 步轻松搞定 Python 装饰器

Python的装饰器的英文名叫Decorator,当你看到这个英文名的时候,你可能会把其跟Design Pattern里的Decorator搞混了,其实这是完全不同的两个东西.虽然好像,他们要干的事都很相似--都是想要对一个已有的模块做一些"修饰工作",所谓修饰工作就是想给现有的模块加上一些小装饰(一些小功能,这些小功能可能好多模块都会用到),但又不让这个小装饰(小功能)侵入到原有的模块中的代码里去.但是OO的Decorator简直就是一场恶梦,不信你就去看看wikipedia上的词条

解决ftp连接出现 无法从控制 Socket 读取。Socket 错误 = #10054。

ftp连接会显示以下错误信息 无法从控制 Socket 读取.Socket 错误 = #10054 或者是这样的信息 Opening data channel for directory list.Transfer OK421 No-transfer-time exceeded. Closing control connection.disconnected. control connection. 奇怪的是本地电脑无法连接,甚至是同一个局域网的其它电脑都无法连接,但是使用另外一台服务器去连接f

Python小程序,读取ACCESS数据库,然后list数据

曾经做过的一个Python小程序,读取ACCESS数据库,然后list数据 # -*- coding: cp936 -*-import wximport wx.libimport sys,glob,randomimport win32com.clientreload(sys)sys.setdefaultencoding('utf-8')class DemoFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self,None,-1,u"安

【python-excel】Selenium+python自动化之读取Excel数据(xlrd)

Selenium2+python自动化之读取Excel数据(xlrd) 转载地址:http://www.cnblogs.com/lingzeng86/p/6793398.html ···························································································································

Python按行读取文件、写文件

Python按行读取文件 学习了:https://www.cnblogs.com/scse11061160/p/5605190.html file = open("sample.txt") for line in file: pass # do something file.close() 学习了:https://blog.csdn.net/ysdaniel/article/details/7970883 去除换行符 for line in file.readlines(): line