[深度学习]Part1 Python高级Ch25 cnocr——【DeepBlue学习笔记】

2023-11-12

本文仅供学习使用(ocr入门包,具体的文字识别需了解其他内容)


25. cnocr

安装:pip install cnocr
调用:from cnocr import CnOcr

利用cnocr进行识别的时候:

  1. 需要先提取目标区域,比如说车牌识别,那就先提取车牌所在的区域
  2. 目标区域的灰度图或者bgr图传入接口函数中进行识别
  3. 如果目标区域的识别不够精准,则可以再做细粒度的分割,识别同步骤2,注意顺序问题

25.1 几个“简单”的例子

25.1.1 信用卡识别

#encoding:utf8
import  cv2
import numpy as  np
import myutils
from cnocr import CnOcr

#from imutils import contours
def cv_show(str,thing):
    cv2.imshow(str, thing)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
# 指定信用卡类型
FIRST_NUMBER = {
    "3": "American Express",
    "4": "Visa",
    "5": "MasterCard",
    "6": "Discover Card"
}
img=cv2.imread("F:/datas2/number.png")
cv2.imshow('img',img)
# 灰度图
ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#二值化
ref=cv2.threshold(ref,10,255,cv2.THRESH_BINARY_INV)[1]
refCnts,hierarchy=cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img,refCnts,-1,(0,0,255),3)
print (np.array(refCnts).shape)

refCnts = myutils.sort_contours(refCnts, method="left-to-right")[0]#排序,从左到右,从上到下
digits = {}
for (i, c) in enumerate(refCnts):
    # 计算外接矩形并且resize成合适大小
    (x, y, w, h) = cv2.boundingRect(c)
    roi = ref[y:y + h, x:x + w]
    roi = cv2.resize(roi, (57, 88))
    # 每一个数字对应每一个模板
    digits[i] = roi
# 初始化卷积核
rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

#读取输入图像,预处理
image = cv2.imread("F:/datas2/testimage.png")
image = myutils.resize(image, width=300)

gray = image[..., 2]

gradX = cv2.Sobel(gray, ddepth=cv2.CV_32F, dx=1, dy=0, #ksize=-1相当于用3*3的
    ksize=-1)

gradX = np.absolute(gradX)
(minVal, maxVal) = (np.min(gradX), np.max(gradX))
gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
gradX = gradX.astype("uint8")
print (np.array(gradX).shape)
cv_show('gradX',gradX)

gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)

cv_show('gradX_CLOSE',gradX)
thresh = cv2.threshold(gradX, 0, 255,
    cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv_show('thresh',thresh)

# 计算轮廓
threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)

cnts = threshCnts
cur_img = image.copy()
cv2.drawContours(cur_img,cnts,-1,(0,0,255),3)
cv_show('img',cur_img)
locs = []
# 遍历轮廓
for (i, c) in enumerate(cnts):
    # 计算矩形
    (x, y, w, h) = cv2.boundingRect(c)
    ar = w / float(h)
    # 选择合适的区域,根据实际任务来,这里的基本都是四个数字一组
    if ar > 2.5 and ar < 4.0:
        if (w > 40 and w < 55) and (h > 10 and h < 20):
            #符合的留下来
            locs.append((x, y, w, h))
# 将符合的轮廓从左到右排序
locs = sorted(locs, key=lambda x:x[0])
output = []

