使用python写的opencv实时监测和解析二维码和条形码


Posted in Python onAugust 14, 2019

今天,我实现了一个很有趣的demo,它可以在视频里找到并解析二维码,然后把解析的内容实时在屏幕上显示出来。

然后我们直入主题,首先你得确保你装了opencv,python,zbar等环境。然后这个教程对于学过opencv的人可能更好理解,但是没学过也无妨,到时候也可以直接用。

比如我的电脑上的环境是opencv2.4.x,python2.7,和最新的zbar,在Ubuntu 12.12的系统下运行的

假设你的opencv已经安装好了,那么我们就可以安装zbar

你可以先更新一下

sudo apt-get update

然后在输入

sudo apt-get install python-zbar

如果环境装好了,我们就可以接着下一步操作了。

首先让我们来实现找到在图片里面找到二维码的功能

先新建一个python文件叫做;simple_barcode_detection.py

代码如下,这定义了一个函数,实现从一副图片里面找出二维码的位置

我们要检测的二维码的图片

使用python写的opencv实时监测和解析二维码和条形码

import numpy as np
 import cv2
 def detect(image):
# 把图像从RGB装换成灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用Scharr操作(指定使用ksize = -1)构造灰度图在水平和竖直方向上的梯度幅值表示。
gradX = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 0, dy = 1, ksize = -1)
#Scharr操作后,从x的梯度减去y的梯度
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
#经过上面的操作后看起来是这样

使用python写的opencv实时监测和解析二维码和条形码

# 对上述的梯度图采用用9x9的核进行平均模糊,这是有利于降噪的

#然后进行二值化处理,要么是255(白)要么是0(黑)

blurred = cv2.blur(gradient, (9, 9))
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)

#模糊与二值化处理后,看起来是这个样子,

使用python写的opencv实时监测和解析二维码和条形码

#上面的操作后发现有一些条形码的竖杠之间存在一些缝隙,并使我们的算法能检测到斑点区域,我们进行一些基本的形态学操作
#我们首先使用cv2.getStructuringElement构造一个长方形内核。这个内核的宽度大于长度,因此我们可以消除条形码中垂直条之间的缝隙。
# 这里进行形态学操作,将上一步得到的内核应用到我们的二值图中,以此来消除竖杠间的缝隙。
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
#上述操作后看起来是这个样子

使用python写的opencv实时监测和解析二维码和条形码

#我们发现还是存在一些小斑点,这时我们可以使用opencv里面的腐蚀和膨胀来处理他们,来去除白色的斑点

closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
#这时候的效果看起来是这样的

使用python写的opencv实时监测和解析二维码和条形码

