当前位置:   article > 正文

CTPN+CRNN算法端到端实现文字识别的实战开发_ctrnn 演化csdn

ctrnn 演化csdn

本文分享自华为云社区《CTPN+CRNN 算法端到端实现文字识别》,作者:HWCloudAI。

OCR介绍

光学字符识别(英语:Optical Character Recognition,OCR)是指对文本资料的图像文件进行分析识别处理,获取文字及版面信息的过程。发展时间较长,使用很普遍。OCR作为计算机视觉中较早使用深度学习技术的领域,有很多优秀的模型出现。普遍的深度学习下的OCR技术将文字识别过程分为:文本区域检测以及字符识别。

文本区域检测——CTPN模型

文字区域检测:将图片中出现的文本位置检测出来,可能存在不同语言,不同文字大小,不同角度倾斜,不同程度遮挡等情况。CTPN网络结合了CNN与LSTM深度网络,通过固定宽度的anchor提取proposal,能有效的检测出复杂场景的横向分布的文字区域,不定长度文本识别效果较好,是目前使用广泛的文字检测算法。

字符序列检测——CRNN模型

字符识别算法:将文本区域的字符识别出来。通过深度神经网络对目标区域进行特征提取,然后对固定特征进行提取和比对,得出识别结果。采用文本识别网络CRNN+CTC。CRNN全称为卷积循环神经网络,将特征提取,序列建模以及转录整合到统一的模型框架中。主要用于端到端地对不定长的文本序列进行识别,不用先对单个文字进行切割,而是将文本识别转化为时序依赖的序列学习问题,就是基于图像的序列识别。如下图,CRNN网络分为:卷积层、循环层和转录层三部分,CTC为无词典的转录方式, 不会被局限在预定义词汇范围中。

完整的端到端OCR流程

了解了文本区域检测以及字符识别后,下面详细讲解完整的端到端OCR流程:

(1)准备一张含有文字的原图;

(2)对原图进行文字位置的检测,检测结果可能是水平矩形框,也可能是倾斜矩形框;

(3)从原图中把文字框对应的图片切下来,并旋转正,得到水平的文字块切片图;

(4)对每个文字块切片图依次进行字符识别,每个切片图的识别结果汇总起来,就得到原图的文字识别结果。

因此完整的端到端OCR流程是:输入原图 -> 文字检测 -> 文字块切片 -> 字符识别 -> 识别结果汇总。

理论部分到此告一段落,下面开始在ModelArts中体验实战项目开发!

注意事项:

  1. 本案例使用框架**:** TensorFlow-1.8

  2. 本案例使用硬件规格**:** 8 vCPU + 64 GiB + 1 x Tesla V100-PCIE-32GB

  3. 进入运行环境方法:点此链接进入AI Gallery,点击Run in ModelArts按钮进入ModelArts运行环境,如需使用GPU,您可以在ModelArts JupyterLab运行界面右边的工作区进行切换

  4. 运行代码方法**:** 点击本页面顶部菜单栏的三角形运行按钮或按Ctrl+Enter键 运行每个方块中的代码

  5. JupyterLab的详细用法**:** 请参考《ModelAtrs JupyterLab使用指导》

  6. 碰到问题的解决办法**:** 请参考《ModelAtrs JupyterLab常见问题解决办法》

1. 下载代码和模型

本案例中已经将CTPN和CRNN的代码模型都整合到一起

  1. import os
  2. from modelarts.session import Session
  3. sess = Session()
  4. if sess.region_name == 'cn-north-1':
  5. bucket_path="modelarts-labs/notebook/DL_ocr_crnn_sequence_recognition/E2E_ocr.zip"
  6. elif sess.region_name == 'cn-north-4':
  7. bucket_path="modelarts-labs-bj4/notebook/DL_ocr_crnn_sequence_recognition/E2E_ocr.zip"
  8. else:
  9. print("请更换地区到北京一或北京四")
  10. if not os.path.exists('E2E_ocr'):
  11. sess.download_data(bucket_path=bucket_path, path="./E2E_ocr.zip")
  12. if os.path.exists('./E2E_ocr.zip'):
  13. status = os.system("unzip -q E2E_ocr.zip")
  14. if status == 0:
  15. os.system("rm E2E_ocr.zip")
