Skip to content

Commit

Permalink
提高准确率
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed Aug 21, 2018
1 parent bb2058e commit 58dcb3b
Show file tree
Hide file tree
Showing 3 changed files with 285 additions and 172 deletions.
31 changes: 13 additions & 18 deletions findidcard.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 9,16 @@ def __init__(self):
pass

#img1为身份证模板, img2为需要识别的图像
def find(self, img1_name, img2_name):
def find(self, img2_name):
print(u'进入身份证模版匹配流程...')
img1_name = 'idcard_mask.jpg'
MIN_MATCH_COUNT = 10
#idocr = idcardocr.idcardocr()
img1 = cv2.UMat(cv2.imread(img1_name, 0)) # queryImage in Gray
img1 = self.img_resize(img1, 640)
#self.showimg(img1)
# self.showimg(img1)
#img1 = idocr.hist_equal(img1)
img2 = cv2.UMat(cv2.imread(img2_name, 0)) # trainImage in Gray
# print(img2.get().shape)
img2 = self.img_resize(img2, 1920)
#img2 = idocr.hist_equal(img2)
img_org = cv2.UMat(cv2.imread(img2_name))
Expand All @@ -36,9 38,6 @@ def find(self, img1_name, img2_name):
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des1,des2,k=2)

t2 = round(time.time()*1000)
print 'time:%s'%(t2-t1)

# store all the good matches as per Lowe's ratio test.
#两个最佳匹配之间距离需要大于ratio 0.7,距离过于相似可能是噪声点
good = []
Expand All @@ -54,17 53,11 @@ def find(self, img1_name, img2_name):
matchesMask = mask.ravel().tolist()
#使用转换矩阵M计算出img1在img2的对应形状
h,w = cv2.UMat.get(img1).shape
pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
dst = cv2.perspectiveTransform(pts,M)

img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA)
#self.showimg(img2)
#进行图像矫正(透视变换)
M_r, mask_r = cv2.findHomography(dst, pts, 0,5.0)
M_r=np.linalg.inv(M)
im_r = cv2.warpPerspective(img_org, M_r, (w,h))
#self.showimg(im_r)
# self.showimg(im_r)
else:
print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT)
print("Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT))
matchesMask = None

#draw_params = dict(matchColor = (0,255,0), # draw matches in green color
Expand All @@ -73,6 66,8 @@ def find(self, img1_name, img2_name):
# flags = 2)
#img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params)
#plt.imshow(img3, 'gray'),plt.show()
t2 = round(time.time() * 1000)
print(u'查找身份证耗时:%s' % (t2 - t1))
return im_r


Expand All @@ -89,10 84,10 @@ def img_resize(self, imggray, dwidth):
height = size[0]
width = size[1]
height = height * dwidth / width
crop = cv2.resize(src=crop, dsize=(dwidth, height), interpolation=cv2.INTER_CUBIC)
crop = cv2.resize(src=crop, dsize=(dwidth, int(height)), interpolation=cv2.INTER_CUBIC)
return crop

if __name__=="__main__":
idfind = findidcard()
result = idfind.find('idcard_mask.jpg', '9.jpg')
idfind.showimg(result)
result = idfind.find('idcard_mask.jpg', 'testimages/9.jpg')
#idfind.showimg(result)
35 changes: 19 additions & 16 deletions idcard_recognize.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 2,25 @@
import idcardocr
import findidcard
import json
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import cv2, time
import uuid
import cgi

def process(img_name):
try:
idfind = findidcard.findidcard()
idcard_img = idfind.find('idcard_mask.jpg', img_name)
idcard_img = idfind.find(img_name)
result_dict = idcardocr.idcardocr(idcard_img)
result_dict['error'] = 0
except StandardError as e:
except Exception as e:
result_dict = {'error':1}
print e
print(e)
return result_dict

#SocketServer.ForkingMixIn, SocketServer.ThreadingMixIn
class ForkingServer(SocketServer.ForkingMixIn, HTTPServer):
class ForkingServer(socketserver.ForkingMixIn, HTTPServer):
pass

class S(BaseHTTPRequestHandler):
Expand All @@ -40,23 40,26 @@ def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
# post_data = self.rfile.read(content_length) # <--- Gets the data itself
ctype, pdict = cgi.parse_header(self.headers['content-type'])
print pdict
print(pdict)
pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
multipart_data = cgi.parse_multipart(self.rfile, pdict)
filename = uuid.uuid1()
fo = open("tmp/%s.jpg"%filename, "w")
fo.write( multipart_data['pic'][0] )
fo = open("tmp/%s.jpg"%filename, "wb")
# print(str(multipart_data))
# print(multipart_data.get('pic')[0])
fo.write( multipart_data.get('pic')[0] )
fo.close()
result = process("tmp/%s.jpg"%filename)
#print result
self._set_headers()
self.wfile.write(json.dumps(result))
self.wfile.write(json.dumps(result).encode('utf-8'))

def http_server(server_class=ForkingServer, handler_class=S, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
cv2.ocl.setUseOpenCL(False)
print 'Starting httpd...'
print "是否启用OpenCL:%s"%cv2.ocl.useOpenCL()
print('Starting httpd...')
print(u"是否启用OpenCL:%s"%cv2.ocl.useOpenCL())
httpd.serve_forever()

if __name__=="__main__":
Expand All @@ -72,10 75,10 @@ def http_server(server_class=ForkingServer, handler_class=S, port=8080):
# p.join()
#print r9.get(), r14.get()
http_server()
# cv2.ocl.setUseOpenCL(False)
# cv2.ocl.setUseOpenCL(True)
# t1 = round(time.time() * 1000)
# for i in range(1,10):
# print process('./testimages/%s.jpg'%i)
# for i in range(1,15):
# print(process('./testimages/%s.jpg'%i))
# t2 = round(time.time() * 1000)
# print 'time:%s' % (t2 - t1)
# print('time:%s' % (t2 - t1))

Loading

0 comments on commit 58dcb3b

Please sign in to comment.