# 接下来我们来找轮廓
(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
#如果没找到则返回为空
if len(cnts) == 0:
return None
#找到了就通过面积来排序,并计算旋转角
# 给最大的轮廓找到边框
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
rect = cv2.minAreaRect(c)
#box(里面是ndarry数组,包含了4个顶点的位置)
box = np.int0(cv2.cv.BoxPoints(rect))
# 返回box
return box

最终结果

使用python写的opencv实时监测和解析二维码和条形码

 好了,上面的解释里面有中文,可能python解释的时候会通不过,我下面直接给出代码

import numpy as np
import cv2
def detect(image):
	# convert the image to grayscale
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	# compute the Scharr gradient magnitude representation of the images
	# in both the x and y direction
	gradX = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 1, dy = 0, ksize = -1)
	gradY = cv2.Sobel(gray, ddepth = cv2.cv.CV_32F, dx = 0, dy = 1, ksize = -1)
	# subtract the y-gradient from the x-gradient
	gradient = cv2.subtract(gradX, gradY)
	gradient = cv2.convertScaleAbs(gradient)
	# blur and threshold the image
	blurred = cv2.blur(gradient, (9, 9))
	(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
	# construct a closing kernel and apply it to the thresholded image
	kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
	closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
	# perform a series of erosions and dilations
	closed = cv2.erode(closed, None, iterations = 4)
	closed = cv2.dilate(closed, None, iterations = 4)
	# find the contours in the thresholded image
	(cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)
	# if no contours were found, return None
	if len(cnts) == 0:
		return None
	# otherwise, sort the contours by area and compute the rotated
	# bounding box of the largest contour
	c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
	rect = cv2.minAreaRect(c)
	box = np.int0(cv2.cv.BoxPoints(rect))
	# return the bounding box of the barcode
	return box

完成了上述的工作,我们就完成了二维码和条形码的定位,接下去实现视频里面二维码的解析

你可以新建一个python文件,barcode_vid.py

解析二维码我们需要用zbar这个模块和PIL,PIL在python里面装好了

我们先导入模块

# import the necessary packages
import simple_barcode_detection
import cv2
import numpy as np
import zbar
from PIL import Image

#接下去是创建一个扫描器,他可以解析二维码的内容

# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
#设置屏幕显示字体
font=cv2.FONT_HERSHEY_SIMPLEX
#启用摄像头
camera=cv2.VideoCapture(0)
#接下去是一个大的while循环
while True:
#得到当前的帧
# grab the current frame
(grabbed, frame) = camera.read()
#检测视频是否到底了,如果检测视频文件里面的二维码或条形码用这个,如果开启摄像头就无所谓了
# check to see if we have reached the end of the
# video
if not grabbed:
break
调用刚才我们建的那个函数来查找二维码返回二维码的位置
# detect the barcode in the image
box = simple_barcode_detection.detect(frame)
if box != None:
#这下面的3步得到扫描区域,扫描区域要比检测出来的位置要大
min=np.min(box,axis=0)
max=np.max(box,axis=0)
roi=frame[min[1]-10:max[1]+10,min[0]-10:max[0]+10]
#把区域里的二维码传换成RGB,并把它转换成pil里面的图像,因为zbar得调用pil里面的图像,而不能用opencv的图像
roi=cv2.cvtColor(roi,cv2.COLOR_BGR2RGB)
pil= Image.fromarray(frame).convert('L')
width, height = pil.size
raw = pil.tostring()
#把图像装换成数据
zarimage = zbar.Image(width, height, 'Y800', raw)
#扫描器进行扫描
scanner.scan(zarimage)
#得到结果
for symbol in zarimage:
  # 对结果进行一些有用的处理
print 'decoded', symbol.type, 'symbol', '"%s"' %symbol.data
cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)
#把解析的内容放到视频上
cv2.putText(frame,symbol.data,(20,100),font,1,(0,255,0),4)
# show the frame and record if the user presses a key
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break
# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()

CSDN不能上传视频,我下面传一下图片

使用python写的opencv实时监测和解析二维码和条形码

下面还是上源码

# import the necessary packages
import simple_barcode_detection
import cv2
import numpy as np
import zbar
from PIL import Image
# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
font=cv2.FONT_HERSHEY_SIMPLEX
camera=cv2.VideoCapture(0)
while True:
# grab the current frame
(grabbed, frame) = camera.read()
# check to see if we have reached the end of the
# video
if not grabbed:
break
# detect the barcode in the image
box = simple_barcode_detection.detect(frame)
if box != None:
min=np.min(box,axis=0)
max=np.max(box,axis=0)
roi=frame[min[1]-10:max[1]+10,min[0]-10:max[0]+10]
print roi.shape
roi=cv2.cvtColor(roi,cv2.COLOR_BGR2RGB)
pil= Image.fromarray(frame).convert('L')
width, height = pil.size
raw = pil.tostring()
# wrap image data
zarimage = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
scanner.scan(zarimage)
# extract results
for symbol in zarimage:
  # do something useful with results
print 'decoded', symbol.type, 'symbol', '"%s"' %symbol.data
cv2.drawContours(frame, [box], -1, (0, 255, 0), 2)
cv2.putText(frame,symbol.data,(20,100),font,1,(0,255,0),4)
# if a barcode was found, draw a bounding box on the frame
# show the frame and record if the user presses a key
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the loop
if key == ord("q"):
break
# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()

总结