Successfully download file modelarts-labs-bj4/notebook/DL_ocr_crnn_sequence_recognition/E2E_ocr.zip from OBS to local ./E2E_ocr.zip

2. CTPN相关模块导入

  1. import shutil
  2. import cv2
  3. import numpy as np
  4. import datetime
  5. import os
  6. import sys
  7. import time
  8. import json
  9. import codecs
  10. from PIL import Image
  11. import tensorflow as tf
  12. sys.path.append(os.getcwd() + '/E2E_ocr')
  13. sys.path.append(os.getcwd() + '/E2E_ocr/CRNN/')
  14. from collections import OrderedDict
  15. from tensorflow.contrib import slim
  16. from CTPN import data_provider as data_provider
  17. from CTPN.model import mean_image_subtraction,Bilstm,lstm_fc,loss
  18. from CTPN import vgg
  19. from CTPN import model
  20. from CTPN.utils.rpn_msr.proposal_layer import proposal_layer
  21. from CTPN.utils.text_connector.detectors import TextDetector
  22. from CTPN.utils.image import resize_image

  1. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  2. _np_qint8 = np.dtype([("qint8", np.int8, 1)])
  3. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  4. _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
  5. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:521: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  6. _np_qint16 = np.dtype([("qint16", np.int16, 1)])
  7. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:522: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  8. _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
  9. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:523: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  10. _np_qint32 = np.dtype([("qint32", np.int32, 1)])
  11. /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:528: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  12. np_resource = np.dtype([("resource", np.ubyte, 1)])

