Commit 8996f9d3 by 周杭

sn识别test

1 parent 478e563b
import logging
import os
import sys
from logging.handlers import TimedRotatingFileHandler
def setup_logging(log_file):
"""
设置日志记录器,将日志输出到文件并按天进行保存
:param log_file: 日志文件路径
"""
# 创建一个日志记录器
logger = logging.getLogger(log_file)
if logger.hasHandlers():
logger.handlers.clear()
logger.setLevel(logging.DEBUG)
# 创建一个 TimedRotatingFileHandler 实例,将日志输出到文件,并按天进行保存
file_handler = TimedRotatingFileHandler(filename=log_file, when="midnight", interval=1, backupCount=30,encoding='UTF-8')
file_handler.setLevel(logging.DEBUG)
# 设置日志格式
formatter = logging.Formatter('%(asctime)s %(thread)d %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
file_handler.setFormatter(formatter)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
# 将处理器添加到日志记录器中
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
log=setup_logging('mytest.log')
\ No newline at end of file
......@@ -5,7 +5,7 @@ import random
import re
import time
from math import sqrt
from logger import log
import cv2
import numpy as np
import pymysql
......@@ -14,13 +14,25 @@ from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
from pyzbar.pyzbar import decode
environment = os.environ.get('ENV')
if environment == 'pro':
from config_pro import Config
print(vars(Config))
elif environment == 'test':
from config_test import Config
print(vars(Config))
else:
from config_dev import Config
print(vars(Config))
# 连接database
conn_dev = pymysql.connect(
host="192.168.3.227",
port=3306,
user="dev_user",
password="df234fl",
database="glsx_car_service",
host=Config.host,
port=Config.port,
user=Config.user,
password=Config.password,
database=Config.database,
charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
......@@ -75,7 +87,7 @@ ocr = PaddleOCR(
# 定义要执行的SQL语句
SQL = """
select * from sys_order_file_ocr_sn sofon limit 2000
select * from sys_order_file_ocr_sn sofon limit 5
"""
# 执行SQL语句
cursor_dev.execute(SQL)
......@@ -102,7 +114,7 @@ def get_project_root():
current_file = os.path.abspath(__file__)
# 获取当前项目的根目录
project_root = os.path.dirname(os.path.dirname(current_file))
print(project_root)
log.info(project_root)
return project_root
......@@ -147,12 +159,57 @@ def extract_sn(string):
return None
def extract_vin(string):
string = re.sub(r"O", "0", string)
string = re.sub(r"I", "1", string)
pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z]{17})"
# pattern = r"(?=.*[0-9A-HJ-NPR-Z])(?!(.*[IOQ]))([0-9A-HJ-NPR-Z\s\u4e00-\u9fa5]{17})"
# pattern = r"[0-9A-HJ-NPR-Z]{17}"
# pattern = r"^[A-HJ-NPR-Z\d]{17}$"
match = re.search(pattern, string)
if match:
vin = match.group()
pattern01 = r"^\d+$"
match = re.match(pattern01, vin)
# 如果全是数字 则不是车架号
if bool(match):
return None
else:
return vin
else:
return None
def flip_image_45(image):
# 逆时针旋转45度
log.info("逆时针旋转45度")
# rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0)
rotated_image = image.rotate(45)
return rotated_image
def flip_image_90(image):
# 逆时针旋转90度
log.info("逆时针旋转90度")
# rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0)
rotated_image = image.rotate(90)
return rotated_image
def flip_image_180(image):
# 旋转180度
log.info("逆时针旋转180度")
rotated_image = image.rotate(180)
return rotated_image
# 下载图片数据
for index, row in enumerate(result):
print(row)
log.info(row)
filename = generate_random_filename()
network_img_path = row[4]
print("network_img_path", network_img_path)
log.info("network_img_path %s", network_img_path)
extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}"
try:
......@@ -162,11 +219,14 @@ for index, row in enumerate(result):
path = os.path.join(
get_project_root(), "Identify_sn", "train", "threecode", complete_filename
)
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
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.")
log.info("File downloaded successfully.")
original_image = Image.open(path)
......@@ -183,11 +243,11 @@ for index, row in enumerate(result):
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])
log.info(line)
# log.info(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
log.info("result_list %s", result_list)
with open("./log01.txt", "a+", encoding="utf-8") as file:
if result_list is not None:
file.write(path + "----" + str(result_list) + "\n")
......@@ -196,37 +256,154 @@ for index, row in enumerate(result):
# 使用正则表达式进行过滤 获取车架号
sn_str = ""
flag = True
for item in result_list:
print(item)
vin_check = extract_sn(item)
if vin_check is not None:
sn_str = vin_check
break
if sn_str:
print(str(row))
print(sn_str)
log.info(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
log.info(str(row))
log.info(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{sn_str}',sysdate())
"""
# 执行SQL语句
log.info(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
if flag:
# 旋转45
dst = flip_image_45(dst)
result = ocr.ocr(np.asarray(dst), cls=True)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
log.info(line)
# log.info(line[0][1][0])
result_list = flatten_list(result)
log.info("result_list %s", result_list)
with open("./log01.txt", "a+", encoding="utf-8") as file:
if result_list is not None:
file.write(path + "----" + str(result_list) + "\n")
else:
file.write(path + "----" + "NULL" + "\n")
# 使用正则表达式进行过滤 获取车架号
sn_str = ""
for item in result_list:
log.info(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
log.info(str(row))
log.info(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{sn_str}',sysdate())
"""
# 执行SQL语句
log.info(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
if flag:
# 旋转90
dst = flip_image_45(dst)
result = ocr.ocr(np.asarray(dst), cls=True)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
log.info(line)
# log.info(line[0][1][0])
result_list = flatten_list(result)
log.info("result_list %s", result_list)
with open("./log01.txt", "a+", encoding="utf-8") as file:
if result_list is not None:
file.write(path + "----" + str(result_list) + "\n")
else:
file.write(path + "----" + "NULL" + "\n")
# 使用正则表达式进行过滤 获取车架号
sn_str = ""
for item in result_list:
log.info(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
log.info(str(row))
log.info(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{sn_str}',sysdate())
"""
# 执行SQL语句
log.info(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
if flag:
# 旋转180
dst = flip_image_90(dst)
result = ocr.ocr(np.asarray(dst), cls=True)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
log.info(line)
# log.info(line[0][1][0])
result_list = flatten_list(result)
log.info("result_list %s", result_list)
with open("./log01.txt", "a+", encoding="utf-8") as file:
if result_list is not None:
file.write(path + "----" + str(result_list) + "\n")
else:
file.write(path + "----" + "NULL" + "\n")
# 使用正则表达式进行过滤 获取车架号
sn_str = ""
for item in result_list:
log.info(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
log.info(str(row))
log.info(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{sn_str}',sysdate())
"""
# 执行SQL语句
log.info(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
if flag:
# 定义要执行的SQL语句
SQL01 = f"""
SQL02 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{sn_str}',sysdate())
VALUES ({row[1]},{row[0]},'{row[9]}',null,sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}',null,sysdate())
"""
# 执行SQL语句
print(SQL02)
log.info(SQL02)
cursor_dev.execute(SQL02)
conn_dev.commit()
try:
os.remove(path)
log.info("文件删除成功")
except FileNotFoundError:
log.info("文件不存在")
except PermissionError:
log.info("权限不足,无法删除文件")
# # 关闭光标对象
# cursor.close()
# # 关闭数据库连接
......
......@@ -13,7 +13,7 @@ import requests
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
from PIL import ImageEnhance
from pyzbar.pyzbar import decode
# from pyzbar.pyzbar import decode
# 连接database
conn_dev = pymysql.connect(
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!