电脑摄像头识别二维码OpenCV程序

本文介绍了一个使用ZBar解码库结合OpenCV的程序,该程序能通过电脑WebCam实时采集图像并识别二维码,支持多种条形码类型,如EAN-13/UPC-A、UPC-E、EAN-8等。识别结果会被记录在本地文件中,便于后续分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个程序主要用zbar解码库来解析二维码的,ZBar是一个开源软件套件,用于从各种来源读取条形码,例如视频流,图像文件和原始强度传感器。 它支持许多流行的符号(条形码类型),包括EAN-13 / UPC-A,UPC-E,EAN-8,Code 128,Code 39,Interleaved 2 of 5和QR Code。
这里用电脑自带的WebCam采集图像,并对每一帧都进行识别,然后检测到码信息时将其写入到当前目录下的文件中方便观察,请看代码:

#include "zbar.h"        
#include "cv.h"        
#include "highgui.h"        
#include "iostream"
#include "fstream"

using namespace std;
using namespace zbar;  //添加zbar名称空间      
using namespace cv;

int main(int argc, char*argv[])
{

	VideoCapture VC(0);
	while (true)
	{
		ImageScanner scanner;
		scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);

		Mat image;
		VC.read(image);
		imshow("Source Image", image);
		if (!image.data)
		{
			cout << "请确认摄像头正确采集" << endl;
			system("pause");
			return 0;
		}
		Mat imageGray;
		cvtColor(image, imageGray, CV_RGB2GRAY);
		int width = imageGray.cols;
		int height = imageGray.rows;
		uchar *raw = (uchar *)imageGray.data;
		Image imageZbar(width, height, "Y800", raw, width * height);
		scanner.scan(imageZbar); //扫描条码      
		Image::SymbolIterator symbol = imageZbar.symbol_begin();
		if (imageZbar.symbol_begin() == imageZbar.symbol_end())
		{
			cout << "查询条码失败,请检查图片!" << endl;
		}
		else 
		{
			for (; symbol != imageZbar.symbol_end(); ++symbol)
			{
				cout << "类型:" << endl << symbol->get_type_name() << endl << endl;
				cout << "条码:" << endl << symbol->get_data() << endl << endl;
				//将检测的结果写到result.txt中方便查阅,追加方式写入的,
				ofstream fout("result.txt", ios::app);
				fout << "类型:" << symbol->get_type_name() << endl << "条码:" << symbol->get_data() << endl<<endl;
				fout.close();
				int key = cvWaitKey();
				if (key == 27) return 0;
			}
		}
			
		imageZbar.set_data(NULL, 0);
		int key = cvWaitKey(100);
		if (key == 27) return 0;
	}
	waitKey();
	return 0;
}

首先要去官网下载ZBar 0.10 Windows installer,然后将其库安装本地,将zbar/bin目录添加到系统的环境变量,然后将zbar/lib添加到VS的项目/属性/VC++目录/包含目录下,将zbar/include 添加到VC++目录/库目录下,在链接器-输入中添加libzbar-0.lib ,完工,运行代码试试吧!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值