Commit 4b1edc61 by 杨林龙

合并

2 parents c5b35950 8bb1327b
...@@ -5,7 +5,7 @@ import random ...@@ -5,7 +5,7 @@ import random
import re import re
import time import time
from math import sqrt from math import sqrt
from logger import log
import cv2 import cv2
import numpy as np import numpy as np
import pymysql import pymysql
...@@ -14,13 +14,25 @@ from paddleocr import PaddleOCR, draw_ocr ...@@ -14,13 +14,25 @@ from paddleocr import PaddleOCR, draw_ocr
from PIL import Image from PIL import Image
from pyzbar.pyzbar import decode 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 # 连接database
conn_dev = pymysql.connect( conn_dev = pymysql.connect(
host="192.168.3.227", host=Config.host,
port=3306, port=Config.port,
user="dev_user", user=Config.user,
password="df234fl", password=Config.password,
database="glsx_car_service", database=Config.database,
charset="utf8", charset="utf8",
) )
# 得到一个可以执行SQL语句的光标对象 # 得到一个可以执行SQL语句的光标对象
...@@ -75,7 +87,7 @@ ocr = PaddleOCR( ...@@ -75,7 +87,7 @@ ocr = PaddleOCR(
# 定义要执行的SQL语句 # 定义要执行的SQL语句
SQL = """ SQL = """
select * from sys_order_file_ocr_sn sofon limit 2000 select * from sys_order_file_ocr_sn sofon limit 5
""" """
# 执行SQL语句 # 执行SQL语句
cursor_dev.execute(SQL) cursor_dev.execute(SQL)
...@@ -102,7 +114,7 @@ def get_project_root(): ...@@ -102,7 +114,7 @@ def get_project_root():
current_file = os.path.abspath(__file__) current_file = os.path.abspath(__file__)
# 获取当前项目的根目录 # 获取当前项目的根目录
project_root = os.path.dirname(os.path.dirname(current_file)) project_root = os.path.dirname(os.path.dirname(current_file))
print(project_root) log.info(project_root)
return project_root return project_root
...@@ -147,12 +159,83 @@ def extract_sn(string): ...@@ -147,12 +159,83 @@ def extract_sn(string):
return None 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(image,angle):
# 逆时针旋转45度
log.info("逆时针旋转"+angle+"度")
# rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0)
rotated_image = image.rotate(angle)
return rotated_image
def handler_sn(dst, flag, angle, path):
# 旋转角度
if angle>0:
dst = flip_image(dst, angle)
try:
result = ocr.ocr(np.asarray(dst), cls=True)
except Exception as msg:
log.error(msg)
# 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")
# 使用正则表达式进行过滤 获取车架号
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()
return flag
# 下载图片数据 # 下载图片数据
for index, row in enumerate(result): for index, row in enumerate(result):
print(row) log.info(row)
filename = generate_random_filename() filename = generate_random_filename()
network_img_path = row[4] 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) extension = get_extension(network_img_path)
complete_filename = f"{filename}.{extension}" complete_filename = f"{filename}.{extension}"
try: try:
...@@ -162,16 +245,24 @@ for index, row in enumerate(result): ...@@ -162,16 +245,24 @@ for index, row in enumerate(result):
path = os.path.join( path = os.path.join(
get_project_root(), "Identify_sn", "train", "threecode", complete_filename 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: with open(path, "wb") as file:
file.write(response.content) file.write(response.content)
# urllib.request.urlretrieve(network_img_path, path) # urllib.request.urlretrieve(network_img_path, path)
time.sleep(0.001) time.sleep(0.001)
print("File downloaded successfully.") log.info("File downloaded successfully.")
original_image = Image.open(path) original_image = Image.open(path)
if original_image.mode == "RGBA":
original_image = original_image.convert("RGB")
print(original_image.mode)
# 放大图片 # 放大图片
scale_factor = 5 # 放大倍数 scale_factor = 3 # 放大倍数
# scaled_image = original_image.resize( # scaled_image = original_image.resize(
# (original_image.width * scale_factor, original_image.height * scale_factor) # (original_image.width * scale_factor, original_image.height * scale_factor)
# ) # )
...@@ -180,53 +271,44 @@ for index, row in enumerate(result): ...@@ -180,53 +271,44 @@ for index, row in enumerate(result):
(original_image.width * scale_factor, original_image.height * scale_factor) (original_image.width * scale_factor, original_image.height * scale_factor)
) )
result = ocr.ocr(np.asarray(dst), cls=True) flag = True
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result: flag = handler_sn(dst, flag, 0, path, row)
print(line)
# print(line[0][1][0]) if flag:
flag = handler_sn(dst, flag, 45, path, row)
result_list = flatten_list(result) if flag:
print("result_list", result_list) flag = handler_sn(dst, flag, 45, path, row)
with open("./log01.txt", "a+", encoding="utf-8") as file: if flag:
if result_list is not None: flag = handler_sn(dst, flag, 90, path, row)
file.write(path + "----" + str(result_list) + "\n") if flag:
else: scale_factor = 5
file.write(path + "----" + "NULL" + "\n") dst = original_image.resize(
(
# 使用正则表达式进行过滤 获取车架号 original_image.width * scale_factor,
sn_str = "" original_image.height * scale_factor,
for item in result_list: )
print(item) )
vin_check = extract_sn(item) flag = handler_sn(dst, flag, 0, path, row)
if vin_check is not None:
sn_str = vin_check if flag:
break
if sn_str:
print(str(row))
print(sn_str)
# 定义要执行的SQL语句 # 定义要执行的SQL语句
SQL01 = f""" SQL02 = f"""
INSERT INTO sys_vin_check_ocr_sn_01 (order_id,file_id,db_sn,ocr_sn,create_time) 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语句 # 执行SQL语句
print(SQL01) log.info(SQL02)
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)
cursor_dev.execute(SQL02) cursor_dev.execute(SQL02)
conn_dev.commit() conn_dev.commit()
try:
os.remove(path)
log.info("文件删除成功")
except FileNotFoundError:
log.info("文件不存在")
except PermissionError:
log.info("权限不足,无法删除文件")
# # 关闭光标对象 # # 关闭光标对象
# cursor.close() # cursor.close()
# # 关闭数据库连接 # # 关闭数据库连接
......
...@@ -13,8 +13,8 @@ import requests ...@@ -13,8 +13,8 @@ import requests
from paddleocr import PaddleOCR, draw_ocr from paddleocr import PaddleOCR, draw_ocr
from PIL import Image from PIL import Image
from PIL import ImageEnhance from PIL import ImageEnhance
from pyzbar.pyzbar import decode # from pyzbar.pyzbar import decode
from logger import log
# 连接database # 连接database
conn_dev = pymysql.connect( conn_dev = pymysql.connect(
host="192.168.3.227", host="192.168.3.227",
...@@ -157,29 +157,60 @@ def extract_vin(string): ...@@ -157,29 +157,60 @@ def extract_vin(string):
return None return None
def flip_image_45(image): def flip_image(image,angle):
# 逆时针旋转45度 # 逆时针旋转45度
print("逆时针旋转45度") log.info("逆时针旋转"+angle+"度")
# rotated_image = cv2.transpose(image) # rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0) # rotated_image = cv2.flip(rotated_image, 0)
rotated_image = image.rotate(45) rotated_image = image.rotate(angle)
return rotated_image return rotated_image
def flip_image_90(image): def handler_vin(dst, flag, angle, path):
# 逆时针旋转90度 if angle > 0:
print("逆时针旋转90度") dst = flip_image(dst, angle)
# rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0) try:
rotated_image = image.rotate(90) result = ocr.ocr(np.asarray(dst), cls=True)
return rotated_image except Exception as msg:
log.error(msg)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True)
for line in result:
print(line)
# print(line[0][1][0])
def flip_image_180(image): result_list = flatten_list(result)
# 旋转180度 print("result_list", result_list)
rotated_image = cv2.flip(image, -1) with open("./log10.txt", "a+", encoding="utf-8") as file:
return rotated_image if result_list is not None:
file.write(path + "----" + str(result_list) + "\n")
else:
file.write(path + "----" + "NULL" + "\n")
# 使用正则表达式进行过滤 获取车架号
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
flag=False
break
if vin_str:
print(str(row))
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_vin_check_ocr_11 (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()
return flag
# 下载图片数据 # 下载图片数据
for index, row in enumerate(result): for index, row in enumerate(result):
...@@ -225,196 +256,38 @@ for index, row in enumerate(result): ...@@ -225,196 +256,38 @@ for index, row in enumerate(result):
dst = original_image.resize( dst = original_image.resize(
(original_image.width * scale_factor, original_image.height * scale_factor) (original_image.width * scale_factor, original_image.height * scale_factor)
) )
flag = True
result = ocr.ocr(np.asarray(dst), cls=True) flag = handler_vin(dst, flag, 0, path, row)
# result = ocr.ocr(image_path.replace("train", "validation"), cls=True) if flag:
for line in result: # 旋转45度宠重新识别
print(line) flag = handler_vin(dst, flag, 45, path, row)
# print(line[0][1][0]) if flag:
# 旋转90度宠重新识别
result_list = flatten_list(result) flag = handler_vin(dst, flag, 45, path, row)
print("result_list", result_list) if flag:
with open("./log10.txt", "a+", encoding="utf-8") as file: # 旋转180度宠重新识别
if result_list is not None: flag = handler_vin(dst, flag, 90, path, row)
file.write(path + "----" + str(result_list) + "\n") if flag:
else: # 如果识别不了 直接再放大图片
file.write(path + "----" + "NULL" + "\n") scale_factor = 5
dst = original_image.resize(
# 使用正则表达式进行过滤 获取车架号 (
vin_str = "" original_image.width * scale_factor,
for item in result_list: original_image.height * scale_factor,
print(item) )
vin_check = extract_vin(item) )
if vin_check is not None: flag = handler_vin(dst, flag, 0, path, row)
vin_str = vin_check if flag:
break
if vin_str:
print(str(row))
print(vin_str)
# 定义要执行的SQL语句 # 定义要执行的SQL语句
SQL01 = f""" SQL02 = f"""
INSERT INTO sys_vin_check_ocr_11 (order_id,file_id,db_vin,ocr_vin,create_time) INSERT INTO sys_vin_check_ocr_11 (order_id,file_id,db_vin,ocr_vin,create_time)
VALUES ({row[1]},{row[0]},'{row[9]}','{vin_str}',sysdate()) VALUES ({row[1]},{row[0]},'{row[9]}',null,sysdate())
""" """
# 执行SQL语句 # 执行SQL语句
print(SQL01) print(SQL02)
cursor_dev.execute(SQL01) cursor_dev.execute(SQL02)
conn_dev.commit() conn_dev.commit()
else:
# 旋转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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_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_11 (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:
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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_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_11 (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:
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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_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_11 (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:
# 如果识别不了 直接再放大图片
scale_factor = 5
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)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_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_11 (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_11 (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()
# # 关闭光标对象 # # 关闭光标对象
......
class Config:
DEBUG = False
env = 'dev'
# 数据库连接配置
host='192.168.3.227'
port = 3306
user = 'dev_user'
password = 'df234fl'
database = 'glsx_car_service'
# Kafka consumer配置
kafka_consumer_bootstrap_servers = '192.168.3.131:9092'
kafka_consumer_group_id = 'ocr_consumer_dev'
kafka_consumer_auto_offset_reset = 'earliest'
kafka_consumer_topic = 'ocr_topic'
charset = 'utf8'
#
class Config:
DEBUG = False
env = 'pro'
# 数据库连接配置
host = '192.168.5.2'
port = 3307
user = 'biz_car_service'
password = 'df234fl'
database = 'glsx_car_service'
# Kafka consumer配置
kafka_consumer_bootstrap_servers = 'localhost:9092'
kafka_consumer_group_id = 'my_consumer_group'
kafka_consumer_auto_offset_reset = 'earliest'
kafka_consumer_topic = 'ocr_topic'
charset = 'utf8'
#
class Config:
DEBUG = False
env='test'
# 数据库连接配置
host = '192.168.3.222'
port = 3307
user = 'root'
password = 'Msd^*$@online'
database = 'glsx_car_service'
# Kafka consumer配置
kafka_consumer_bootstrap_servers = '192.168.3.131:9092'
kafka_consumer_group_id = 'ocr_consumer_test'
kafka_consumer_auto_offset_reset = 'earliest'
kafka_consumer_topic = 'ocr_topic'
charset = 'utf8'
#
...@@ -3,8 +3,10 @@ import numpy as np ...@@ -3,8 +3,10 @@ import numpy as np
import base64 import base64
from io import BytesIO from io import BytesIO
import logging import logging
import tf as tf
from keras.models import load_model from keras.models import load_model
from keras.utils import image_utils # from keras.utils import image_utils
from keras import backend as K from keras import backend as K
from PIL import ImageFile from PIL import ImageFile
...@@ -38,9 +40,9 @@ class ImageClassificationService(object): ...@@ -38,9 +40,9 @@ class ImageClassificationService(object):
""" """
# 加载图像 # 加载图像
img = image_utils.load_img(img_path, target_size=self.input_shape) img = tf.keras.utils.load_img(img_path, target_size=self.input_shape)
# 图像预处理 # 图像预处理
x = image_utils.img_to_array(img) / 255.0 # 与训练一致 x = tf.keras.utils.img_to_array(img) / 255.0 # 与训练一致
x = np.expand_dims(x, axis=0) x = np.expand_dims(x, axis=0)
# 对图像进行分类 # 对图像进行分类
......
import os
from flask import request, Blueprint,json
import random
import re
import time
import pymysql
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
import requests
import numpy as np
# 创建一个蓝图
ocr_classfication_bp = Blueprint("ocr_classfication", __name__)
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",
)
# 定义要执行的SQL语句
# SQL = """
# select * from sys_order_file_ocr_sn sofon limit 5
# """
# # 执行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_sn(string):
string = re.sub(r"O", "0", string)
string = re.sub(r"I", "1", string)
pattern = r"\b(\d{10,11})\b"
match = re.search(pattern, string)
if match:
sn = match.group()
return sn
else:
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度
print("逆时针旋转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度
print("逆时针旋转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度
print("逆时针旋转180度")
rotated_image = image.rotate(180)
return rotated_image
def handle_process(order_id, file_path, sns, vin):
print("recognition handle_process:", order_id, file_path, sns, vin)
# 删除数据库里的旧数据
delete_sql1 = "DELETE FROM sys_order_ocr_sn_result WHERE order_id = {}".format(order_id)
print(delete_sql1)
cursor_dev.execute(delete_sql1)
conn_dev.commit()
delete_sql2 = "DELETE FROM sys_order_ocr_vin_result WHERE order_id = {}".format(order_id)
print(delete_sql2)
cursor_dev.execute(delete_sql2)
conn_dev.commit()
filename = generate_random_filename()
network_img_path = file_path
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_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.")
original_image = Image.open(path)
if original_image.mode == "RGBA":
original_image = original_image.convert("RGB")
print(original_image.mode)
# 放大图片
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)
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 = ""
flag = True
for item in result_list:
print(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
print(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
"""
# 执行SQL语句
print(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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", 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:
print(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
print(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
"""
# 执行SQL语句
print(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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", 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:
print(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
print(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
"""
# 执行SQL语句
print(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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", 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:
print(item)
sn_check = extract_sn(item)
if sn_check is not None:
flag = False
sn_str = sn_check
if sn_str:
print(sn_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},null,'{sns}','{sn_str}',sysdate(),sysddate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
if flag:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},null,'{sns}',null,sysdate(),sysddate())
"""
# 执行SQL语句
print(SQL02)
cursor_dev.execute(SQL02)
conn_dev.commit()
print("==========================处理vin==================================")
# 创建对比度增强器
# enhancer = ImageEnhance.Contrast(original_image)
# 增强对比度(将对比度增强为原来的2倍)
# factor = 2.0
# original_image = enhancer.enhance(factor)
# 放大图片
scale_factor = 3 # 放大倍数
# 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)
with open("./log10.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")
# 使用正则表达式进行过滤 获取车架号
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
# 旋转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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
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:
print(line)
# print(line[0][1][0])
result_list = flatten_list(result)
print("result_list", result_list)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
# 如果识别不了 直接再放大图片
scale_factor = 5
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)
with open("./log10.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")
vin_str = ""
for item in result_list:
print(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
break
if vin_str:
print(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL01)
cursor_dev.execute(SQL01)
conn_dev.commit()
else:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},null,'{vin}',null,sysdate(),sysdate())
"""
# 执行SQL语句
print(SQL02)
cursor_dev.execute(SQL02)
conn_dev.commit()
try:
os.remove(path)
print("文件删除成功")
except FileNotFoundError:
print("文件不存在")
except PermissionError:
print("权限不足,无法删除文件")
# 在蓝图中定义路由和视图函数
@ocr_classfication_bp.route("/recognition", methods=["POST"])
def identify():
data = request.get_data()
json_data = json.loads(data.decode("UTF-8"))
order_id = json_data.get("orderId")
file_path = json_data.get("filePath")
sns = json_data.get("sns")
vin = json_data.get("vin")
handle_process(order_id,file_path,sns,vin)
import json
from kafka import KafkaConsumer
import sys
import logging
# 导入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
# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 将根目录添加到 Python 解释器的搜索路径中
root_dir = os.path.join(current_dir, '..') # 假设根目录是当前目录的父目录
sys.path.append(root_dir)
from logger import log
environment = sys.argv[1] if len(sys.argv) > 1 else "default"
# environment = os.environ.get('ENV')
if environment == 'pro':
from config_pro import Config
log.info(vars(Config))
elif environment == 'test':
from config_test import Config
log.info(vars(Config))
else:
from config_dev import Config
log.info(vars(Config))
log.info("启动1")
# 配置 Kafka 消费者
consumer = KafkaConsumer(
Config.kafka_consumer_topic,
bootstrap_servers=Config.kafka_consumer_bootstrap_servers, # Kafka broker 的地址
group_id=Config.kafka_consumer_group_id, # 消费者组 ID
auto_offset_reset=Config.kafka_consumer_auto_offset_reset # 从最早的消息开始消费
)
log.info("启动2")
# 连接database
conn_dev = pymysql.connect(
host=Config.host,
port=Config.port,
user=Config.user,
password=Config.password,
database=Config.database,
charset="utf8",
)
# 得到一个可以执行SQL语句的光标对象
cursor_dev = conn_dev.cursor()
log.info("启动3")
# 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",
)
# 定义要执行的SQL语句
# SQL = """
# select * from sys_order_file_ocr_sn sofon limit 5
# """
# # 执行SQL语句
# cursor_dev.execute(SQL)
#
# # 获取查询结果
# result = cursor_dev.fetchall()
log.info("启动4")
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))
log.info(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_sn(string):
string = re.sub(r"O", "0", string)
string = re.sub(r"I", "1", string)
pattern = r"\b(\d{10,11})\b"
match = re.search(pattern, string)
if match:
sn = match.group()
return sn
else:
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(image,angle):
# 逆时针旋转45度
log.info("逆时针旋转"+str(angle)+"度")
# rotated_image = cv2.transpose(image)
# rotated_image = cv2.flip(rotated_image, 0)
rotated_image = image.rotate(angle)
return rotated_image
# 处理设备号
def handler_sn(dst, flag, angle, path, row):
# 旋转角度
if angle>0:
dst = flip_image(dst, angle)
try:
result = ocr.ocr(np.asarray(dst), cls=True)
except Exception as msg:
log.error(msg)
# 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")
# 使用正则表达式进行过滤 获取车架号
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_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({row[0]},{row[1]},'{row[2]}','{sn_str}',sysdate(),sysdate())
"""
# 执行SQL语句
log.info(SQL01)
SQL01=SQL01.replace("'None',", "null,").replace("None,", "null,")
cursor_dev.execute(SQL01)
conn_dev.commit()
return flag
# 处理车架号
def handler_vin(dst, flag, angle, path,row):
if angle > 0:
dst = flip_image(dst, angle)
try:
result = ocr.ocr(np.asarray(dst), cls=True)
except Exception as msg:
log.error(msg)
# 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("./log10.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")
# 使用正则表达式进行过滤 获取车架号
vin_str = ""
for item in result_list:
log.info(item)
vin_check = extract_vin(item)
if vin_check is not None:
vin_str = vin_check
flag = False
break
if vin_str:
log.info(str(row))
log.info(vin_str)
# 定义要执行的SQL语句
SQL01 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({row[0]},{row[1]},'{row[3]}','{vin_str}',sysdate(),sysdate())
"""
# 执行SQL语句
log.info(SQL01)
SQL01=SQL01.replace("'None',", "null,").replace("None,", "null,")
cursor_dev.execute(SQL01)
conn_dev.commit()
return flag
def handle_process(jsonData):
log.info("Received message handle_process: %s",jsonData)
row = json.loads(jsonData.value.decode('utf-8'))
order_id = row.get("orderId")
file_id = row.get("fileId")
sns = row.get("sns")
vin = row.get("vin")
data = [order_id, file_id, sns, vin]
# 删除数据库里的旧数据
delete_sql1 = "DELETE FROM sys_order_ocr_sn_result WHERE order_id = {}".format(order_id)
log.info(delete_sql1)
cursor_dev.execute(delete_sql1)
conn_dev.commit()
delete_sql2 = "DELETE FROM sys_order_ocr_vin_result WHERE order_id = {}".format(order_id)
log.info(delete_sql2)
cursor_dev.execute(delete_sql2)
conn_dev.commit()
filename = generate_random_filename()
network_img_path = row.get("filePath")
log.info("network_img_path %s", 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_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)
log.info("File downloaded successfully.")
original_image = Image.open(path)
if original_image.mode == "RGBA":
original_image = original_image.convert("RGB")
log.info(original_image.mode)
# 放大图片
scale_factor = 3 # 放大倍数
# 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)
)
flag = True
flag = handler_sn(dst, flag, 0, path, data)
if flag:
flag = handler_sn(dst, flag, 45, path, data)
if flag:
flag = handler_sn(dst, flag, 45, path, data)
if flag:
flag = handler_sn(dst, flag, 90, path, data)
if flag:
scale_factor = 5
dst = original_image.resize(
(
original_image.width * scale_factor,
original_image.height * scale_factor,
)
)
flag = handler_sn(dst, flag, 0, path, data)
if flag:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_order_ocr_sn_result (order_id,file_id,db_sn,ocr_sn,create_time,update_time)
VALUES ({order_id},{file_id},'{sns}',null,sysdate(),sysdate())
"""
# 执行SQL语句
log.info(SQL02)
SQL02=SQL02.replace("'None',", "null,").replace("None,", "null,")
cursor_dev.execute(SQL02)
conn_dev.commit()
log.info("==========================处理vin==================================")
# 创建对比度增强器
# enhancer = ImageEnhance.Contrast(original_image)
# 增强对比度(将对比度增强为原来的2倍)
# factor = 2.0
# original_image = enhancer.enhance(factor)
# 放大图片
scale_factor = 3 # 放大倍数
# 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)
)
flag = True
flag = handler_vin(dst, flag, 0, path, data)
if flag:
# 旋转45度宠重新识别
flag = handler_vin(dst, flag, 45, path, data)
if flag:
# 旋转90度宠重新识别
flag = handler_vin(dst, flag, 45, path, data)
if flag:
# 旋转180度宠重新识别
flag = handler_vin(dst, flag, 90, path, data)
if flag:
# 如果识别不了 直接再放大图片
scale_factor = 5
dst = original_image.resize(
(
original_image.width * scale_factor,
original_image.height * scale_factor,
)
)
flag = handler_vin(dst, flag, 0, path, row)
if flag:
# 定义要执行的SQL语句
SQL02 = f"""
INSERT INTO sys_order_ocr_vin_result (order_id,file_id,db_vin,ocr_vin,create_time,update_time)
VALUES ({order_id},{file_id},'{vin}',null,sysdate(),sysdate())
"""
# 执行SQL语句
log.info(SQL02)
SQL02=SQL02.replace("'None',", "null,").replace("None,", "null,")
cursor_dev.execute(SQL02)
conn_dev.commit()
try:
os.remove(path)
log.info("文件删除成功")
except FileNotFoundError:
log.info("文件不存在")
except PermissionError:
log.info("权限不足,无法删除文件")
def consume_kafka():
log.info("启动consume_kafka")
# 消费消息并进行逻辑处理
try:
for msg in consumer:
if msg is None:
continue
# 处理逻辑
handle_process(msg)
except Exception as e:
log.error("ocr consumer Exception: " + str(e))
finally:
# 关闭消费者
consumer.close()
# 关闭光标对象
cursor_dev.close()
# 关闭数据库连接
conn_dev.close()
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('ocr.log')
\ No newline at end of file \ No newline at end of file
# coding=utf-8
from flask import request, render_template from flask import request, render_template
from flaskr import create_app from flaskr import create_app
from flaskr.biz import user_service from flaskr.biz import user_service
from flaskr.biz.identify_service import IdentifyService from flaskr.biz.identify_service import IdentifyService
from flaskr.controller import image_classfication_controller from flaskr.controller import image_classfication_controller, ocr_controller
import os import os
from kafka_consumer import ocr_consumer
app = create_app() app = create_app()
# 注册蓝图到应用程序中 # 注册蓝图到应用程序中
app.register_blueprint( app.register_blueprint(
image_classfication_controller.classfication_bp, url_prefix="/classfication" image_classfication_controller.classfication_bp, url_prefix="/classfication"
) )
app.register_blueprint(
ocr_controller.ocr_classfication_bp , url_prefix="/ocr"
)
@app.route("/") @app.route("/")
...@@ -61,4 +66,5 @@ def upload(): ...@@ -61,4 +66,5 @@ def upload():
if __name__ == "__main__": if __name__ == "__main__":
ocr_consumer.consume_kafka()
app.run(host="0.0.0.0", port=5000) app.run(host="0.0.0.0", port=5000)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!