3. CRNN相关模块安装与导入

  1. !pip install -i https://pypi.tuna.tsinghua.edu.cn/simple keras==2.1.6
  2. !pip install -i https://pypi.tuna.tsinghua.edu.cn/simple keras_applications==1.0.5

  1. Requirement already satisfied: keras==2.1.6 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages
  2. Requirement already satisfied: numpy>=1.9.1 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras==2.1.6)
  3. Requirement already satisfied: six>=1.9.0 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras==2.1.6)
  4. Requirement already satisfied: scipy>=0.14 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras==2.1.6)
  5. Requirement already satisfied: pyyaml in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras==2.1.6)
  6. Requirement already satisfied: h5py in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras==2.1.6)
  7. [33mYou are using pip version 9.0.1, however version 21.0.1 is available.
  8. You should consider upgrading via the 'pip install --upgrade pip' command.[0m
  9. Requirement already satisfied: keras_applications==1.0.5 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages
  10. Requirement already satisfied: h5py in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras_applications==1.0.5)
  11. Requirement already satisfied: keras>=2.1.6 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras_applications==1.0.5)
  12. Requirement already satisfied: numpy>=1.9.1 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras_applications==1.0.5)
  13. Requirement already satisfied: six in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from h5py->keras_applications==1.0.5)
  14. Requirement already satisfied: pyyaml in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras>=2.1.6->keras_applications==1.0.5)
  15. Requirement already satisfied: scipy>=0.14 in /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages (from keras>=2.1.6->keras_applications==1.0.5)
  16. [33mYou are using pip version 9.0.1, however version 21.0.1 is available.
  17. You should consider upgrading via the 'pip install --upgrade pip' command.[0m

  1. from keras.layers import Flatten, BatchNormalization, Permute, TimeDistributed, Dense, Bidirectional, GRU
  2. from keras.layers import Input, Conv2D, MaxPooling2D, ZeroPadding2D,Lambda
  3. from keras.models import Model
  4. from keras.optimizers import SGD
  5. from keras import backend as K
  6. import keys as keys
  7. from CRNN_model import decode

Using TensorFlow backend.

4. 加载CTPN模型

  1. checkpoint_path = './E2E_ocr/models/checkpoints/' # 训练模型保存路径
  2. vgg_path = "./E2E_ocr/models/vgg_16.ckpt" # vgg16预训练模型
  3. image_path = './E2E_ocr/data/CTW-200' # 训练集图片路径
  4. CHECKPOINT_PATH = './E2E_ocr/models/checkpoints' # 测试模型保存路径
  5. os.environ['CUDA_VISIBLE_DEVICES'] = '0' #计算设备调用,空值为CPU计算,数字为GPU的序号
  6. tf.reset_default_graph()
  7. # 定义模型输入信息占位符
  8. input_image = tf.placeholder(tf.float32, shape=[None, None, None, 3], name='input_image')
  9. input_im_info = tf.placeholder(tf.float32, shape=[None, 3], name='input_im_info')
  10. init_op = tf.initialize_all_variables()
  11. # 定义模型训练步骤数
  12. global_step = tf.variable_scope('global_step', [], initializer=tf.constant_initializer(0))
  13. # 加载预训练模型
  14. bbox_pred, cls_pred, cls_prob = model.model(input_image)
  15. variable_averages = tf.train.ExponentialMovingAverage(0.997, global_step)
  16. # 将变量存储到saver中
  17. saver = tf.train.Saver(variable_averages.variables_to_restore())
  18. ctpn_sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
  19. with ctpn_sess.as_default():
  20. # 加载预训练模型权重信息
  21. ckpt_state = tf.train.get_checkpoint_state(CHECKPOINT_PATH)
  22. model_path = os.path.join(CHECKPOINT_PATH, os.path.basename(ckpt_state.model_checkpoint_path))
  23. saver.restore(ctpn_sess, model_path)
  24. print('CTPN model load success')

  1. WARNING:tensorflow:From /home/ma-user/anaconda3/envs/TensorFlow-1.8/lib/python3.6/site-packages/tensorflow/python/util/tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
  2. Instructions for updating:
  3. Use `tf.global_variables_initializer` instead.
  4. CTPN model load success

CTPN为了更好检测出文本区域,anchor为 宽度固定为16 , 高度为[11, 16, 23, 33, 48, 68, 97, 139, 198, 283] 的文本框,共10个anchor。

这样的设计是为了更好检测出文字区域的水平位置,在文字检测中,检测文字的水平范围比较垂直范围要更困难。将anchor的宽度固定,只检测10个高度的anchor,尤其在面对多个分离的文本的情况时,能够更好检测文字的范围。

不同的anchor得到了边界框,利用nms(非极大值抑制)进行边界框回归计算,最终得到细粒度的文本区域。

5. 加载CRNN模型

下图给出CRNN的结构参考:

  1. characters = keys.alphabet[:]
  2. nclass=len(characters)+1
  3. input = Input(shape=(32, None, 1), name='the_input')
  4. # CNN卷积层部分
  5. m = Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same', name='conv1')(input)
  6. m = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name='pool1')(m)
  7. m = Conv2D(128, kernel_size=(3, 3), activation='relu', padding='same', name='conv2')(m)
  8. m = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), name='pool2')(m)
  9. m = Conv2D(256, kernel_size=(3, 3), activation='relu', padding='same', name='conv3')(m)
  10. m = Conv2D(256, kernel_size=(3, 3), activation='relu', padding='same', name='conv4')(m)
  11. m = ZeroPadding2D(padding=(0, 1))(m)
  12. m = MaxPooling2D(pool_size=(2, 2), strides=(2, 1), padding='valid', name='pool3')(m)
  13. m = Conv2D(512, kernel_size=(3, 3), activation='relu', padding='same', name='conv5')(m)
  14. m = BatchNormalization(axis=1)(m)
  15. m = Conv2D(512, kernel_size=(3, 3), activation='relu', padding='same', name='conv6')(m)
  16. m = BatchNormalization(axis=1)(m)
  17. m = ZeroPadding2D(padding=(0, 1))(m)
  18. m = MaxPooling2D(pool_size=(2, 2), strides=(2, 1), padding='valid', name='pool4')(m)
  19. m = Conv2D(512, kernel_size=(2, 2), activation='relu', padding='valid', name='conv7')(m)
  20. m = Permute((2, 1, 3), name='permute')(m)
  21. m = TimeDistributed(Flatten(), name='timedistrib')(m)
  22. # RNN循环层部分
  23. m = Bidirectional(GRU(256, return_sequences=True), name='blstm1')(m)
  24. m = Dense(256, name='blstm1_out', activation='linear')(m)
  25. m = Bidirectional(GRU(256, return_sequences=True), name='blstm2')(m)
  26. y_pred = Dense(nclass, name='blstm2_out', activation='softmax')(m)
  27. basemodel = Model(inputs=input, outputs=y_pred)
  28. basemodel.load_weights('./E2E_ocr/CRNN/model_crnn.h5')
  29. print("CRNN model load success")

