python opencv
来源:互联网 发布:劲舞团淘宝网 编辑:程序博客网 时间:2024/06/10 13:39
import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibSTEP = int(0)def showWindow(img): pass # global STEP # STEP = STEP + 1 # title = "step" + str(STEP) # cv2.namedWindow(title) # cv2.imshow(title, img) # cv2.waitKey(0) # cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = 255) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" src = cv2.cvtColor(src , cv2.COLOR_RGB2GRAY) img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='chi_sim') if str == None : return "failed" str = str.replace(" " , "") if str == None: return "failed" if (str.count("mu") > 0 ) or (str.count("MU") > 0) or (str.count("E") > 0): str = str.replace("O" , "0").replace("o" , "0") ok = True for d in str[2:]: if not ('0' <= d and d <= '9'): ok = False if ok: return str return tools[0].image_to_string(img, lang='eng') return strdef recog(img_path): img = cv2.imread(img_path) split_y = 10000 split_y1 = None split_y2 = None split_x1 = None split_x2 = None split_theta = None img = cv2.resize(img, (210 * 4, 297 * 4), interpolation=cv2.INTER_CUBIC) src = img.copy() showWindow(img) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 180) lines = cv2.HoughLines(edges, 1, np.pi / 180, 350) lines1 = lines[:, 0, :] for rho, theta in lines1[:]: if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): continue a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) y = min(y1 , y2) if 150 <= y and y <= 300 and split_y > y: split_y = y split_y1 = y1 split_y2 = y2 split_x1 = x1 split_x2 = x2 split_theta = theta cv2.line(img, (split_x1, split_y1), (split_x2, split_y2), (0, 0, 255), 3) showWindow(img) src = src[:split_y+15, :] showWindow(src) img_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) angleD = split_theta * 180.0 / np.pi #print("angleD" + str(angleD)) if angleD <= 89 : nCols , nRows = src.shape[:2] src = image_rotate_newsize(src.copy() , (nCols // 2, nRows // 2), angleD - 90.0, 1.0) showWindow(src) img_rotated = image_rotate_newsize(img_gray.copy() , (nCols // 2, nRows // 2), angleD - 90.0, 1.0) # print("img_rotated") showWindow(img_rotated) img_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) showWindow(img_gray) img_blur = cv2.GaussianBlur(img_gray, (5, 5), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) showWindow(img_th3) kernel = np.ones((3, 3), np.uint8) img_closing = cv2.morphologyEx(img_th3, cv2.MORPH_OPEN, kernel) img_closing = cv2.morphologyEx(img_closing, cv2.MORPH_CLOSE, kernel) showWindow(img_closing) kernel = np.ones((7, 13), np.uint8) img_open = cv2.morphologyEx(img_closing, cv2.MORPH_OPEN, kernel) showWindow(img_open) image, contours, hierarchy = cv2.findContours(img_open, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) src_height, src_width, c = src.shape src_area = src_width * src_height reslut_mu = None reslut_img = None img_rec = src.copy() for i in range(len(contours)): box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if 4 <= rate and rate <= 10 and 10 <= area_rate and area_rate <= 100: angle = box[2] img_now = src.copy() points = np.int0(cv2.boxPoints(box)) cv2.drawContours(img_rec, [points], -1, 255, 0) img_now = cv2.getRectSubPix(src.copy(), (int(width) + 10, 10 + int(height)), (int(x), int(y))) showWindow(img_now) s = chi_sim(img_now) # print(s) if s.find("mu") == 0 or s.find("MU") == 0 or s.find("E") == 0: reslut_mu = s # reslut_img = cv2.drawContours(src.copy(), [points], -1, 255, 0) # print(str(s)) # cv2.imwrite("C:/Users/liyang/Desktop/ly/" + str(i) + ".PNG" , img_now) if reslut_mu is not None: return reslut_mu # showWindow(reslut_img) # zhfont1 = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simsun.ttc') # plt.title(reslut_mu , fontproperties=zhfont1) # plt.imshow(reslut_img) # plt.show() return "failed"if __name__ == '__main__': img_path = sys.argv[1] os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' mu = recog(img_path) # IMG_4651.JPG # reslut = {} # reslut["status"] = "Yes" # reslut["result"] = mu # IMG_4567,IMG_4645 # IMG_4653 print(mu)
#coding:utf-8import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibimport jsonSTEP = int(0)def showWindow(img): return global STEP STEP = STEP + 1 title = "step" + str(STEP) cv2.namedWindow(title) cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = (255,255,255)) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='eng') if str == None or len(str) == 0: return "failed" str = str.replace(" " , "") if str == None or len(str) == 0: return "failed" str = str.replace("%", "X").replace("x", "X") if len(str) >= 18: str = str[:18] return strdef isIdcode(s): if s == None or len(s) == 0: return False if len(s) != 18: return False for i in s: if i == 'X' or i == 'x': continue if i < '0' or i > '9': return False return Truedef is_chinese(s): rt = False if s >= u"\u4e00" and s <= u"\u9fa6": rt = True return rtdef s_is_chinese(s): for i in s: if not is_chinese(i): return False return Truedef cmp(x , y): if x < y: return -1 if x == y: return 0 if x > y: return 1if __name__ == '__main__': os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' img_path = sys.argv[1] img_src = cv2.imread(img_path)#IMG_4751 showWindow(img_src) img_src = cv2.resize(img_src, (85 * 8, 54 * 8), interpolation=cv2.INTER_CUBIC) showWindow(img_src) img_gray = cv2.cvtColor(img_src , cv2.COLOR_RGB2GRAY) showWindow(img_gray) img_blur = cv2.GaussianBlur(img_gray, (9, 9), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 7, 7) showWindow(img_th3) kernel = np.ones((9, 21), np.uint8) x = cv2.morphologyEx(img_th3, cv2.MORPH_CLOSE, kernel) showWindow(x) image, contours, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_NONE) s = cv2.drawContours(img_gray.copy(), contours, -1, (0, 0, 255), 3) showWindow(s) src_height, src_width = img_gray.shape[:2] src_area = src_width * src_height idcode = "Failed" names = [] img_rec = img_gray.copy() for i in range(len(contours)): # if idcode != "Failed": # continue box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width == 0 or height == 0: continue if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if rate < 10 or rate > 25 or area_rate < 10 or area_rate >= 1000: continue else: # print(str(rate) + " " + str(area_rate)) angle = box[2] img_now = img_gray.copy() points = np.int0(cv2.boxPoints(box)) # cv2.drawContours(img_rec, [points], -1, 255, 0) img_now = cv2.getRectSubPix(img_gray.copy(), (int(width) +15 , 20+int(height)), (int(x), int(y))) # _, img_now = cv2.threshold(img_now , 0, 255, cv2.THRESH_OTSU) # showWindow(img_now) # nRows, nCols = img_now.shape[:2] # M = cv2.getRotationMatrix2D((nCols / 2, nRows / 2), angle, 1) # img_now = cv2.warpAffine(img_now, M, (nCols, nRows)) # showWindow(img_now) # nRows , nCols = img_now.shape[:2] # img_now = image_rotate_newsize(img_now.copy(), (nCols // 2, nRows // 2), angle, 1.0) s = chi_sim(img_now) if (s == None) or (len(s) == 0) : continue showWindow(img_now) if isIdcode(s): idcode = s continue print(json.dumps({"idcode":idcode , "name":"暂未提供"}))
#coding:utf-8import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibimport jsonimport operatorSTEP = int(0)def showWindow(img): return global STEP STEP = STEP + 1 title = "step" + str(STEP) cv2.namedWindow(title) cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = (255,255,255)) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='eng') if str == None or len(str) == 0: return "failed" return strdef isIdcode(s): if s == None or len(s) == 0: return False if len(s) != 4: return False for i in s: if i < '0' or i > '9': return False return Truedef is_chinese(s): rt = False if s >= u"\u4e00" and s <= u"\u9fa6": rt = True return rtdef s_is_chinese(s): for i in s: if not is_chinese(i): return False return Truedef cmp(x , y): if x < y: return -1 if x == y: return 0 if x > y: return 1if __name__ == '__main__': os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' img_path = sys.argv[1] img_src = cv2.imread(img_path)#IMG_4771 # print(img_src.shape) r , c = img_src.shape[:2] img_src = img_src[int(r/2):,:] showWindow(img_src) img_src = cv2.resize(img_src, (int(600 ), int(400)), interpolation=cv2.INTER_CUBIC) showWindow(img_src) img_gray = cv2.cvtColor(img_src , cv2.COLOR_RGB2GRAY) img_blur = cv2.GaussianBlur(img_gray, (7, 7), 0) # showWindow(img_blur) xxx = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 5) showWindow(xxx) # cv2.imwrite("C:/Users/liyang/Desktop/idcs/mu110.jpg" , xxx) # print(chi_sim(xxx)) # exit(0) # showWindow(img_gray) # _simg = cv2.adaptiveThreshold(xxx, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 7) # showWindow(_simg) # print(chi_sim(_simg)) img_blur = cv2.GaussianBlur(xxx, (5, 7), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 7, 7) showWindow(img_th3) # print(chi_sim(img_th3)) kernel = np.ones((9, 15), np.uint8) x = cv2.morphologyEx(img_th3, cv2.MORPH_CLOSE, kernel) showWindow(x) image, contours, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_NONE) s = cv2.drawContours(img_gray.copy(), contours, -1, (0, 0, 255), 3) showWindow(s) src_height, src_width = img_gray.shape[:2] src_area = src_width * src_height names = [] idcode = "Failed" name = None name_y = None img_rec = img_gray.copy() for i in range(len(contours)): # if idcode != "Failed": # continue box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width == 0 or height == 0: continue if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if rate < 1 or rate > 10 or area_rate < 50 or area_rate >= 1000: continue else: # print(str(rate) + " " + str(area_rate)) angle = box[2] img_now = img_gray.copy() points = np.int0(cv2.boxPoints(box)) img_now = cv2.getRectSubPix(img_src.copy(), (int(width) +10 , 10+int(height)), (int(x), int(y))) s = chi_sim(img_now) # print(s) showWindow(img_now) if (s == None) or (len(s) == 0) or (s == "failed") : continue if isIdcode(s): names.append({"name": s, "x": x, "y": y}) # # print(names) # if len(names) == 1: # name = names[0].get("name") # elif len(names) >= 2: # names.sort(key=operator.itemgetter("y")) # if len(names) == 3: # name = names[1].get("name") # else: # name = names[0].get("name") names.sort(key=operator.itemgetter("x")) idcode = "" for n in names: idcode = idcode + n.get("name") print(json.dumps({"idcode":idcode , "name":""}))
#coding:utf-8import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibimport jsonimport operatorSTEP = int(0)def showWindow(img): return global STEP STEP = STEP + 1 title = "step" + str(STEP) cv2.namedWindow(title) cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = (255,255,255)) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='eng') if str == None or len(str) == 0: return "failed" str = str.replace("T" , "7").replace("B" , "8").replace("O" ,"0").replace("o" ,"0").replace("l" ,"1") return strdef isIdcode(s): if s == None or len(s) == 0: return False if len(s) != 13: return False for i in s: if i < '0' or i > '9': return False return Truedef is_chinese(s): rt = False if s >= u"\u4e00" and s <= u"\u9fa6": rt = True return rtdef s_is_chinese(s): for i in s: if not is_chinese(i): return False return Truedef findFirst(s): n = len(s) if n < 13: return -1 for i in range(n-13): if isIdcode(s[i:i+13]): return i return -1if __name__ == '__main__': os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' img_path = sys.argv[1] img_src = cv2.imread(img_path)#IMG_4771 # print(img_src.shape) # showWindow(img_src) r , c = img_src.shape[:2] # im_old = img_src.copy()[int(r*3/5):,:int(c*2/5)] img_src = img_src[int(r*1/2):,:int(c*2/5)] img_src = cv2.resize(img_src, (int(500), int(400)), interpolation=cv2.INTER_CUBIC) # img_src = img_src[int(r*3/5):,:int(c*1/5)] showWindow(img_src)# print(img_src.shape) # img_src = cv2.resize(img_src, (int(1200 ), int(500)), interpolation=cv2.INTER_CUBIC) # showWindow(img_src) img_gray = cv2.cvtColor(img_src , cv2.COLOR_RGB2GRAY) # img_blur = cv2.GaussianBlur(img_gray, (7, 7), 0) # showWindow(img_blur) xxx = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 5) showWindow(xxx) # cv2.imwrite("C:/Users/liyang/Desktop/idcs/mu110.jpg" , xxx) # print(chi_sim(xxx)) # exit(0) # showWindow(img_gray) # _simg = cv2.adaptiveThreshold(xxx, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 7) # showWindow(_simg) # print(chi_sim(_simg)) img_blur = cv2.GaussianBlur(xxx, (7,7), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 5, 5) showWindow(img_th3) # print(chi_sim(img_th3)) kernel = np.ones((9, 15), np.uint8) x = cv2.morphologyEx(img_th3, cv2.MORPH_CLOSE, kernel) showWindow(x) image, contours, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_NONE) s = cv2.drawContours(img_gray.copy(), contours, -1, (0, 0, 255), 3) showWindow(s) src_height, src_width = img_gray.shape[:2] src_area = src_width * src_height names = [] idcode = "Failed" name = None name_y = None img_rec = img_gray.copy() # print(len(contours)) for i in range(len(contours)): # if idcode != "Failed": # continue box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width == 0 or height == 0: continue if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if rate < 4 or rate > 20 or area_rate < 10 or area_rate >= 1000: continue else: # print(str(rate) + " " + str(area_rate)) angle = box[2] img_now = img_gray.copy() points = np.int0(cv2.boxPoints(box)) img_now = cv2.getRectSubPix(img_src.copy(), (int(width) +10 , 10+int(height)), (int(x), int(y))) s = chi_sim(img_now) s = s.replace(" " , "") # print(s) fs = findFirst(s) if fs != -1: idcode = s[fs:fs+13] showWindow(img_now) # # print(names) # if len(names) == 1: # name = names[0].get("name") # elif len(names) >= 2: # names.sort(key=operator.itemgetter("y")) # if len(names) == 3: # name = names[1].get("name") # else: # name = names[0].get("name") print(json.dumps({"idcode":idcode , "name":""}))
#coding:utf-8import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibimport jsonimport operatorSTEP = int(0)def showWindow(img): return global STEP STEP = STEP + 1 title = "step" + str(STEP) cv2.namedWindow(title) cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = (255,255,255)) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='eng') if str == None or len(str) == 0: return "failed" return strdef isIdcode(s): if s == None or len(s) == 0: return False if len(s) != 8: return False for i in s: if i < '0' or i > '9': return False return Truedef is_chinese(s): rt = False if s >= u"\u4e00" and s <= u"\u9fa6": rt = True return rtdef s_is_chinese(s): for i in s: if not is_chinese(i): return False return Truedef cmp(x , y): if x < y: return -1 if x == y: return 0 if x > y: return 1if __name__ == '__main__': os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' img_path = sys.argv[1] img_src = cv2.imread(img_path)#IMG_4771 # print(img_src.shape) showWindow(img_src) img_src = cv2.resize(img_src, (120 * 5 + 50, 100 * 5), interpolation=cv2.INTER_CUBIC) showWindow(img_src) img_gray = cv2.cvtColor(img_src , cv2.COLOR_RGB2GRAY) showWindow(img_gray) _simg = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 7) showWindow(_simg) img_blur = cv2.GaussianBlur(img_gray, (7, 7), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 7, 7) showWindow(img_th3) kernel = np.ones((9, 17), np.uint8) x = cv2.morphologyEx(img_th3, cv2.MORPH_CLOSE, kernel) showWindow(x) image, contours, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_NONE) s = cv2.drawContours(img_gray.copy(), contours, -1, (0, 0, 255), 3) showWindow(s) src_height, src_width = img_gray.shape[:2] src_area = src_width * src_height names = [] idcode = "Failed" name = None name_y = None img_rec = img_gray.copy() for i in range(len(contours)): # if idcode != "Failed": # continue box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width == 0 or height == 0: continue if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if rate < 5 or rate > 20 or area_rate < 50 or area_rate >= 1000: continue else: # print(str(x) + " " + str(y)) angle = box[2] img_now = img_gray.copy() points = np.int0(cv2.boxPoints(box)) img_now = cv2.getRectSubPix(_simg.copy(), (int(width) +10 , 10+int(height)), (int(x), int(y))) s = chi_sim(img_now) if (s == None) or (len(s) == 0) or (s == "failed") : continue showWindow(img_now) if isIdcode(s): idcode = s else: s = s.replace("1" , "I") names.append({"name": s, "x": x, "y": y}) # print(names) if len(names) == 1: name = names[0].get("name") elif len(names) >= 2: names.sort(key=operator.itemgetter("y")) if len(names) == 3: name = names[1].get("name") else: name = names[0].get("name") print(json.dumps({"idcode":idcode , "name":name}))
#coding:utf-8import cv2import numpy as npimport mathimport sysimport osfrom pyocr import pyocrfrom PIL import Imageimport matplotlib.pyplot as pltimport matplotlibimport jsonimport operatorSTEP = int(0)def showWindow(img): return global STEP STEP = STEP + 1 title = "step" + str(STEP) cv2.namedWindow(title) cv2.imshow(title, img) cv2.waitKey(0) cv2.destroyWindow(title)def image_rotate_newsize(src, center , angle , scale) : angle2 = angle * math.acos(-1.0) / 180 height , width = src.shape[:2] alpha = math.cos(angle2) * scale beta = math.sin(angle2) * scale new_width = int(width * math.fabs(alpha) + height * math.fabs(beta)) new_height = int(width * math.fabs(beta) + height * math.fabs(alpha)) center = (float(width / 2), float(height / 2)) M = cv2.getRotationMatrix2D(center, angle, scale) M[0][2] += int((new_width - width) / 2) M[1][2] += int((new_height - height) / 2) dst = cv2.warpAffine(src , M, (new_width, new_height) , borderValue = (255,255,255)) return dstdef chi_sim(src): tools = pyocr.get_available_tools()[:] if len(tools) == 0: return "failed" img = Image.fromarray(src) str = tools[0].image_to_string(img, lang='eng') if str == None or len(str) == 0: return "failed" return strdef isIdcode(s): if s == None or len(s) == 0: return False if len(s) != 13: return False for i in s: if i < '0' or i > '9': return False return Truedef is_chinese(s): rt = False if s >= u"\u4e00" and s <= u"\u9fa6": rt = True return rtdef s_is_chinese(s): for i in s: if not is_chinese(i): return False return Truedef cmp(x , y): if x < y: return -1 if x == y: return 0 if x > y: return 1if __name__ == '__main__': os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' img_path = sys.argv[1] img_src = cv2.imread(img_path)#IMG_4771 # print(img_src.shape) # showWindow(img_src) r , c = img_src.shape[:2] im_old = img_src.copy()[int(r*3/5):,:int(c*2/5)] img_src = img_src[int(r*3/5):,:int(c*1/5)] showWindow(img_src)# print(img_src.shape) # img_src = cv2.resize(img_src, (int(1200 ), int(500)), interpolation=cv2.INTER_CUBIC) # showWindow(img_src) img_gray = cv2.cvtColor(img_src , cv2.COLOR_RGB2GRAY) # showWindow(img_gray) ys = [] gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 180) lines = cv2.HoughLines(edges, 1, np.pi / 180, 300) lines1 = lines[:, 0, :] for rho, theta in lines1[:]: if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)): continue a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) cv2.line(img_src, (x1, y1), (x2, y2), (0, 0, 255), 0) # print(str(x1) + "," +str(y1) + " " +str(x1) + "," +str(y2) ) ys.append((y1+y2)//2) # showWindow(img_src) ys.sort() # print(ys) yod = [] n = len(ys) sum_y = ys[0] k = 1 for i in range(n): if ys[i] - ys[i-1] < 10: sum_y = sum_y + ys[i] k += 1 else: yod.append(sum_y // k) sum_y = ys[i] k = 1 yod.append(sum_y // k) # print(yod) im = im_old[yod[0]:yod[1],:] r , c = im.shape[:2] im = im[int(r*1/5):,:] showWindow(im) img_gray = cv2.cvtColor(im , cv2.COLOR_BGR2GRAY) showWindow(img_gray) # cv2.imwrite("C:/Users/liyang/Desktop/idcs/air0001ss.jpg" , im) img_blur = cv2.GaussianBlur(img_gray, (7, 7), 0) # showWindow(img_blur) xxx = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 5) showWindow(xxx) # cv2.imwrite("C:/Users/liyang/Desktop/idcs/mu110.jpg" , xxx) # print(chi_sim(xxx)) # exit(0) # showWindow(img_gray) # _simg = cv2.adaptiveThreshold(xxx, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 7, 7) # showWindow(_simg) # print(chi_sim(_simg)) img_blur = cv2.GaussianBlur(xxx, (7,7), 0) showWindow(img_blur) img_th3 = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 5, 5) showWindow(img_th3) # print(chi_sim(img_th3)) kernel = np.ones((9, 15), np.uint8) x = cv2.morphologyEx(img_th3, cv2.MORPH_CLOSE, kernel) showWindow(x) image, contours, hierarchy = cv2.findContours(x, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_NONE) s = cv2.drawContours(img_gray.copy(), contours, -1, (0, 0, 255), 3) showWindow(s) src_height, src_width = img_gray.shape[:2] src_area = src_width * src_height names = [] idcode = "Failed" name = None name_y = None img_rec = img_gray.copy() # print(len(contours)) for i in range(len(contours)): # if idcode != "Failed": # continue box = cv2.minAreaRect(contours[i]) x, y = box[0] width, height = box[1] if width == 0 or height == 0: continue if width < height: t = width width = height height = t angle = box[2] rate = height / width if rate < 1: rate = width / height area_rate = src_area / width / height if 1>2:#rate < 1 or rate > 10 or area_rate < 50 or area_rate >= 1000: continue else: # print(str(rate) + " " + str(area_rate)) angle = box[2] img_now = img_gray.copy() points = np.int0(cv2.boxPoints(box)) img_now = cv2.getRectSubPix(im.copy(), (int(width) +10 , 10+int(height)), (int(x), int(y))) s = chi_sim(img_now) # print(s) showWindow(img_now) if (s == None) or (len(s) == 0) or (s == "failed") : continue if isIdcode(s): names.append({"name": s, "x": x, "y": y}) # # print(names) # if len(names) == 1: # name = names[0].get("name") # elif len(names) >= 2: # names.sort(key=operator.itemgetter("y")) # if len(names) == 3: # name = names[1].get("name") # else: # name = names[0].get("name") names.sort(key=operator.itemgetter("x")) idcode = "" for n in names: idcode = idcode + n.get("name") print(json.dumps({"idcode":idcode , "name":""}))
package com.ceair.api;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.URLConnection;import java.nio.charset.Charset;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.alibaba.fastjson.JSONObject;import com.google.common.base.Strings;import com.google.common.collect.Maps;@Controllerpublic class ApiContorller {@RequestMapping(value = "home")public String homeWeb() {int i = 1 ;return "home";}@RequestMapping(value = "upload")public String uploadWeb() {return "upload";}@RequestMapping(value = "operate")public String operateWeb() {return "operate";}@RequestMapping(value = "/upload.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> upload(@RequestParam(value = "file", required = true) MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String path = request.getSession().getServletContext().getRealPath("upload");File targetFile = new File(path, file.getOriginalFilename());if (!targetFile.exists()) {targetFile.mkdirs();}file.transferTo(targetFile); map.put("status", "seccessed") ;map.put("imgPath", targetFile.getAbsolutePath()) ; map.put("imgSrc", "upload/" + file.getOriginalFilename()) ;return map ; } @RequestMapping(value = "/flightSeatselectionRecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> flightSeatselectionRecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/laige_api.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += line ; } in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_code", json) ; return map ; }@RequestMapping(value = "/idcardRecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> idcardRecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;String idcode = "" ;String name = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/laige/idcard.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += new String(line.getBytes("iso-8859-1"),"utf-8") ; } JSONObject jo = JSONObject.parseObject(json) ; idcode = jo.getString("idcode") ; name = jo.getString("name") ; in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_msg", "身份证号 "+ idcode + " ,姓名 " + name) ; return map ; }@RequestMapping(value = "/psscardRecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> psscardRecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;String idcode = "" ;String name = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/psscard.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += new String(line.getBytes("iso-8859-1"),"utf-8") ; } JSONObject jo = JSONObject.parseObject(json) ; idcode = jo.getString("idcode") ; name = jo.getString("name") ; in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_msg", "东航信息卡号 "+ idcode + " ,姓名 " + name) ; return map ; }@RequestMapping(value = "/muEmbershipCardecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> muEmbershipCardecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;String idcode = "" ;String name = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/muEmbershipCard.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += new String(line.getBytes("iso-8859-1"),"utf-8") ; } JSONObject jo = JSONObject.parseObject(json) ; idcode = jo.getString("idcode") ; name = jo.getString("name") ; in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_msg", "东航会员卡号 "+ idcode + " ,姓名 " + name) ; return map ; }@RequestMapping(value = "/airticketRecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> airticketRecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;String idcode = "" ;String name = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/airticket.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += new String(line.getBytes("iso-8859-1"),"utf-8") ; } JSONObject jo = JSONObject.parseObject(json) ; idcode = jo.getString("idcode") ; // name = jo.getString("name") ; in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_msg", "电子客票号 "+ idcode) ; return map ; }@RequestMapping(value = "/muetktRecog.do", produces = "text/html;charset=UTF-8" )@ResponseBodypublic Map<String , String> muetktRecog(@RequestBody JSONObject param) throws IllegalStateException, IOException {Map<String , String> map = Maps.newHashMap() ; String imgPath = param.getString("imgPath") ; String json = "" ;String idcode = "" ;String name = "" ;try { Process pr = Runtime.getRuntime().exec("python C:/iguardPy/muetkt.py " + imgPath) ; BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream() , "utf-8")); String line; while ((line = in.readLine()) != null) { json += new String(line.getBytes("iso-8859-1"),"utf-8") ; } JSONObject jo = JSONObject.parseObject(json) ; idcode = jo.getString("idcode") ; // name = jo.getString("name") ; in.close(); pr.waitFor(); } catch (Exception e) { e.printStackTrace(); } map.put("status", "seccessed") ;map.put("mu_msg", "电子客票号 "+ idcode) ; return map ; } @RequestMapping(value="/download" )public void downloadFile(String fileName , HttpServletRequest request , HttpServletResponse response) throws IOException {String path = request.getSession().getServletContext().getRealPath("upload") ;File file = new File(path , fileName) ;if(!file.exists()){String errorMessage = "Sorry. The file you are looking for does not exist";OutputStream outputStream = response.getOutputStream();outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));outputStream.close();return;}String mimeType= URLConnection.guessContentTypeFromName(file.getName());if(Strings.isNullOrEmpty(mimeType)){mimeType = "application/octet-stream";} response.setContentType(mimeType); response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\"")); response.setContentLength((int)file.length());InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); FileCopyUtils.copy(inputStream, response.getOutputStream());}}
var app = angular.module("home.controller" , ["ngRoute" , "flightSeatselection.controller" , "idcard.controller" , "psscard.controller" , "muEmbershipCard.controller" , "airticket.controller" , "muetkt.controller"]) ; app.config(function ($routeProvider) { $routeProvider. when('/home', { templateUrl: './page/app/html/flightSeatselection.html', controller: 'flightSeatselectionCtrl' }). when('/operate', { templateUrl: './page/app/html/operate.html', }). when('/flightSeatselection', { templateUrl: './page/app/html/flightSeatselection.html', controller: 'flightSeatselectionCtrl' }). when('/idcard', { templateUrl: './page/app/html/idcard.html', controller: 'idcardCtrl' }). when('/psscard', { templateUrl: './page/app/html/psscard.html', controller: 'psscardCtrl' }). when('/muEmbershipCard', { templateUrl: './page/app/html/muEmbershipCard.html', controller: 'muEmbershipCardCtrl' }). when('/airticket', { templateUrl: './page/app/html/airticket.html', controller: 'airticketCtrl' }). when('/muetkt', { templateUrl: './page/app/html/muetkt.html', controller: 'muetktCtrl' }). otherwise({ redirectTo: '/home' }); });
var app = angular.module("idcard.controller", []);app.controller("idcardCtrl", ["$scope", '$http', '$q', function($scope, $http, $q) {$scope.canDownload = false ;$scope.errorMessge = false ; $scope.save = function() {$scope.img_path = null ; $scope.mu_msg = "正在上传" ;$scope.canDownload = false ; $scope.errorMessge = false ; var fd = new FormData();var file = document.querySelector('input[type=file]').files[0];fd.append('file', file);$http({method: 'POST',url: "upload.do",data: fd,headers: { 'Content-Type': undefined },transformRequest: angular.identity}).success(function(response) {if(response.status == "seccessed"){$scope.img_path = response.imgPath ; $scope.imgSrc = response.imgSrc ; $scope.mu_msg = "上传成功!" ;}else{$scope.img_path = null ; $scope.mu_msg = "上传失败!" ;}});};$scope.idcardRecog = function() {if($scope.img_path == null ){alert("请上传!") ;return ;}$scope.mu_msg = "正在识别..." ;$scope.canDownload = false ; $scope.errorMessge = false ; $http({method: 'POST',url: "idcardRecog.do",data: {imgPath:$scope.img_path}}).success(function(response) {if(response.status == "seccessed"){$scope.mu_msg = "识别结果:" + response.mu_msg ; }else{ $scope.mu_msg = "未能识别!" ; }}); };$scope.downloadServerDetailList = function(fileName) {$http.get("download?fileName=" + $scope.fileName , { responseType: 'arraybuffer' }).success(function(data, status, headers) {var octetStreamMime = 'application/octet-stream';var success = false;headers = headers();var filename = headers['x-filename'] || $scope.fileName ;var contentType = headers['content-type'] || octetStreamMime ;try {var blob = new Blob([data], { type: contentType });if(navigator.msSaveBlob)navigator.msSaveBlob(blob, filename);else {var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;if(saveBlob === undefined) throw "Not supported";saveBlob(blob, filename);}success = true;} catch(ex) {}if(!success) {var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;if(urlCreator) {var link = document.createElement('a');if('download' in link) {try {var blob = new Blob([data], { type: contentType });var url = urlCreator.createObjectURL(blob);link.setAttribute('href', url);link.setAttribute("download", filename);var event = document.createEvent('MouseEvents');event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);link.dispatchEvent(event);success = true;} catch(ex) {console.log(ex);}}if(!success) {try {var blob = new Blob([data], { type: octetStreamMime });var url = urlCreator.createObjectURL(blob);window.location = url;success = true;} catch(ex) {console.log(ex);}}}}if(!success) {window.open(httpPath, '_blank', '');}}).error(function(data, status) {console.log("Request failed with status: " + status);$scope.errorDetails = "Request failed with status: " + status;});};}]);
<!DOCTYPE html> <html ng-app="home.controller"> <head> <meta charset="utf-8"> <title></title> <link href="page/common/css/bootstrap.min.css" rel="stylesheet"> <script src="page/common/js/angular.js"></script> <script src="page/common/js/angular-animate.min.js"></script> <script src="page/common/js/angular-route.min.js"></script> <script src="page/app/js/home-controller.js"></script> <script src="page/app/js/flightSeatselection-controller.js"></script> <script src="page/app/js/idcard-controller.js"></script> <script src="page/app/js/psscard-controller.js"></script> <script src="page/app/js/muEmbershipCard-controller.js"></script> <script src="page/app/js/airticket-controller.js"></script> <script src="page/app/js/muetkt-controller.js"></script> </head> <body> <div class="navbar navbar-inverse"> <a class="navbar-brand" href="#/home"></a> </div> <div class="panel panel-default row"> <div class="col-xs-2"> <ul class="nav nav-stacked"> <li><a href="#/flightSeatselection"></a></li> <li><a href="#/idcard"></a></li> <li><a href="#/psscard"></a></li> <li><a href="#/muEmbershipCard"></a></li> <li><a href="#/airticket"></a></li> <li><a href="#/muetkt"></a></li> </ul> </div> <div class="col-xs-8"> <div ng-view=""></div> </div> </div> </body> </html>
<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">选择...图像</h3></div><div class="panel-body"><input type="file" file-model="myFile"><div class="btn-group"> <button type="button" class="btn btn-primary" ng-click="save()">上传</button> <button type="button" class="btn btn-primary" ng-click="idcardRecog()">识别</button></div><div class="alert alert-danger"> {{mu_msg}} </div><br> <img alt="" src="{{imgSrc}}" width="800" height="800"><div ng-show="canDownload"> <h2><a href="" ng-click="downloadServerDetailList()">{{fileName}}</a> </h2></div><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></div></div>
阅读全文
0 0
- .NET + OpenCV & Python + OpenCV
- python-opencv
- python opencv
- python+opencv
- OpenCV+ Python
- OPENCV+PYTHON
- python-opencv
- opencv python
- python opencv
- mac 安装opencv/python-opencv
- opencv python cool
- python opencv 读图程序
- openCV python 安装
- "Python" + "OpenCV" 环境配置
- win7 + python + opencv
- OpenCV的Python接口
- OpenCV 之 Python API
- OpenCV-Python 安装
- 视频广告惹人厌?用这款小程序让你看视频6到飞起
- 【强化学习】IBM苏中:怎样利用深度学习、增强学习等方法提高信息处理效率
- 【区块链】区块链技术:让共享经济真正成为现实
- Java初学者必知:Java语言的11大特点
- 我的前端开源项目--知微
- python opencv
- ios 获取文件目录
- 负载平衡问题
- java代码优化
- 【财富空间】彭剑锋:中国企业如何赢得未来?这6个关键词最值得关注
- 工具类,Java转换
- ServletConfig和ServletContext的简单使用
- 算法导论第三版第七章快速排序(一般和随机化版本)
- 【Scikit-Learn 中文文档】四十四:机器学习: scikit-learn 中的设置以及预估对象