版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、【精品文檔】如有侵權(quán),請聯(lián)系網(wǎng)站刪除,僅供學(xué)習(xí)與交流車牌識別Python程序.精品文檔.# -*- coding: utf-8 -*-_author_ = 'd1bysj'import pymysqldb = pymysql.connect(host = '', # 遠(yuǎn)程主機(jī)的ip地址, user = '', # MySQL用戶名 db = '', # database名 passwd = '', # 數(shù)據(jù)庫密碼 port = 3306, #數(shù)據(jù)庫監(jiān)聽端口,默認(rèn)3306 charset = "utf8&q
2、uot;) #指定utf8編碼的連接cur= db.cursor()sql="select * from sex"try: cur.execute(sql) re=cur.fetchall() for it in re: name = it0 num = it1 print(name,num)except Exception as e: raise efinally: db.close()import cv2import numpy as npfrom numpy.linalg import normimport sysimport osimport jsonSZ = 20
3、 # 訓(xùn)練圖片長寬MAX_WIDTH = 1000 # 原始圖片最大寬度Min_Area = 2000 # 車牌區(qū)域允許最大面積PROVINCE_START = 1000# 讀取圖片文件def imreadex(filename): return cv2.imdecode(np.fromfile(filename, dtype=np.uint8), cv2.IMREAD_COLOR)def point_limit(point): if point0 < 0: point0 = 0 if point1 < 0: point1 = 0# 根據(jù)設(shè)定的閾值和圖片直方圖,找出波峰,用于分隔字
4、符def find_waves(threshold, histogram): up_point = -1 # 上升點(diǎn) is_peak = False if histogram0 > threshold: up_point = 0 is_peak = True wave_peaks = for i, x in enumerate(histogram): if is_peak and x < threshold: if i - up_point > 2: is_peak = False wave_peaks.append(up_point, i) elif not is_peak
5、 and x >= threshold: is_peak = True up_point = i if is_peak and up_point != -1 and i - up_point > 4: wave_peaks.append(up_point, i) return wave_peaks# 根據(jù)找出的波峰,分隔圖片,從而得到逐個(gè)字符圖片def seperate_card(img, waves): part_cards = for wave in waves: part_cards.append(img:, wave0:wave1) return part_cards# 來
6、自opencv的sample,用于svm訓(xùn)練def deskew(img): m = cv2.moments(img) if abs(m'mu02') < 1e-2: return img.copy() skew = m'mu11' / m'mu02' M = np.float32(1, skew, -0.5 * SZ * skew, 0, 1, 0) img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR) return im
7、g# 來自opencv的sample,用于svm訓(xùn)練def preprocess_hog(digits): samples = for img in digits: gx = cv2.Sobel(img, cv2.CV_32F, 1, 0) gy = cv2.Sobel(img, cv2.CV_32F, 0, 1) mag, ang = cv2.cartToPolar(gx, gy) bin_n = 16 bin = 32(bin_n * ang / (2 * np.pi) bin_cells = bin:10, :10, bin10:, :10, bin:10, 10:, bin
8、10:, 10: mag_cells = mag:10, :10, mag10:, :10, mag:10, 10:, mag10:, 10: hists = np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells) hist = np.hstack(hists) # transform to Hellinger kernel eps = 1e-7 hist /= hist.sum() + eps hist = np.sqrt(hist) hist /= norm(hist) + eps sam
9、ples.append(hist) return np.float32(samples)# 不能保證包括所有省份provinces = "zh_cuan", "川", "zh_e", "鄂", "zh_gan", "贛", "zh_gan1", "甘", "zh_gui", "貴", "zh_gui1", "桂", "zh_hei", &
10、quot;黑", "zh_hu", "滬", "zh_ji", "冀", "zh_jin", "津", "zh_jing", "京", "zh_jl", "吉", "zh_liao", "遼", "zh_lu", "魯", "zh_meng", "蒙", "z
11、h_min", "閩", "zh_ning", "寧", "zh_qing", "靑", "zh_qiong", "瓊", "zh_shan", "陜", "zh_su", "蘇", "zh_sx", "晉", "zh_wan", "皖", "zh_xiang", &q
12、uot;湘", "zh_xin", "新", "zh_yu", "豫", "zh_yu1", "渝", "zh_yue", "粵", "zh_yun", "云", "zh_zang", "藏", "zh_zhe", "浙"class StatModel(object): def load(self, fn):
13、 self.model = self.model.load(fn) def save(self, fn): self.model.save(fn)class SVM(StatModel): def _init_(self, C=1, gamma=0.5): self.model = cv2.ml.SVM_create() self.model.setGamma(gamma) self.model.setC(C) self.model.setKernel(cv2.ml.SVM_RBF) self.model.setType(cv2.ml.SVM_C_SVC) # 訓(xùn)練svm def train(
14、self, samples, responses): self.model.train(samples, cv2.ml.ROW_SAMPLE, responses) # 字符識別 def predict(self, samples): r = self.model.predict(samples) return r1.ravel()class CardPredictor: def _init_(self): # 車牌識別的部分參數(shù)保存在js中,便于根據(jù)圖片分辨率做調(diào)整 f = open('config.js') j = json.load(f) for c in j"
15、config": print(c) if c"open": self.cfg = c.copy() break else: raise RuntimeError('沒有設(shè)置有效配置參數(shù)') def _del_(self): self.save_traindata() def train_svm(self): # 識別英文字母和數(shù)字 self.model = SVM(C=1, gamma=0.5) # 識別中文 self.modelchinese = SVM(C=1, gamma=0.5) if os.path.exists("svm.da
16、t"): self.model.load("svm.dat") else: chars_train = chars_label = for root, dirs, files in os.walk("trainchars2"): if len(os.path.basename(root) > 1: continue root_int = ord(os.path.basename(root) for filename in files: filepath = os.path.join(root, filename) digit_img =
17、cv2.imread(filepath) digit_img = cv2.cvtColor(digit_img, cv2.COLOR_BGR2GRAY) chars_train.append(digit_img) # chars_label.append(1) chars_label.append(root_int) chars_train = list(map(deskew, chars_train) chars_train = preprocess_hog(chars_train) # chars_train = chars_train.reshape(-1, 20, 20).astype
18、(np.float32) chars_label = np.array(chars_label) print(chars_train.shape) self.model.train(chars_train, chars_label) if os.path.exists("svmchinese.dat"): self.modelchinese.load("svmchinese.dat") else: chars_train = chars_label = for root, dirs, files in os.walk("traincharsCh
19、inese"): if not os.path.basename(root).startswith("zh_"): continue pinyin = os.path.basename(root) index = provinces.index(pinyin) + PROVINCE_START + 1 # 1是拼音對應(yīng)的漢字 for filename in files: filepath = os.path.join(root, filename) digit_img = cv2.imread(filepath) digit_img = cv2.cvtColor(
20、digit_img, cv2.COLOR_BGR2GRAY) chars_train.append(digit_img) # chars_label.append(1) chars_label.append(index) chars_train = list(map(deskew, chars_train) chars_train = preprocess_hog(chars_train) # chars_train = chars_train.reshape(-1, 20, 20).astype(np.float32) chars_label = np.array(chars_label)
21、print(chars_train.shape) self.modelchinese.train(chars_train, chars_label) def save_traindata(self): if not os.path.exists("svm.dat"): self.model.save("svm.dat") if not os.path.exists("svmchinese.dat"): self.modelchinese.save("svmchinese.dat") def accurate_pla
22、ce(self, card_img_hsv, limit1, limit2, color): row_num, col_num = card_img_hsv.shape:2 xl = col_num xr = 0 yh = 0 yl = row_num # col_num_limit = self.cfg"col_num_limit" row_num_limit = self.cfg"row_num_limit" col_num_limit = col_num * 0.8 if color != "green" else col_nu
23、m * 0.5 # 綠色有漸變 for i in range(row_num): count = 0 for j in range(col_num): H = card_img_hsv.item(i, j, 0) S = card_img_hsv.item(i, j, 1) V = card_img_hsv.item(i, j, 2) if limit1 < H <= limit2 and 34 < S and 46 < V: count += 1 if count > col_num_limit: if yl > i: yl = i if yh <
24、i: yh = i for j in range(col_num): count = 0 for i in range(row_num): H = card_img_hsv.item(i, j, 0) S = card_img_hsv.item(i, j, 1) V = card_img_hsv.item(i, j, 2) if limit1 < H <= limit2 and 34 < S and 46 < V: count += 1 if count > row_num - row_num_limit: if xl > j: xl = j if xr &
25、lt; j: xr = j return xl, xr, yh, yl def predict(self, car_pic): if type(car_pic) = type(""): img = imreadex(car_pic) else: img = car_pic pic_hight, pic_width = img.shape:2 if pic_width > MAX_WIDTH: resize_rate = MAX_WIDTH / pic_width img = cv2.resize(img, (MAX_WIDTH, int(pic_hight * res
26、ize_rate), interpolation=cv2.INTER_AREA) blur = self.cfg"blur" # 高斯去噪 if blur > 0: img = cv2.GaussianBlur(img, (blur, blur), 0) # 圖片分辨率調(diào)整 oldimg = img img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # equ = cv2.equalizeHist(img) # img = np.hstack(img, equ) # 去掉圖像中不會(huì)是車牌的區(qū)域 kernel = np.ones(2
27、0, 20), np.uint8) img_opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) img_opening = cv2.addWeighted(img, 1, img_opening, -1, 0); # 找到圖像邊緣 ret, img_thresh = cv2.threshold(img_opening, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) img_edge = cv2.Canny(img_thresh, 100, 200) # 使用開運(yùn)算和閉運(yùn)算讓圖像邊緣成為一個(gè)整
28、體 kernel = np.ones(self.cfg"morphologyr", self.cfg"morphologyc"), np.uint8) img_edge1 = cv2.morphologyEx(img_edge, cv2.MORPH_CLOSE, kernel) img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, kernel) # 查找圖像邊緣整體形成的矩形區(qū)域,可能有很多,車牌就在其中一個(gè)矩形區(qū)域中 image, contours, hierarchy = cv2.findC
29、ontours(img_edge2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours = cnt for cnt in contours if cv2.contourArea(cnt) > Min_Area print('len(contours)', len(contours) # 一一排除不是車牌的矩形區(qū)域 car_contours = for cnt in contours: rect = cv2.minAreaRect(cnt) area_width, area_height = rect1 if area_wid
30、th < area_height: area_width, area_height = area_height, area_width wh_ratio = area_width / area_height # print(wh_ratio) # 要求矩形區(qū)域長寬比在2到5.5之間,2到5.5是車牌的長寬比,其余的矩形排除 if wh_ratio > 2 and wh_ratio < 5.5: car_contours.append(rect) box = cv2.boxPoints(rect) box = 0(box) # oldimg = cv2.drawCo
31、ntours(oldimg, box, 0, (0, 0, 255), 2) # cv2.imshow("edge4", oldimg) # print(rect) print(len(car_contours) print("精確定位") card_imgs = # 矩形區(qū)域可能是傾斜的矩形,需要矯正,以便使用顏色定位 for rect in car_contours: if rect2 > -1 and rect2 < 1: # 創(chuàng)造角度,使得左、高、右、低拿到正確的值 angle = 1 else: angle = rect2 rect
32、 = (rect0, (rect10 + 5, rect11 + 5), angle) # 擴(kuò)大范圍,避免車牌邊緣被排除 box = cv2.boxPoints(rect) heigth_point = right_point = 0, 0 left_point = low_point = pic_width, pic_hight for point in box: if left_point0 > point0: left_point = point if low_point1 > point1: low_point = point if heigth_point1 < p
33、oint1: heigth_point = point if right_point0 < point0: right_point = point if left_point1 <= right_point1: # 正角度 new_right_point = right_point0, heigth_point1 pts2 = np.float32(left_point, heigth_point, new_right_point) # 字符只是高度需要改變 pts1 = np.float32(left_point, heigth_point, right_point) M = c
34、v2.getAffineTransform(pts1, pts2) dst = cv2.warpAffine(oldimg, M, (pic_width, pic_hight) point_limit(new_right_point) point_limit(heigth_point) point_limit(left_point) card_img = dstint(left_point1):int(heigth_point1), int(left_point0):int(new_right_point0) card_imgs.append(card_img) # cv2.imshow(&q
35、uot;card", card_img) # cv2.waitKey(0) elif left_point1 > right_point1: # 負(fù)角度 new_left_point = left_point0, heigth_point1 pts2 = np.float32(new_left_point, heigth_point, right_point) # 字符只是高度需要改變 pts1 = np.float32(left_point, heigth_point, right_point) M = cv2.getAffineTransform(pts1, pts2) d
36、st = cv2.warpAffine(oldimg, M, (pic_width, pic_hight) point_limit(right_point) point_limit(heigth_point) point_limit(new_left_point) card_img = dstint(right_point1):int(heigth_point1), int(new_left_point0):int(right_point0) card_imgs.append(card_img) # cv2.imshow("card", card_img) # cv2.wa
37、itKey(0) # 開始使用顏色定位,排除不是車牌的矩形,目前只識別藍(lán)、綠、黃車牌 colors = for card_index, card_img in enumerate(card_imgs): green = yello = blue = black = white = 0 card_img_hsv = cv2.cvtColor(card_img, cv2.COLOR_BGR2HSV) # 有轉(zhuǎn)換失敗的可能,原因來自于上面矯正矩形出錯(cuò) if card_img_hsv is None: continue row_num, col_num = card_img_hsv.shape:2 c
38、ard_img_count = row_num * col_num for i in range(row_num): for j in range(col_num): H = card_img_hsv.item(i, j, 0) S = card_img_hsv.item(i, j, 1) V = card_img_hsv.item(i, j, 2) if 11 < H <= 34 and S > 34: # 圖片分辨率調(diào)整 yello += 1 elif 35 < H <= 99 and S > 34: # 圖片分辨率調(diào)整 green += 1 elif
39、99 < H <= 124 and S > 34: # 圖片分辨率調(diào)整 blue += 1 if 0 < H < 180 and 0 < S < 255 and 0 < V < 46: black += 1 elif 0 < H < 180 and 0 < S < 43 and 221 < V < 225: white += 1 color = "no" limit1 = limit2 = 0 if yello * 2 >= card_img_count: color = &qu
40、ot;yello" limit1 = 11 limit2 = 34 # 有的圖片有色偏偏綠 elif green * 2 >= card_img_count: color = "green" limit1 = 35 limit2 = 99 elif blue * 2 >= card_img_count: color = "blue" limit1 = 100 limit2 = 124 # 有的圖片有色偏偏紫 elif black + white >= card_img_count * 0.7: # TODO color = &
41、quot;bw" print(color) colors.append(color) print(blue, green, yello, black, white, card_img_count) # cv2.imshow("color", card_img) # cv2.waitKey(0) if limit1 = 0: continue # 以上為確定車牌顏色 # 以下為根據(jù)車牌顏色再定位,縮小邊緣非車牌邊界 xl, xr, yh, yl = self.accurate_place(card_img_hsv, limit1, limit2, color) if
42、 yl = yh and xl = xr: continue need_accurate = False if yl >= yh: yl = 0 yh = row_num need_accurate = True if xl >= xr: xl = 0 xr = col_num need_accurate = True card_imgscard_index = card_imgyl:yh, xl:xr if color != "green" or yl < (yh - yl) / 4 else card_img yl - ( yh - yl) / 4:y
43、h, xl:xr if need_accurate: # 可能x或y方向未縮小,需要再試一次 card_img = card_imgscard_index card_img_hsv = cv2.cvtColor(card_img, cv2.COLOR_BGR2HSV) xl, xr, yh, yl = self.accurate_place(card_img_hsv, limit1, limit2, color) if yl = yh and xl = xr: continue if yl >= yh: yl = 0 yh = row_num if xl >= xr: xl = 0 xr = col_num card_imgscard_index = card_imgyl:yh, xl:xr if color != "green" or yl < (yh - yl) / 4 else card_img yl - ( yh - yl) / 4:yh, xl:xr # 以上為車牌定位 # 以下為識別車牌中的字符 predict_result = roi = None card_color = None for i, color in enumerate(colors): if color in ("blue", &q
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 狼獲獎(jiǎng)?wù)n件教學(xué)課件
- 統(tǒng)計(jì)分析軟件模擬試題三及答案
- 飛向太空的航程說課稿
- 隊(duì)列口令說課稿
- 適合小班課件教學(xué)課件
- 怎樣評價(jià)課件教學(xué)課件
- 南京工業(yè)大學(xué)浦江學(xué)院《公益營銷》2021-2022學(xué)年第一學(xué)期期末試卷
- 南京工業(yè)大學(xué)浦江學(xué)院《籌資原理和技巧》2022-2023學(xué)年第一學(xué)期期末試卷
- 秸稈打捆協(xié)議書(2篇)
- 南京工業(yè)大學(xué)《應(yīng)用統(tǒng)計(jì)學(xué)》2023-2024學(xué)年第一學(xué)期期末試卷
- 2025數(shù)學(xué)步步高大一輪復(fù)習(xí)講義人教A版復(fù)習(xí)講義含答案
- 車站調(diào)度員技能大賽理論考試題庫(單選、多選題)
- 2024-2030年樺樹汁行業(yè)市場現(xiàn)狀供需分析及重點(diǎn)企業(yè)投資評估規(guī)劃分析研究報(bào)告
- 創(chuàng)新創(chuàng)業(yè)心智模式探索智慧樹知到期末考試答案章節(jié)答案2024年天津農(nóng)學(xué)院
- 2024年九年級化學(xué)上冊 第6單元 碳和碳的氧化物教案 (新版)新人教版
- 2024詳解新版《公司法》課件
- 醫(yī)院法律、法規(guī)培訓(xùn)課件
- 2024年高考作文真題解讀(立意+提綱+范文+總評)
- 美沙酮門診管理新規(guī)制度
- 2024年河南省信陽市新縣中考一模數(shù)學(xué)試題 【含答案解析】
- 正常與心梗心電圖
評論
0/150
提交評論