CRNN model load success

6. 定义文字位置检测函数

  1. from CTPN.utils.text_connector.text_connect_cfg import Config as TextLineCfg
  2. def ctpn_text_detection(img_path):
  3. """
  4. CTPN文字位置检测函数
  5. :param img_path: 图片路径
  6. :return: img: 需要进行文字检测的图片
  7. :return: boxes: 图片上检测到的文字框
  8. """
  9. try:
  10. im = cv2.imread(img_path)[:, :, ::-1]
  11. except Exception as e:
  12. raise Exception("打开图片文件失败,图片路径:", img_path)
  13. img, (rh, rw) = resize_image(im) #对图片进行形状调整
  14. h, w, c = img.shape
  15. im_info = np.array([h, w, c]).reshape([1, 3])
  16. #将图片信息传入模型得出预测结果,分别为文字区域坐标以及其得分
  17. bbox_pred_val, cls_prob_val = ctpn_sess.run([bbox_pred, cls_prob],feed_dict={input_image: [img],input_im_info: im_info})
  18. textsegs_total, _ = proposal_layer(cls_prob_val, bbox_pred_val, im_info)
  19. scores = textsegs_total[:, 0]
  20. textsegs = textsegs_total[:, 1:5]
  21. """文本框合并策略"""
  22. TextLineCfg.MAX_HORIZONTAL_GAP = 50 # 两个框之间的距离小于50,才会被判定为临近框。该值越小,两个框之间要进行合并的要求就越高
  23. TextLineCfg.TEXT_PROPOSALS_MIN_SCORE = 0.7 # 单个小文本框的置信度,高于这个置信度的框才会被合并。该值越大,越多的框就会被丢弃掉
  24. TextLineCfg.TEXT_PROPOSALS_NMS_THRESH = 0.2 # 非极大值抑制阈值。该值越大,越多的框就会被丢弃掉
  25. TextLineCfg.MIN_V_OVERLAPS = 0.7 # 两个框之间的垂直重合度大于0.7,才会被判定为临近框。该值越大,两个在垂直方向上有偏差的框进行合并的可能性就越小
  26. textdetector = TextDetector(DETECT_MODE='H') # DETECT_MODE有两种取值:'H''O''H'模式适合检测水平文字,'O'模式适合检测有轻微倾斜的文字
  27. """文本框合并策略"""
  28. boxes = textdetector.detect(textsegs, scores[:, np.newaxis], img.shape[:2])
  29. boxes = np.array(boxes, dtype=np.int)
  30. return img, boxes

7. 定义文字块切片函数

  1. def img_transform_perspective(image, points, w_pad_rate=(0.0, 0.0), h_pad_rate=(0.0, 0.0)):
  2. """
  3. 根据四个点进行透视变换,将四个点表示的四边形图变换成水平矩形图
  4. :param image: 原图
  5. :param points: 参考的四个点,坐标顺序是xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax
  6. :param w_pad_rate: 数组(rate1, rate2),对图像宽度左右两边的扩宽比例
  7. :param h_pad_rate: 数组(rate1, rate2),对图像宽度上下两边的扩宽比例
  8. :return: persp_img: 变换后的图
  9. :return: points2: 变换后的四点
  10. """
  11. if not isinstance(points, np.ndarray):
  12. points = np.array(points)
  13. points = points.reshape((4, 2))
  14. widths = np.linalg.norm(points[::2] - points[1::2], axis=1) # points的4点组成的四边形的上下两边的长度
  15. width = int(round(widths.mean()))
  16. heights = np.linalg.norm(points[:2] - points[3:1:-1], axis=1) # points的4点组成的四边形的左右两边的长度
  17. height = int(round(heights.mean()))
  18. points2 = np.array([[0, 0], [width - 1, 0],
  19. [width - 1, height - 1], [0, height - 1]], np.float32)
  20. points2 += np.array([int(width * w_pad_rate[0]), int(height * h_pad_rate[0])]).reshape(1, 2)
  21. size = (int(width * (1 + w_pad_rate[0] + w_pad_rate[1])),
  22. int(height * (1 + h_pad_rate[0] + h_pad_rate[1])))
  23. mat = cv2.getPerspectiveTransform(points.astype(np.float32), points2)
  24. persp_img = cv2.warpPerspective(image, mat, size,
  25. borderMode=cv2.BORDER_CONSTANT,
  26. borderValue=(255, 255, 255))
  27. return persp_img, points2

