車牌模擬生成器:Python代碼實現與商業應用前景
引言
在智慧城市建設和汽車行業數字化浪潮中,車牌作為車輛的唯一標識,其相關技術應用正變得越來越重要。今天我們將介紹一個基于Python的車牌模擬生成器,探討其技術實現、功能特點以及潛在的商業價值。
【注意】
在線生成隨機或自定義的中國車牌,支持多種車牌類型和樣式,僅用于模型數據測試、車牌識別系統的演示效果等,切勿用于商業用途和不合法用途,否則自己將承擔相關責任,與本工具無關。
【需要的素材】
1、需要各個省市的簡稱:
由于用到了opencv,建議將圖片和具體的車牌號做個映射關系:
【效果圖】
映射關系文件 font_mappings.txt
云=yunnan
京=beijing
冀=hebei
晉=shanxi
蒙=neimenggu
遼=liaoning
吉=jilin
黑=heilongjiang
滬=shanghai
蘇=jiangsu
浙=zhejiang
皖=anhui
閩=fujian
贛=jiangxi
魯=shandong
豫=henan
鄂=hubei
湘=hunan
粵=guangdong
桂=guangxi
瓊=hainan
渝=chongqing
川=sichuan
貴=guizhou
藏=xizang
陜=shanxi_s
甘=gansu
青=qinghai
寧=ningxia
新=xinjiang
津=tianjin
港=gang
澳=ao
使=shi
領=ling
學=xue
警=jing
掛=gua
需求分析
車牌模擬生成在多個領域有著廣泛的應用需求:
- 軟件開發與測試?:智能交通系統、停車場管理系統需要大量車牌數據進行測試
- 教育培訓?:駕校、交通法規培訓需要示例車牌進行教學演示
影視制作?:影視劇中需要符合規定的虛擬車牌避免侵權問
數據分析?:交通流量模擬、城市規劃需要車牌數據支持
功能特點
我們的車牌模擬生成器具備以下核心功能:
1. 符合中國車牌標準
- ?
支持普通藍牌和新能源綠牌兩種格式
- ?
遵循中國車牌編號規則,排除易混淆字母(O/I)
- ?
省份簡稱符合國家標準
2. 靈活生成模式
- ?
可指定生成特定類型車牌
- ?
支持完全隨機生成模式
- ?
生成數量可自定義擴展
3. 高度可定制化代碼結構清晰,易于擴展其他類型車牌
生成規則可調整,滿足不同場景需求
代碼結構清晰,易于擴展其他類型車牌
由于服務端是python,這里給出的是部分核心邏輯代碼,需要自己搭建。
【核心代碼實現,流程參考】
import random
import stringclass LicensePlateGenerator:"""車牌生成器類"""def __init__(self):# 省份簡稱列表self.provinces = ['京', '津', '冀', '晉', '蒙', '遼', '吉', '黑', '滬', '蘇','浙', '皖', '閩', '贛', '魯', '豫', '鄂', '湘', '粵', '桂','瓊', '渝', '川', '貴', '云', '藏', '陜', '甘', '青', '寧', '新']# 車牌字母列表(排除O和I)self.letters = [c for c in string.ascii_uppercase if c not in ['O', 'I']]def generate_plate(self, plate_type=None, province=None):"""生成車牌號碼:param plate_type: 車牌類型('normal'普通/'new_energy'新能源):param province: 指定省份簡稱:return: 車牌號碼字符串"""# 確定省份if province and province in self.provinces:province_char = provinceelse:province_char = random.choice(self.provinces)# 確定車牌類型if plate_type is None:plate_type = random.choice(['normal', 'new_energy'])# 生成普通車牌if plate_type == 'normal':return self._generate_normal_plate(province_char)# 生成新能源車牌elif plate_type == 'new_energy':return self._generate_new_energy_plate(province_char)def _generate_normal_plate(self, province):"""生成普通藍牌"""plate = province + random.choice(self.letters)# 生成5位序號for _ in range(5):if random.random() < 0.3:plate += random.choice(self.letters)else:plate += random.choice(string.digits)return platedef _generate_new_energy_plate(self, province):"""生成新能源綠牌"""plate = province + random.choice(self.letters)plate += random.choice(['D', 'F']) # D=純電, F=混動plate += ''.join(random.choices(string.digits, k=5))return plate# 使用示例
if __name__ == "__main__":generator = LicensePlateGenerator()# 生成10個隨機車牌print("隨機車牌示例:")for i in range(10):plate_type = random.choice(['normal', 'new_energy'])plate = generator.generate_plate(plate_type)print(f"{i+1}. {'普通車牌' if plate_type == 'normal' else '新能源車牌'}: {plate}")# 生成特定省份車牌print("\n北京車牌示例:")for i in range(3):print(f"{i+1}. {generator.generate_plate('normal', '京')}")
【生成車牌、計算數字邊框等算法】
# -*- coding: utf-8 -*-
import numpy as np
import cv2, os, argparse
from glob import glob
from tqdm import tqdmfrom plate_number import random_select, generate_plate_number_white, generate_plate_number_yellow_xue
from plate_number import generate_plate_number_black_gangao, generate_plate_number_black_shi, generate_plate_number_black_ling
from plate_number import generate_plate_number_blue, generate_plate_number_yellow_gua
from plate_number import letters, digits# 加載中文字符到英文文件名的映射
def load_font_mappings():mappings = {}try:with open('font_mappings.txt', 'r', encoding='utf-8') as f:for line in f:if '=' in line:cn, en = line.strip().split('=', 1)mappings[cn] = enexcept Exception as e:print(f"警告: 無法加載字體映射文件,錯誤: {e}")return mappings# 中文到英文的映射
CHINESE_TO_ENGLISH = load_font_mappings()
# 英文到中文的反向映射
ENGLISH_TO_CHINESE = {v: k for k, v in CHINESE_TO_ENGLISH.items()}def get_location_data(length=7, split_id=1, height=140):"""獲取車牌號碼在底牌中的位置length: 車牌字符數,7或者8,7為普通車牌、8為新能源車牌split_id: 分割空隙height: 車牌高度,對應單層和雙層車牌"""# 字符位置location_xy = np.zeros((length, 4), dtype=np.int32)# 單層車牌高度if height == 140:# 單層車牌,y軸坐標固定location_xy[:, 1] = 25location_xy[:, 3] = 115# 螺栓間隔step_split = 34 if length == 7 else 49# 字符間隔step_font = 12 if length == 7 else 9# 字符寬度width_font = 45for i in range(length):if i == 0:location_xy[i, 0] = 15elif i == split_id:location_xy[i, 0] = location_xy[i - 1, 2] + step_splitelse:location_xy[i, 0] = location_xy[i - 1, 2] + step_font# 新能源車牌if length == 8 and i > 0:width_font = 43location_xy[i, 2] = location_xy[i, 0] + width_fontelse:# 雙層車牌第一層location_xy[0, :] = [110, 15, 190, 75]location_xy[1, :] = [250, 15, 330, 75]# 第二層width_font = 65step_font = 15for i in range(2, length):location_xy[i, 1] = 90location_xy[i, 3] = 200if i == 2:location_xy[i, 0] = 27else:location_xy[i, 0] = location_xy[i - 1, 2] + step_fontlocation_xy[i, 2] = location_xy[i, 0] + width_fontreturn location_xy# 字符貼上底板
def copy_to_image_multi(img, font_img, bbox, bg_color, is_red):x1, y1, x2, y2 = bboxfont_img = cv2.resize(font_img, (x2 - x1, y2 - y1))img_crop = img[y1: y2, x1: x2, :]if is_red:img_crop[font_img < 200, :] = [0, 0, 255]elif 'blue' in bg_color or 'black' in bg_color:img_crop[font_img < 200, :] = [255, 255, 255]else:img_crop[font_img < 200, :] = [0, 0, 0]return imgclass MultiPlateGenerator:def __init__(self, adr_plate_model, adr_font):# 車牌底板路徑self.adr_plate_model = adr_plate_model# 車牌字符路徑# 如果存在英文目錄,則使用英文目錄self.adr_font = 'font_model_english' if os.path.exists('font_model_english') else adr_font# 車牌字符圖片,預存處理self.font_imgs = {}# 獲取所有jpg文件font_filenames = []for root, dirs, files in os.walk(self.adr_font):for file in files:if file.lower().endswith('.jpg'):font_filenames.append(os.path.join(root, file))for font_filename in font_filenames:# 嘗試讀取文件,如果失敗則跳過try:font_img = cv2.imread(font_filename, cv2.IMREAD_GRAYSCALE)if font_img is None:continueif '140' in font_filename:font_img = cv2.resize(font_img, (45, 90))elif '220' in font_filename:font_img = cv2.resize(font_img, (65, 110))elif font_filename.split('_')[-1].split('.')[0] in letters + digits:font_img = cv2.resize(font_img, (43, 90))# 獲取文件名作為keybasename = os.path.basename(font_filename).split('.')[0]# 保存原始文件名映射self.font_imgs[basename] = font_img# 對于英文文件名,我們也建立到中文字符的映射for en, cn in ENGLISH_TO_CHINESE.items():if en in basename:# 構建中文文件名格式的keyparts = basename.split('_')for i, part in enumerate(parts):if part == en:parts[i] = cnchinese_key = '_'.join(parts)self.font_imgs[chinese_key] = font_imgbreakexcept Exception as e:print(f"警告: 無法讀取或處理文件 {font_filename}, 錯誤: {e}")continue# 字符位置self.location_xys = {}for i in [7, 8]:for j in [1, 2, 4]:for k in [140, 220]:self.location_xys['{}_{}_{}'.format(i, j, k)] = \get_location_data(length=i, split_id=j, height=k)# 獲取字符位置def get_location_multi(self, plate_number, height=140):length = len(plate_number)if '警' in plate_number:split_id = 1elif '使' in plate_number:split_id = 4else:split_id = 2return self.location_xys['{}_{}_{}'.format(length, split_id, height)]# 隨機生成車牌號碼,獲取底板顏色、單雙層def generate_plate_number(self):rate = np.random.random(1)if rate > 0.4:# 藍牌plate_number = generate_plate_number_blue(length=random_select([7, 8]))else:# 白牌、黃牌教練車、黃牌掛車、黑色港澳、黑色使、領館generate_plate_number_funcs = [generate_plate_number_white,generate_plate_number_yellow_xue,generate_plate_number_yellow_gua,generate_plate_number_black_gangao,generate_plate_number_black_shi,generate_plate_number_black_ling]plate_number = random_select(generate_plate_number_funcs)()# 車牌底板顏色bg_color = random_select(['blue'] + ['yellow'])if len(plate_number) == 8:bg_color = random_select(['green_car'] * 10 + ['green_truck'])elif len(set(plate_number) & set(['使', '領', '港', '澳'])) > 0:bg_color = 'black'elif '警' in plate_number or plate_number[0] in letters:bg_color = 'white'elif len(set(plate_number) & set(['學', '掛'])) > 0:bg_color = 'yellow'is_double = random_select([False] + [True] * 3)if '使' in plate_number:bg_color = 'black_shi'if '掛' in plate_number:# 掛車雙層is_double = Trueelif len(set(plate_number) & set(['使', '領', '港', '澳', '學', '警'])) > 0 \or len(plate_number) == 8 or bg_color == 'blue':# 使領港澳學警、新能源、藍色都是單層is_double = False# special,首字符為字母、單層則是軍車if plate_number[0] in letters and not is_double:bg_color = 'white_army'return plate_number, bg_color, is_double# 隨機生成車牌圖片def generate_plate(self, enhance=False):plate_number, bg_color, is_double = self.generate_plate_number()height = 220 if is_double else 140# 獲取底板圖片# print(plate_number, height, bg_color, is_double)number_xy = self.get_location_multi(plate_number, height)# 讀取底板圖片,確保中文文件名正確處理plate_model_path = os.path.join(self.adr_plate_model, '{}_{}.PNG'.format(bg_color, height))img_plate_model = cv2.imread(plate_model_path)if img_plate_model is None:print(f"警告: 無法讀取底板圖片 {plate_model_path}")# 使用默認藍色底板圖片作為備選default_path = os.path.join(self.adr_plate_model, 'blue_140.PNG')img_plate_model = cv2.imread(default_path)if img_plate_model is None:raise FileNotFoundError(f"無法讀取默認底板圖片 {default_path}")img_plate_model = cv2.resize(img_plate_model, (440 if len(plate_number) == 7 else 480, height))for i in range(len(plate_number)):if len(plate_number) == 8:# 新能源key = 'green_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = 'green_{}'.format(en_char)font_img = self.font_imgs[key]else:if '{}_{}'.format(height, plate_number[i]) in self.font_imgs:key = '{}_{}'.format(height, plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '{}_{}'.format(height, en_char)font_img = self.font_imgs[key]else:# 雙層車牌字體庫if i < 2:key = '220_up_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '220_up_{}'.format(en_char)font_img = self.font_imgs[key]else:key = '220_down_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '220_down_{}'.format(en_char)font_img = self.font_imgs[key]# 字符是否紅色if (i == 0 and plate_number[0] in letters) or plate_number[i] in ['警', '使', '領']:is_red = Trueelif i == 1 and plate_number[0] in letters and np.random.random(1) > 0.5:# second letter of army plateis_red = Trueelse:is_red = Falseif enhance:k = np.random.randint(1, 6)kernel = np.ones((k, k), np.uint8)if np.random.random(1) > 0.5:font_img = np.copy(cv2.erode(font_img, kernel, iterations=1))else:font_img = np.copy(cv2.dilate(font_img, kernel, iterations=1))# 貼上底板img_plate_model = copy_to_image_multi(img_plate_model, font_img,number_xy[i, :], bg_color, is_red)img_plate_model = cv2.blur(img_plate_model, (3, 3))return img_plate_model, number_xy, plate_number, bg_color, is_doubledef generate_plate_special(self, plate_number, bg_color, is_double, enhance=False):"""生成特定號碼、顏色車牌:param plate_number: 車牌號碼:param bg_color: 背景顏色,black/black_shi(使領館)/blue/green_car(新能源轎車)/green_truck(新能源卡車)/white/white_army(軍隊)/yellow:param is_double: 是否雙層:param enhance: 圖像增強:return: 車牌圖"""height = 220 if is_double else 140# print(plate_number, height, bg_color, is_double)number_xy = self.get_location_multi(plate_number, height)img_plate_model = cv2.imread(os.path.join(self.adr_plate_model, '{}_{}.PNG'.format(bg_color, height)))img_plate_model = cv2.resize(img_plate_model, (440 if len(plate_number) == 7 else 480, height))for i in range(len(plate_number)):if len(plate_number) == 8:# 新能源key = 'green_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = 'green_{}'.format(en_char)font_img = self.font_imgs[key]else:if '{}_{}'.format(height, plate_number[i]) in self.font_imgs:key = '{}_{}'.format(height, plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '{}_{}'.format(height, en_char)font_img = self.font_imgs[key]else:if i < 2:key = '220_up_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '220_up_{}'.format(en_char)font_img = self.font_imgs[key]else:key = '220_down_{}'.format(plate_number[i])# 如果找不到中文key,嘗試使用英文keyif key not in self.font_imgs:# 檢查字符是否是中文字符,如果是則轉換為英文char = plate_number[i]if char in CHINESE_TO_ENGLISH:en_char = CHINESE_TO_ENGLISH[char]key = '220_down_{}'.format(en_char)font_img = self.font_imgs[key]if (i == 0 and plate_number[0] in letters) or plate_number[i] in ['警', '使', '領']:is_red = Trueelif i == 1 and plate_number[0] in letters and np.random.random(1) > 0.5:# second letter of army plateis_red = Trueelse:is_red = Falseif enhance:k = np.random.randint(1, 6)kernel = np.ones((k, k), np.uint8)if np.random.random(1) > 0.5:font_img = np.copy(cv2.erode(font_img, kernel, iterations=1))else:font_img = np.copy(cv2.dilate(font_img, kernel, iterations=1))img_plate_model = copy_to_image_multi(img_plate_model, font_img,number_xy[i, :], bg_color, is_red)# is_double = 'double' if is_double else 'single'img_plate_model = cv2.blur(img_plate_model, (3, 3))return img_plate_modeldef parse_args():parser = argparse.ArgumentParser(description='中國車牌生成器')parser.add_argument('--number', default=10, type=int, help='生成車牌數量')parser.add_argument('--save-adr', default='multi_val', help='車牌保存路徑')args = parser.parse_args()return argsdef mkdir(path):try:os.makedirs(path)except:passif __name__ == '__main__':args = parse_args()print(args)# 隨機生成車牌print('save in {}'.format(args.save_adr))mkdir(args.save_adr)generator = MultiPlateGenerator('plate_model', 'font_model')for i in tqdm(range(args.number)):img, number_xy, gt_plate_number, bg_color, is_double = generator.generate_plate()# 使用cv2.imencode和open函數來正確處理中文文件名save_path = os.path.join(args.save_adr, '{}_{}_{}.jpg'.format(gt_plate_number, bg_color, is_double))try:# 將圖像編碼為JPEG格式success, encoded_img = cv2.imencode('.jpg', img)if success:# 使用open函數以二進制寫入模式保存文件with open(save_path, 'wb') as f:f.write(encoded_img.tobytes())else:print(f"警告: 無法編碼圖像 {save_path}")except Exception as e:print(f"警告: 無法保存圖像 {save_path}, 錯誤: {e}")
商業應用前景
1. 軟件開發服務
- ?
為智能交通系統提供測試數據生成服務
- ?
向停車場管理系統開發商提供車牌模擬解決方案
- ?
為駕考系統提供虛擬車牌生成功能
2. 數據服務業務
- ?
向研究機構提供交通模擬數據
- ?
為城市規劃部門提供車輛流量預測數據支持
- ?
向廣告公司提供區域車輛分布分析數據
3. 教育培訓應用
- ?
開發交通法規教學工具
- ?
為駕校提供理論考試模擬系統
- ?
制作交通安全教育材料
4. 增值服務擴展
- ?
添加車牌識別驗證功能
- ?
開發車牌樣式自定義功能
- ?
增加多國車牌生成支持
技術拓展方向
1、增加圖像生成功能?:將車牌文本轉換為真實車牌圖像
?2、添加驗證算法?:驗證生成的車牌是否符合編碼規則
3、支持更多車牌類型?:擴展至武警車牌、領事館車牌等特殊類型
4、?開發API接口?:提供Web服務供第三方調用
車牌模擬生成器雖是一個小型工具,但其應用場景廣泛,商業價值可觀。
【最后注意】:
在線生成隨機或自定義的中國車牌,支持多種車牌類型和樣式,僅用于模型數據測試、演示效果等,切勿用于商業用途和不合法用途,否則自己將承擔相關責任,與本工具無關。
工具截圖:可以自己開發一個,提供下載地址
通過網盤分享的文件(網盤中是編譯好的可以運行的exe):車牌模擬生成demo
鏈接: https://pan.baidu.com/s/1WBzzd3qNpD8m837wqfgVBA?pwd=tgp4 提取碼: tgp4?
生成的藍牌、綠牌、黑、白、黃牌如下:
模擬生成效果:
感謝您的閱讀和支持,歡迎點贊拍磚!