以上所述是小编给大家介绍的使用python写的opencv实时监测和解析二维码和条形码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
Python中Continue语句的用法的举例详解
May 14 Python
python paramiko模块学习分享
Aug 23 Python
python交互式图形编程实例(一)
Nov 17 Python
python正则中最短匹配实现代码
Jan 16 Python
pandas重新生成索引的方法
Nov 06 Python
对IPython交互模式下的退出方法详解
Feb 16 Python
python初学者,用python实现基本的学生管理系统(python3)代码实例
Apr 10 Python
pyqt5中QThread在使用时出现重复emit的实例
Jun 21 Python
python lambda表达式(匿名函数)写法解析
Sep 16 Python
python 爬取古诗文存入mysql数据库的方法
Jan 08 Python
Python基于staticmethod装饰器标示静态方法
Oct 17 Python
使用Python实现NBA球员数据查询小程序功能
Nov 09 Python
用python3 urllib破解有道翻译反爬虫机制详解
Aug 14 #Python
使用Python实现图像标记点的坐标输出功能
Aug 14 #Python
python2爬取百度贴吧指定关键字和图片代码实例
Aug 14 #Python
python提取照片坐标信息的实例代码
Aug 14 #Python
python2使用bs4爬取腾讯社招过程解析
Aug 14 #Python
详解用python计算阶乘的几种方法
Aug 14 #Python
Python使用scrapy爬取阳光热线问政平台过程解析
Aug 14 #Python
You might like
PHP网页游戏学习之Xnova(ogame)源码解读(十一)
2014/06/25 PHP
PHP实现采集抓取淘宝网单个商品信息
2015/01/08 PHP
PHP中Notice错误常见解决方法
2017/04/28 PHP
PHP使用PhpSpreadsheet操作Excel实例详解
2020/03/26 PHP
extJs 文本框后面加上说明文字+下拉列表选中值后触发事件
2009/11/27 Javascript
仿谷歌主页js动画效果实现代码
2013/07/14 Javascript
JavaScript中的console.dir()函数介绍
2014/12/29 Javascript
javascript事件模型实例分析
2015/01/30 Javascript
window.onerror()的用法与实例分析
2016/01/27 Javascript
Angular 中 select指令用法详解
2016/09/29 Javascript
node.js基于mongodb的搜索分页示例
2017/01/22 Javascript
JS常见构造模式实例对比分析
2018/08/27 Javascript
JS实现鼠标拖拽盒子移动及右键点击盒子消失效果示例
2019/01/29 Javascript
基于Echarts图表在div动态切换时不显示的解决方式
2020/07/20 Javascript
[05:17]DOTA2誓师:今天我们在这里 明天TI4等我!
2014/03/26 DOTA
[09:33]2015国际邀请赛第四日TOP10
2015/08/08 DOTA
python中使用PIL制作并验证图片验证码
2018/03/15 Python
Python数据类型之Tuple元组实例详解
2019/05/08 Python
Python导入模块包原理及相关注意事项
2020/03/25 Python
解决django的template中如果无法引用MEDIA_URL问题
2020/04/07 Python
Python如何将将模块分割成多个文件
2020/08/04 Python
JD Sports法国:英国篮球和运动时尚的领导者
2017/09/28 全球购物
Lookfantastic希腊官网:英国知名美妆购物网站
2018/09/15 全球购物
写一个函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度
2015/11/18 面试题
超级搞笑检讨书
2014/01/15 职场文书
《蒲公英》教学反思
2014/02/28 职场文书
《富饶的西沙群岛》教学反思
2014/04/09 职场文书
初二学习计划书范文
2014/04/27 职场文书
基层党员对照检查材料
2014/08/25 职场文书
解放思想大讨论活动心得体会
2014/09/11 职场文书
组织生活会表态发言材料
2014/10/17 职场文书
教育见习报告范文
2014/11/03 职场文书
学校趣味运动会开幕词
2016/03/04 职场文书
职场新人刚入职工作总结该怎么写?
2019/05/15 职场文书
Python编解码问题及文本文件处理方法详解
2021/06/20 Python
vue配置型表格基于el-table拓展之table-plus组件
2022/04/12 Vue.js