Python programming example | barcode image recognition

 * In this series of tweet cases, it is recommended that Python use version 3.10 and above, NumPy use version 1.22.3 and above, Matplotlib use version 3.5.1 and above, and Pandas use version 1.4.2 and above. Starting from version 3.10 of Python, the input prompt >>> in the IDLE interactive environment that comes with the standard release version is placed alone on the left side and cannot be copied along with the input statement. In order to clearly distinguish the input and output of the instance in the interactive environment, this series of tweets still retains the input prompt >>> at the beginning of each input statement.

01. Application example background

A friend opened a Taobao store and sent out many express deliveries every day and took photos to record them, so there were many pictures of express delivery orders. There is a repetitive task every night, which is to open the pictures one by one, extract the barcode number, save it in Excel, and change the name of the picture to "Barcode Number.jpg" to save it, as shown in Figure 1 .

■ Figure 1 Barcode identification of express delivery orders

This friend's business is getting better and better, so the workload is getting bigger and bigger (there may be hundreds of pictures that need to be identified every day). He hopes to develop an application that can automatically recognize barcodes and modify file names.

The pictures are all in jpg format, but the express orders come from different express companies, so they look all kinds of strange. The people taking the photos are also different, so the photos taken may not be neat. The only thing that's certain is that every photo has a barcode and is in good clarity.

02. Barcode recognition program

The difficulty of this application lies in barcode recognition. If it is developed from scratch, the workload will be too large. We found the open source software zbar (http://zbar.sourceforge.net/, of course you can also choose other software) that can recognize barcodes and QR codes. After downloading and installing, you can open the command line and enter zbarimg -h in the bin of the software installation directory to get the following results:

C: work Python barcodes ZBar bin>zbarimg -h
usage: zbarimgoptions] <image >...
scan and decode bar codes from one or more image files
options:
h--help  display this help text
--version  display version information and exit
-q,-- quiet   minimal output,only print decoded symbol data
-V,--verbose   increase debug output level
-- verbose=N    set specific debug output level
-d,-- display  enable display of following images to the screen
-D,--nodisplay disable display of following images (default)
--xml,--nodisplay enable/disable XML output format-- noxm]
-- raw  output decoded symbol data without symbology prefix
--S  < CONFIG>=< VALUE >], 
-set < CONFIG>=< VALUE >],
set  decoder/scanner < CONFIG> to < VALUE> (or 1)

 This means the installation was successful. Use your mobile phone to take a photo of the ISBN barcode of a book, as shown in Figure 2, and save it as isbn.jpg.

■ Figure 2 Picture of ISBN barcode

Run the following code in the command line window of the operating system to successfully identify the ISBN number corresponding to the barcode shown in Figure 2.

EAN-13:9780521865715
C: work Python barcodes ZBar bin>zbarimg isbn.jpg
scanned 1 barcode symbols from 1 images

The key problem of identification is solved, and then the GUI interface can be written, and then the problem can be solved by calling zbar.

03. Interface design

After the preparation of the preliminary work is completed, it is the formal software design and coding. To conceive a GUI, there are the following requirements.

(1) There is an "Open" button to select the picture to be recognized; an export data button.

(2) The data display window can be presented in the form of a table.

(3) A multi-line text box, used to output some debugging data, such as error feedback, unrecognized and other information.

Use wxFormBuilder to design GUI. In the GUI design interface shown in Figure 3, first create a Frame window. Add a vertical BoxSizer, add a ToolBar toolbar and a GridSizer with 1 row and 2 columns. In the ToolBar toolbar, add two Tool buttons and select the appropriate icon (source selects Load From Art Provider, id selects wxART_FILE_OPEN and wxART_FILE_SAVE). Add a DataViewListCtrl to the lower left part of the interface to display data, and add a TextCtrl to the lower right part to output debugging information. The software running results are shown in Figure 4.

 ■ Figure 3 Design software interface

 ■ Figure 4 Software running results

04. Complete code

The program is saved in the barcodes.py file, and the entire code is as follows:

#-*- coding:utf-8 -*
import wx
import wx.xrc
import wx.dataview
import os
import csv
from datetime import datetime
class MyFramel (wx.Frame):
definit (self,parent) :
wx.Frame.__init__(self,parent,id= wx.ID_ANY,title= u"条形码识别程序"pos = wx.DefaultPosition,size = wx.Size866,302)style = WX.DEFAULT FRAME STYLEWX.TAB TRAVERSAL)self.SetSizeHints(wx.DefaultSize,wx.DefaultSize)bSizer5 = wx.BoxSizer(wx.VERTICAL)self.m toolBar2 = wx,ToolBar(self,WX.ID ANY,wx,DefaultPosition,wx.DefaultSize,wX.TB HORIZONTAL)self.m_open = self.m toolBar2.AddTool(wx.ID ANY,u"打开”
wx.ArtProvider.GetBitmap(wx.ART FILE OPEN
WX.ART TOOLBAR),wx.NullBitmap,wX.ITEM NORMAL,
wx.EmptyString,wx.EmptyString,None)
self.m_export = self.m toolBar2.AddTool(wx.ID ANY,u"导出”wX.ArtProvider.GetBitmap(wx.ART FILE SAVEWX.ART TOOLBAR),wX.NullBitmap,wX.ITEM NORMALwx.EmptyString,wx.EmptyString,None)self.m toolBar2.Realize()bSizer5.Add(self.m toolBar2,0,WX.EXPAND,5)gSizer1 = wx.GridSizer(1,2,0,0)self.m dvc = wx.dataview.DataViewListCtrl(self,wx.ID ANY
wx.DefaultPosition,wx.DefaultSize,
wx.dataview.DV MULTIPLE wx.dataview.DV ROW LINES)
qSizer1.Add(self.m dvc,0,wx.EXPAND,5)self.m out = wx.TextCtrl(self,wX.ID ANY,wx.EmptyString,
wx.DefaultPosition,wx.DefaultSize,
WX.TE MULTILINE)
0,WX.EXPAND,5)gSizer1.Add(self.m out,bSizer5.Add(gSizer1,1,WX.EXPAND,5)
self.SetSizer(bSizer5)
self.Layout(
self.Centre(wx.BOTH)
# Connect Events
self.Bind(wx.EVT_TOOL,self.openimgs,id = self.m open.GetId())self.Bind(wx.EVT TOOL,self.export2csv,id= self.m export.GetId())#Mycode
self.m dvc.AppendTextColumn(u'日期
self.m dvc.AppendTextColumn(u'条形码',width = 120)self.m_dvc.AppendTextColumn(u'文件地址 width = 400)
del (self):def
pass
#Virtual event handlersdef openimgs(self,event)dlg = wx.FileDialog(
self,message =“Choose some images"
defaultDir = os.getcwd()
defaultFile =n
wildcard=wildcard
style = Wx.FD OPENWX.FD MULTIPLE WX.FD CHANGE DIR
if dlq.ShowModal() == wx.ID OK:
self.m out.WriteText( Recognizing!n')paths = dlg.GetPaths()
for path in paths:
tmp = os.popen%s -- raw %s'%(cmd,path)).readlines()barN
while barNum == and i< len(tmp)barNum = tmp[i].strip()
i +=1
if barNum == .
self.m out.WriteText('% s recognize fails! n'% path)continuenewname ='%sss' (os.path.dirname(path),barNum,os.path.splitext(path)[ -1:][0])
try:
os.rename(path,newname)item = [datetime.now().strftime('%Y-%m-%d'),s” barNum,newname]self.m dvc.AppendItem( item)
csvdata.append( item)
self.m out.WriteText( %s Recognize Done! n'% barNumexcept Exception as e:self.m out.WriteText(  %s rename fails! n' path)self.m out.WriteText(str(e))
dlg.Destroy()
def export2csv(self,event):
dlg = wx.FileDialog(self,message ="Save file as ...",defaultDir = os.getcwd()defaultFile=wildcard = wildcard2,style = wx.FD SAVE
dlg.SetFilterIndex(2)
if dlg.ShowModal() == wX.ID OK:
self.m out.WriteText(Exporting! n')path = dlg.GetPath()
try:with open(path,w',newline =) as csvfile:writer = csv.writer(csvfile,dialect =excel',quoting = csV.OUOTE ALL)for row in csvdata:writer.writerow(row)
self.m out.WriteText( s Export Done! n' path)except Exception as e:
self.m out.WriteText(str(e))
dlg.Destroy()
wildcard = "Pictures ( *.jpg,*.png)*.jpg;*.png All files (*.*)*.*"
wildcard2 ="CSV files (*.csv) *.csv"
cmd = os.path.realpath('Zbar/bin/zbarimq.exe')
csvdata = []
app= wX.App()
win = MyFramel(None)
win.Show()
app.MainLoop()

Explanation:  Because some lines in the above code are too long, numbers are added to the front of the code to indicate the line number.

Precautions:

(1) The zbar software is installed in the current directory of the above program and can be run through Zbar\bin\zbarimg.exe.

(2) There may be errors if there are Chinese characters in the directory.

(3) When opening a file with FileDialog, the current directory will be changed, so the absolute path of the zbar command must be saved at the beginning.

(4) Since the barcode has numbers starting with 0, which will be automatically omitted when opened in Excel, a "'" symbol is added before the number.

Guess you like

Origin blog.csdn.net/qq_41640218/article/details/132754477