Commit fbe610a4 by 杨林龙

验证OCR获取车架号功能

1 parent fa16ac4e
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
import re
# load model
# Paddleocr目前支持中英文、英文、法语、德语、韩语、日语,可以通过修改 lang参数进行切换
# lang参数依次为`ch`, `en`, `french`, `german`, `korean`, `japan`
ocr = PaddleOCR(
lang="ch",
use_gpu=False,
# use_gpu=True,
det_model_dir="ch_ppocr_server_v2.0_det_infer/",
cls_model_dir="ch_ppocr_mobile_v2.0_cls_infer/",
rec_model_dir="ch_ppocr_server_v2.0_rec_infer/",
)
class AutoIdentify(object):
"""
自动识别照片service
"""
def __init__(self, img_path):
self.img_path = img_path
def identify(self):
"""
识别照片
:return: 车牌号
"""
result = ocr.ocr(self.img_path, cls=True)
flattened_list = self.flatten_list(result)
for line in flattened_list:
print(line)
if self.validate_license_plate(str(line).replace("·", "")):
return str(line).replace("·", "")
def flatten_list(self, nested_list):
flattened_list = []
for item in nested_list:
if isinstance(item, list):
flattened_list.extend(self.flatten_list(item))
elif isinstance(item, tuple):
for value in item:
flattened_list.append(value)
else:
# flattened_list.append(item)
pass
return flattened_list
def validate_license_plate(self, plate_number):
pattern = (
r"^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}"
r"[A-HJ-NP-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$"
)
# pattern 是匹配车牌号的正则表达式
match = re.match(pattern, str(plate_number))
if match:
return True
else:
return False
# 导入pymysql模块
import os
import random
import time
import pymysql
import requests
# 连接database
conn = pymysql.connect(
host="192.168.5.1",
port=3307,
user="user_yangll",
password="vGxw9jWg",
database="glsx_car_service",
charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
SQL = """
select sof.*,so.vin_no from sys_order_file sof LEFT JOIN sys_order so ON so.id = sof.order_id
WHERE so.order_source = 'pazl' AND sof.file_name = '三码合一';
"""
# 执行SQL语句
cursor.execute(SQL)
# 获取查询结果
result = cursor.fetchall()
def generate_random_filename():
timestamp = int(time.time()) # 获取当前时间戳
random_number = random.randint(1000, 9999) # 生成一个随机数
filename = f"file_{timestamp}_{random_number}" # 创建文件名
return filename
def get_extension(filename):
parts = filename.split(".")
extension = parts[-1]
return extension
def get_project_root():
# 获取当前脚本文件的路径
current_file = os.path.abspath(__file__)
# 获取当前项目的根目录
project_root = os.path.dirname(os.path.dirname(current_file))
print(project_root)
return project_root
# 处理查询结果
# 生成训练数据集
for index, row in enumerate(result[0:5000]):
print(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
response = requests.get(network_img_path)
except Exception as e:
response = requests.get(network_img_path)
path = os.path.join(
get_project_root(), "Identify_vinandsn", "train", "threecode", complete_filename
)
with open(path, "wb") as file:
file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001)
print("File downloaded successfully.")
# 生成测试数据集
for index, row in enumerate(result[-5000:]):
print(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
response = requests.get(network_img_path)
except Exception as e:
response = requests.get(network_img_path)
path = os.path.join(
get_project_root(), "Identify_vinandsn", "validation", "threecode", complete_filename
)
with open(path, "wb") as file:
file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001)
print("File downloaded successfully.")
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
# 导入pymysql模块
import os
import random
import time
import pymysql
import requests
# 连接database
conn = pymysql.connect(
host="192.168.3.227",
port=3307,
user="dev_user",
password="df234fl",
database="glsx_car_service",
charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
cursor = conn.cursor()
# 定义要执行的SQL语句
SQL = """
select sof.*,so.vin_no from sys_order_file sof LEFT JOIN sys_order so ON so.id = sof.order_id
WHERE so.order_source = 'pazl' AND sof.file_name = '三码合一';
"""
# 执行SQL语句
cursor.execute(SQL)
# 获取查询结果
result = cursor.fetchall()
def generate_random_filename():
timestamp = int(time.time()) # 获取当前时间戳
random_number = random.randint(1000, 9999) # 生成一个随机数
filename = f"file_{timestamp}_{random_number}" # 创建文件名
return filename
def get_extension(filename):
parts = filename.split(".")
extension = parts[-1]
return extension
def get_project_root():
# 获取当前脚本文件的路径
current_file = os.path.abspath(__file__)
# 获取当前项目的根目录
project_root = os.path.dirname(os.path.dirname(current_file))
print(project_root)
return project_root
# 处理查询结果
# 生成训练数据集
for index, row in enumerate(result[0:5000]):
print(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
response = requests.get(network_img_path)
except Exception as e:
response = requests.get(network_img_path)
path = os.path.join(
get_project_root(), "Identify_vinandsn", "train", "threecode", complete_filename
)
with open(path, "wb") as file:
file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001)
print("File downloaded successfully.")
# 生成测试数据集
for index, row in enumerate(result[-5000:]):
print(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
response = requests.get(network_img_path)
except Exception as e:
response = requests.get(network_img_path)
path = os.path.join(
get_project_root(),
"Identify_vinandsn",
"validation",
"threecode",
complete_filename,
)
with open(path, "wb") as file:
file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001)
print("File downloaded successfully.")
# 关闭光标对象
cursor.close()
# 关闭数据库连接
conn.close()
from PIL import Image
# 加载原始图像
image_path = "./train/threecode/file_1704852415_6623.jpg"
original_image = Image.open(image_path)
# 放大图片
scale_factor = 2 # 放大倍数
scaled_image = original_image.resize(
(original_image.width * scale_factor, original_image.height * scale_factor)
)
# 裁剪放大后的图片
crop_left = scaled_image.width // 2 - original_image.width // 2 # 裁剪左上角 x 坐标
crop_top = scaled_image.height // 2 - original_image.height // 2 # 裁剪左上角 y 坐标
crop_width = original_image.width # 裁剪宽度
crop_height = original_image.height # 裁剪高度
cropped_image = scaled_image.crop(
(crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
)
# 保存裁剪后的图片
cropped_image.save("cropped_image.jpg")
import win32com.client
# 创建 Shell 对象
shell = win32com.client.Dispatch("WScript.Shell")
# 获取字体集合
font_collection = shell.Environment("PROCESS").items("SystemRoot") + "\\Fonts"
# 遍历字体集合
for font_file in font_collection:
print(font_file)
import cv2
from PIL import Image, ImageDraw, ImageFont
import numpy as np
# 加载图像
image_path = "./train/threecode/file_1704852415_6623.jpg"
image = cv2.imread(image_path)
# 转换图像色彩空间(由 BGR 转换为 RGB)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# 创建 PIL 图像对象
pil_image = Image.fromarray(image_rgb)
# 创建绘图对象
draw = ImageDraw.Draw(pil_image)
# 设置字体和字号
font_path = "C:\\Windows\\Fonts\\FORTE.TTF" # 字体文件路径
font_size = 50
font = ImageFont.truetype(font_path, font_size)
# 设置文字内容和位置
text = "Hello, World!"
text_position = (50, 50)
# 设置加粗效果的偏移量
bold_offset = 2
# 绘制加粗字体的文字
bold_text_position = (text_position[0] + bold_offset, text_position[1] + bold_offset)
draw.text(bold_text_position, text, font=font, fill="white")
draw.text(text_position, text, font=font, fill="black")
# 转换回 OpenCV 图像格式(由 RGB 转换为 BGR)
image_with_bold_text = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
# 保存带有加粗字体的图像
output_path = "output.jpg"
cv2.imwrite(output_path, image_with_bold_text)
# 导入pymysql模块
import glob
import os
import random
import re
import time
from math import sqrt
import cv2
import numpy as np
import pymysql
import requests
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
from pyzbar.pyzbar import decode
# 连接database
conn_dev = pymysql.connect(
host="192.168.3.227",
port=3306,
user="dev_user",
password="df234fl",
database="glsx_car_service",
charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
cursor_dev = conn_dev.cursor()
# load model
# Paddleocr目前支持中英文、英文、法语、德语、韩语、日语,可以通过修改 lang参数进行切换
# lang参数依次为`ch`, `en`, `french`, `german`, `korean`, `japan`
ocr = PaddleOCR(
use_angle_cls=True,
# use_angle_cls=False,
lang="ch",
# use_gpu=False,
use_gpu=True,
use_tensorrt=True,
det_algorithm="DB",
# det_algorithm="EAST",
det_db_score_mode="slow",
# use_space_char=False, #不可用
det_model_dir="ch_ppocr_server_v4.0_det_infer/",
cls_model_dir="ch_ppocr_mobile_v4.0_cls_infer/",
rec_model_dir="ch_ppocr_server_v4.0_rec_infer/",
det_db_thresh=0.1,
det_db_box_thresh=0.1,
det_db_unclip_ratio=2.0,
max_batch_size=20,
use_dilation=True,
# rec_algorithm="SVTR_LCNet",
)
# 连接database
# conn = pymysql.connect(
# host="192.168.5.1",
# port=3307,
# user="user_yangll",
# password="vGxw9jWg",
# database="glsx_car_service",
# charset="utf8",
# )
# # 得到一个可以执行SQL语句的光标对象
# cursor = conn.cursor()
# # 定义要执行的SQL语句
# SQL = """
# select sof.*,so.vin_no from sys_order_file sof LEFT JOIN sys_order so ON so.id = sof.order_id
# WHERE so.order_source = 'pazl' AND sof.file_name = '三码合一';
# """
# # 执行SQL语句
# cursor.execute(SQL)
# # 获取查询结果
# result = cursor.fetchall()
# 定义要执行的SQL语句
SQL = """
select * from sys_order_file_ocr sofo
"""
# 执行SQL语句
cursor_dev.execute(SQL)
# 获取查询结果
result = cursor_dev.fetchall()
def generate_random_filename():
timestamp = int(time.time()) # 获取当前时间戳
random_number = random.randint(1000, 9999) # 生成一个随机数
filename = f"file_{timestamp}_{random_number}" # 创建文件名
return filename
def get_extension(filename):
parts = filename.split(".")
extension = parts[-1]
return extension
def get_project_root():
# 获取当前脚本文件的路径
current_file = os.path.abspath(__file__)
# 获取当前项目的根目录
project_root = os.path.dirname(os.path.dirname(current_file))
print(project_root)
return project_root
def flatten_list(nested_list):
flattened_list = []
for item in nested_list:
if isinstance(item, list):
flattened_list.extend(flatten_list(item))
elif isinstance(item, tuple):
for value in item:
if type(value) in (int, float):
if value > 1.0:
flattened_list.append(value)
else:
flattened_list.append(value)
else:
# flattened_list.append(item)
pass
return flattened_list
def validate_vin(item):
pattern = r"^(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})$"
# pattern 是匹配车牌号的正则表达式
match = re.match(pattern, str(item))
if match:
return True
else:
return False
def extract_vin(string):
pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})"
match = re.search(pattern, string)
if match:
vin = match.group()
return vin
else:
return None
# 下载图片数据
for index, row in enumerate(result):
print(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
response = requests.get(network_img_path)
except Exception as e:
response = requests.get(network_img_path)
path = os.path.join(
get_project_root(), "Identify_vinandsn", "train", "threecode", complete_filename
)
with open(path, "wb") as file:
file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001)
print("File downloaded successfully.")
original_image = Image.open(path)
# 放大图片
scale_factor = 5 # 放大倍数
# scaled_image = original_image.resize(
# (original_image.width * scale_factor, original_image.height * scale_factor)
# )
dst = original_image.resize(
(original_image.width * scale_factor, original_image.height * scale_factor)
)
result = ocr.ocr(np.asarray(dst), cls=True)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
# 使用正则表达式进行过滤 获取车架号
vin_str = ""
for item in result_list:
print(item)
vin_check = validate_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(str(row))
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr (order_id,file_id,db_vin,ocr_vin,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{vin_str}',sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_vin_check_ocr (order_id,file_id,db_vin,ocr_vin,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}',null,sysdate())
"""
# 执行SQL语句
print(SQL02)
cursor_dev.execute(SQL02)
conn_dev.commit()
# # 关闭光标对象
# cursor.close()
# # 关闭数据库连接
# conn.close()
# 关闭光标对象
cursor_dev.close()
# 关闭数据库连接
conn_dev.close()
import glob
import os
from math import sqrt
import cv2
import numpy as np
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
from pyzbar.pyzbar import decode
# load model
# Paddleocr目前支持中英文、英文、法语、德语、韩语、日语,可以通过修改 lang参数进行切换
# lang参数依次为`ch`, `en`, `french`, `german`, `korean`, `japan`
ocr = PaddleOCR(
use_angle_cls=True,
# use_angle_cls=False,
lang="ch",
# use_gpu=False,
use_gpu=True,
use_tensorrt=True,
det_algorithm="DB",
# det_algorithm="EAST",
det_db_score_mode="slow",
# use_space_char=False, #不可用
det_model_dir="ch_ppocr_server_v4.0_det_infer/",
cls_model_dir="ch_ppocr_mobile_v4.0_cls_infer/",
rec_model_dir="ch_ppocr_server_v4.0_rec_infer/",
det_db_thresh=0.1,
det_db_box_thresh=0.1,
det_db_unclip_ratio=2.0,
max_batch_size=20,
use_dilation=True,
# rec_algorithm="SVTR_LCNet",
)
# load dataset
# img_path = "./08631508_2.jpg"
# img_path = "./image/baidu_image/test1.jpg"
# img_path = "./train/threecode/file_1704852415_6623.jpg"
# 构建文件匹配模式
file_pattern = os.path.join("./train/threecode", "*")
# 获取文件夹下的所有文件
file_list = glob.glob(file_pattern)
def flatten_list(nested_list):
flattened_list = []
for item in nested_list:
if isinstance(item, list):
flattened_list.extend(flatten_list(item))
elif isinstance(item, tuple):
for value in item:
if type(value) in (int, float):
if value > 1.0:
flattened_list.append(value)
else:
flattened_list.append(value)
else:
# flattened_list.append(item)
pass
return flattened_list
# 打印文件列表
for image_path in file_list:
original_image = Image.open(image_path)
# 放大图片
scale_factor = 5 # 放大倍数
# scaled_image = original_image.resize(
# (original_image.width * scale_factor, original_image.height * scale_factor)
# )
dst = original_image.resize(
(original_image.width * scale_factor, original_image.height * scale_factor)
)
# 裁剪放大后的图片
# crop_left = scaled_image.width // 2 - original_image.width // 2 # 裁剪左上角 x 坐标
# crop_top = scaled_image.height // 2 - original_image.height // 2 # 裁剪左上角 y 坐标
# # crop_width = original_image.width # 裁剪宽度
# # crop_height = original_image.height # 裁剪高度
# crop_width = original_image.width * 3 / 4 # 裁剪宽度
# crop_height = original_image.height * 3 / 4 # 裁剪高度
# dst = scaled_image.crop(
# (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
# )
# if os.path.exists(image_path.replace("train", "validation")):
# os.remove(image_path.replace("train", "validation"))
# dst.save(image_path.replace("train", "validation"))
# original_image = cv2.imread(img_path)
# # 获取原始图像尺寸
# height, width, _ = original_image.shape
# print(height, width)
# # 将图像放大两倍
# scaled_image = cv2.resize(original_image, (2 * width, 2 * height))
# # 计算裁剪区域的起始坐标
# x = width // 2 # 起始横坐标
# y = height // 2 # 起始纵坐标.
# print(y + height, x + width)
# cropped_image = scaled_image[y : y + height, x : x + width] # 进行裁剪
# dst = cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB) # 将图像从BGR转换为RGB
# cv2.imshow("Image", dst)
# result = ocr.ocr(image_path, cls=True)
# 检测条形码
# dst = cv2.imread(image_path)
# barcodes = decode(dst)
# # 遍历条形码区域并进行遮盖
# for barcode in barcodes:
# x, y, w, h = barcode.rect
# cv2.rectangle(np.asarray(dst), (x, y), (x + w, y + h), (0, 0, 0), -1)
# if os.path.exists(image_path.replace("train", "validation")):
# os.remove(image_path.replace("train", "validation"))
# dst.save(image_path.replace("train", "validation"))
# result = ocr.ocr(image_path, cls=True)
result = ocr.ocr(np.asarray(dst), cls=True)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log06.txt", "a+", encoding="utf-8") as file:
if result_list is not None:
file.write(image_path + "----" + str(result_list) + "\n")
else:
file.write(image_path + "----" + "NULL" + "\n")
import re
def extract_vin(string):
pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})"
match = re.search(pattern, string)
if match:
vin = match.group()
return vin
else:
return None
# 测试字符串
test_string = "This is a test VIN: 1HGCM82633A123456"
result = extract_vin(test_string)
print(result) # 输出 1HGCM82633A123456
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!