8. 定义CRNN字符识别函数

  1. def crnn_ocr(img):
  2. """
  3. CRNN字符识别函数
  4. :param img: 需要进行字符识别的图片
  5. :return: ocr_result: 图片的字符识别结果,数据类型为字符串
  6. """
  7. img = img.convert('L')
  8. img = img.convert('L') # 图片灰度化
  9. scale = img.size[1] * 1.0 / 32 # 图片尺寸调整,把图片高度调整为32
  10. w = img.size[0] / scale
  11. w = int(w)
  12. img = img.resize((w, 32))
  13. img = np.array(img).astype(np.float32) / 255.0
  14. X = img.reshape((32, w, 1))
  15. X = np.array([X])
  16. y_pred = basemodel.predict(X) # 预测
  17. ocr_result = decode(y_pred) # 处理预测结果
  18. return ocr_result

9. 查看原图

  1. img = Image.open('./E2E_ocr/test_dataset/text.png')
  2. img

10. 开始图片测试

  1. test_dir = './E2E_ocr/test_dataset' # 待测试图片目录
  2. save_results = True
  3. output_dir = test_dir + '_output'
  4. if not os.path.exists(output_dir):
  5. os.mkdir(output_dir)
  6. ocr_results = OrderedDict()
  7. files = os.listdir(test_dir)
  8. for file_name in files:
  9. if not (file_name.endswith('jpg') or file_name.endswith('png')
  10. or file_name.endswith('JPG') or file_name.endswith('PNG')):
  11. continue
  12. print(file_name, 'ocr result:')
  13. file_path = os.path.join(test_dir, file_name)
  14. img, boxes = ctpn_text_detection(file_path) # step1, 检测文字位置
  15. sorted_boxes = sorted(boxes.tolist(), key = lambda x: (x[1], x[0])) # step2, 对文字框进行排序,优先按文字框左上顶点的y坐标升序排序,其次按x坐标升序排序
  16. for index, box in enumerate(sorted_boxes):
  17. cut_text_img, _ = img_transform_perspective(img, box[:8]) # step3, 从原图上切割出各个文字块,并将倾斜的文字块变换为水平矩形文字块
  18. ocr_result = crnn_ocr(Image.fromarray(cut_text_img)) # step4, 对每个文字块进行字符识别
  19. ocr_results[str(index)] = ocr_result
  20. print(str(index) + ',', ocr_result)
  21. if save_results:
  22. draw_img = img[:, :, ::-1].copy()
  23. for i, box in enumerate(boxes):
  24. cv2.polylines(draw_img, [box[:8].astype(np.int32).reshape((-1, 1, 2))], True, color=(0, 0, 255), thickness=2)
  25. cv2.imwrite(os.path.join(output_dir, file_name), draw_img)
  26. #将输出结果转为json格式
  27. with codecs.open(os.path.join(output_dir, file_name.split('.')[0] + '.json'), 'w', 'utf-8') as f:
  28. json.dump(ocr_results, f, indent=4, ensure_ascii=False)
  29. print('end')

  1. text.png ocr result:
  2. 0, A1正在改变我们的生活,
  3. 1, 正在改变我们身边的各行各业,
  4. 2, 但是这条通往智能世界的路并不平坦,
  5. 3, 其中一个巨大鸿沟就是AI人才的稀缺。
  6. 4, 在中国庞大的I从业群体,
  7. 5, A开发者缺口达百万级。
  8. 6, A1将成为全民普及性的技能,
  9. 7, 所以今天华为云El为大家带来《2020华为云AI实战营》免费课程,
  10. 8, 大幅降低A1拳习门]椤,
  11. 9, 帮助庞大的软件开发者群体快速拳握A1技能,
  12. 10, 把AI用起来。
  13. end

点击关注,第一时间了解华为云新鲜技术~

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/579409
推荐阅读
相关标签
  

闽ICP备14008679号