ocr = CnOcr()
# 遍历每一个轮廓中的数字
for (i, (gX, gY, gW, gH)) in enumerate(locs):
    # initialize the list of group digits
    groupOutput = []

    # 根据坐标提取每一个组
    group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
    cv_show('group',group)
    # 预处理
    group = cv2.threshold(group, 0, 255,
        cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    cv_show('group',group)
    
    # 计算每一组的轮廓
    digitCnts,hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    digitCnts = myutils.sort_contours(digitCnts,
        method="left-to-right")[0]

    # 计算每一组中的每一个数值
    for c in digitCnts:
        # 找到当前数值的轮廓,resize成合适的的大小
        (x, y, w, h) = cv2.boundingRect(c)
        roi = group[y:y + h, x:x + w]
        roi = cv2.resize(roi, (57, 88))
        result = ocr.ocr_for_single_line(roi)
        print('roi_ocr:', result)        
        #cv_show('roi',roi)

        # 计算匹配得分
        scores = []

        # 在模板中计算每一个得分
        for (digit, digitROI) in digits.items():
            # 模板匹配
            result = cv2.matchTemplate(roi, digitROI,
                cv2.TM_CCOEFF)
            (_, score, _, _) = cv2.minMaxLoc(result)
            scores.append(score)

        # 得到最合适的数字
        groupOutput.append(str(np.argmax(scores)))

    # 画出来
    cv2.rectangle(image, (gX - 5, gY - 5),
        (gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
    cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
        cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)

    # 得到结果
    output.extend(groupOutput)

# 打印结果
print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image)
cv2.waitKey(0)

'''
信用卡识别:模板匹配技术进行识别

1.先检测,将目标局域扣下来
1.1获取较大的区域,一共4组
    *sobel边缘检测
    *形态学操作
    *轮廓查找
    *利用轮廓信息过滤
    
1.2然后从每组中获取单个数字的区域
    *轮廓查找
    *利用轮廓信息过滤

2.然后再进行识别
'''
   

在这里插入图片描述

25.1.2 文字截图识别

#coding=utf-8
import cv2
import numpy as np
from cnocr import CnOcr
#import requests
#s = requests.session()
#s.keep_alive = False
#pip install cnocr -i https://pypi.doubanio.com/simple
#https://gitee.com/cyahua/cnocr?utm_source=alading&utm_campaign=repo#%E8%AF%A6%E7%BB%86%E6%96%87%E6%A1%A3

def get_horizontal_projection(image):
    '''
    统计图片水平位置白色像素的个数
    '''
    #图像高与宽
    height_image, width_image = image.shape 
    height_projection = [0]*height_image
    for height in range(height_image):
        for width in range(width_image):
            if image[height, width] == 255:
                height_projection[height] += 1
    return height_projection

def get_vertical_projection(image): 
    '''
    统计图片垂直位置白色像素的个数
    '''
    #图像高与宽
    height_image, width_image = image.shape 
    width_projection = [0]*width_image
    for width in range(width_image):
        for height in range(height_image):
            if image[height, width] == 255:
                width_projection[width] += 1
    return width_projection

def get_text_lines(projections):
    text_lines = []
    start = 0
    for index, projection in enumerate(projections):# projections:每行白色像素点的个数  
        if projection>0 and start==0:# 白色像素点的个数>0 而且start==0 来确定行的开始位置
            start_location = index
            start = 1  #查找一句话的起始位置和结束位置的标志 start=0 要找的是起始位置 start=1 要找的结束位置
        if projection==0 and start==1:# # 白色像素点的个数==0 而且start==1 来确定行的结束位置
            end_location = index
            start = 0
            text_lines.append((start_location,end_location))
    return text_lines

def get_text_word(projections):
    text_word = [ ]
    start = 0
    for index, projection in enumerate(projections):
        if projection>0 and start==0:
            start_location = index
            start = 1
        if projection==0 and start==1:
            end_location = index
            start = 0
            if len(text_word)>0 and start_location-text_word[-1][1]<3:
                text_word[-1] = (text_word[-1][0],end_location)
            else:
                text_word.append((start_location,end_location))
    return text_word  
def orc_text(filePath):
    #ocr = CnOcr()
    image = cv2.imread(filePath,cv2.IMREAD_GRAYSCALE)
    print(image)
    print(image.shape)
    result = []
    height_image, width_image = image.shape
    _, binary_image = cv2.threshold(image,150,255,cv2.THRESH_BINARY_INV)
    height_projection = get_horizontal_projection(binary_image)
    text_lines = get_text_lines(height_projection)
    for line_index, text_line in enumerate(text_lines):
        text_line_image = binary_image[text_line[0]:text_line[1], 0:width_image]
        vertical_projection = get_vertical_projection(text_line_image)
        text_words = get_text_word(vertical_projection)
        text_line_word_image = image[text_line[0]:text_line[1], text_words[0][0]:text_words[-1][1]]   
        res = ocr.ocr_for_single_line(text_line_word_image) 
        result.append(''.join(res))
    return ''.join(result)

if __name__ == '__main__':
    ocr = CnOcr()
    image = cv2.imread('F:/datas2/cnocrtest.png',cv2.IMREAD_GRAYSCALE)
    print(image)
    print(image.shape)
    # cv2.imshow('gray_image', image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    height_image, width_image = image.shape
    _, binary_image = cv2.threshold(image,150,255,cv2.THRESH_BINARY_INV)
    height_projection = get_horizontal_projection(binary_image)
    text_lines = get_text_lines(height_projection)
    for line_index, text_line in enumerate(text_lines):# text_line :(start_location, end_location)
        start_location = text_line[0]
        end_location = text_line[1]
        text_line_image = binary_image[start_location:end_location]
        vertical_projection = get_vertical_projection(text_line_image)
        text_words = get_text_word(vertical_projection)# text_words:这一行的每个字的位置:(w_s,w_e)
        text_line_word_image = image[start_location:end_location, text_words[0][0]:text_words[-1][1]]   
        res = ocr.ocr_for_single_line(text_line_word_image) 
        print(res)

在这里插入图片描述

25.2 使用逻辑

from cnocr import CnOcr

ocr = CnOcr()
path = r"cn1.png"  # 或者直接传入img
res = ocr.ocr_for_single_line(path)
print(res)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[深度学习]Part1 Python高级Ch25 cnocr——【DeepBlue学习笔记】 的相关文章

随机推荐

  • Woedpress分类目录绑定二级域名

    实现分类目录和二级域名绑定需要使用 WordPress 的多站点功能 Multisite 以下是一个基本的步骤和示例代码来实现这个功能 代码实现方法 步骤 将 WordPress 安装为多站点模式 在 WordPress 安装目录下的 wp
  • verdi使用linux命令,vcs和verdi的调试及联合仿真案例

    环境配置 首先搭建好vcs和Verdi都能工作的环境 主要有license问题 环境变量的设置 在220实验室的服务器上所有软件的运行环境都是csh 所以 所写的脚本也都是csh的语法 生成波形文件 Testbench的编写 若想用Verd
  • 机器学习实战8-基于XGBoost和LSTM的台风强度预测模型训练与应用

    大家好 我是微学AI 今天给大家介绍一下机器学习实战8 基于XGBoost和LSTM的台风强度预测模型训练与应用 今年夏天已经来了 南方的夏天经常会有台风登陆 给人们生活带来巨大的影响 本文主要基于XGBoost模型和长短期记忆 LSTM
  • 淘宝滑动验证码研究

    引言 悠闲的时候 总会去找些事做做 前些天在登录淘宝的时候 发现了滑动验证码 虽然已经不是什么新事物 但还是产生了很大的兴趣 传统的字符输入验证码 变为了滑动验证码 这一看就是产品大师的手笔啊 不知道申请专利没有 这种 情感化 的验证码设计
  • C语言深入学习--checklist7:链接、运行时数据结构、申明

    1 你知道段的概念吗 段是二进制文件中的简单区域 里面保存了某种特定的类型 如符号表条目 相关的所有信息 1 可执行程序分为几个段 每个段保存什么内容 可执行程序分为三个段 BSS段 数据段 文本段 BSS段 Block Started b
  • 矩阵迹运算介绍及C++/OpenCV/Eigen的三种实现

    矩阵迹运算返回的是矩阵对角元素的和 迹运算因为很多原因而有用 若不使用求和符号 有些矩阵运算很难描述 而通过矩阵乘法和迹运算符号 可以清楚地表示 例如 迹运算提供了另一种描述矩阵Frobenius范数的方式 用迹运算表示表达式 我们可以使用
  • 2021斯坦福CS224N课程笔记~2

    2 Neural Classifiers 2 1本篇内容覆盖 word2vec与词向量回顾 算法优化基础 计数与共现矩阵 GloVe模型 词向量评估 word senses 2 2 回顾 word2vec 的主要思想 2 2 1 主要步骤
  • Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime

    报错 在进行编译的时候运行到下面的错误 Node Sass does not yet support your current environment Windows 64 bit with Unsupported runtime 88 这
  • 芯片电源引脚的电容选择

    主要内容 参考如下 DC 100K 10uF以上的钽电容或铝电解 100K 10M 100nF 0 1uF 陶瓷电容 10M 100M 10nF 0 01uF 陶瓷电容 100M以上 1nF 0 001uF 陶瓷电容和PCB的地平面与电源平
  • ggplot2技巧书《R数据可视化手册》读书笔记:第二章 快速探索数据

    2 1绘制散点图 基础绘图 plot data x data y ggplot2 qplot data x data y 提前安装 加载ggplot2 qplot x y data 等价于 ggplot data aes x y geom
  • 医学图像分割--Stacked fully convolutional networks with multi-channel learning

    Stacked fully convolutional networks with multi channel learning application to medical image segmentation https link sp
  • c++基本使用(类的静态成员)

    c 基本使用 类的静态成员 静态成员属性 静态成员方法 类的静态成员包括 静态成员变量 静态成员函数 静态成员属性 用 static 关键字把类的成员变量声明为静态 表示它在程序中 不仅是对象 是共享的 静态成员使用类名加范围解析运算符 就
  • 【Dash搭建可视化网站】项目1:使用Dash创建简单网页

    项目1 使用Dash创建简单网页 项目1 使用Dash创建简单网页 1 1 官网示例 1 2 绘制简单网页的基本步骤 1 3 创建一个稍微有意思的页面 手动反爬虫 禁止转载 原博地址 https blog csdn net lys 828
  • Ansible 企业级自动化运维平台开发实战

    一 运维开发 普通的运维方式 使用Xshell或者脚本去操作服务器 运维开发的方式 可以实现把运维的工作Web化 运维开发优点 可以把运维工作简单化 运维工作规划化 运维开发 负责具体的产品的运维工作 同时也需要进行基本的开发 了解业务的痛
  • WPF之层级数据模板HierarchicalDataTemplate的使用

    WPF之层级数据模板HierarchicalDataTemplate的使用 1 HierarchicalDataTemplate List 2 HierarchicalDataTemplate XML 3 TreeView Hierarch
  • 基于Yolov5目标检测的物体分类识别及定位(一) -- 数据集原图获取与标注

    从本篇博客正式开始深度学习项目的记录 实例代码只会放通用的代码 数据集和训练数据也是不会全部放出 系列文章 基于Yolov5目标检测的物体分类识别及定位 一 数据集原图获取与标注 基于Yolov5目标检测的物体分类识别及定位 二 yolov
  • 一道简单的PV操作题

    这是川大操作系统的一道期末考试题 There is an cage and only one animal can be put into this cage The hunters can put tiger into the cage
  • Android自定义View的数独游戏

    Android自定义View的数独游戏 先说一下数独游戏的规则 在整个横坐标和纵坐标的9个格子上只能填土1 9的数字且不重复 在当前3 3 的格子上填入1 9数字且不重复 先给大家看效果图 项目思路 1 UI呈现 这个放在 GameView
  • exit函数及与return的区别

    通常情况 exit 0 表示程序正常 exit 1 exit 1 表示程序异常退出 exit 2 表示表示系统找不到指定的文件 用Error lookup可以查看 exit 结束当前进程 当前程序 在整个程序中 只要调用exit就结束 当前
  • [深度学习]Part1 Python高级Ch25 cnocr——【DeepBlue学习笔记】

    本文仅供学习使用 ocr入门包 具体的文字识别需了解其他内容 Python高级 Ch25 cnocr 25 cnocr 25 1 几个 简单 的例子 25 1 1 信用卡识别 25 1 2 文字截图识别 25 2 使用逻辑 25 cnocr