特征匹配实现印刷体数字识别,卷积神经网络实现印刷体数字识别(很可靠)
1.印刷体数字识别(特征匹配)
1.首先需要了解为什么印刷体数字识别我使用的是特征匹配的方法,我起初也走了很多的坑,当初固执的识别印刷体数字去使用cnn(卷积神经网络),但是没有专用的印刷体数字的数据集供我去训练卷积神经网络,我却很傻很天真的将mnist手写体数字数据集用作训练。我先在郑重的告诉你们卷积神经网络可以训练印刷体数字,并且得到正确的结果,但是这很难,我在讲解完特征匹配识别印刷体数字后会告诉你们运用卷积神经网络怎样去操作!
2.以下为特征匹配识别印刷体数字的代码,在这里感谢这篇博客: 点一下
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int getColSum(Mat src, int col) //统计所有列的总和
{
int sum = 0;
int height = src.rows;
int width = src.cols;
for (int i = 0; i < height; i++)
{
sum = sum + src.at<uchar>(i, col);
}
return sum;
}
int getRowSum(Mat src, int row)//统计所有行的总和
{
int sum = 0;
int height = src.rows;
int width = src.cols;
for (int i = 0; i < width; i++)
{
sum = sum + src.at<uchar>(row,i);
}
return sum;
}
void cutTop(Mat& src, Mat& dstImg) //切掉图片的上下空白
{
int top, bottom;
top = 0;
bottom = src.rows;
int i;
for (i = 0; i < src.rows; i++)
{
int colValue = getRowSum(src, i);
if (colValue > 0)
{
top = i;
break;
}
}
for (; i < src.rows; i++)
{
int colValue = getRowSum(src, i);
if (colValue == 0)
{
bottom = i;
break;
}
}
int height = bottom - top;
Rect rect(0, top, src.cols, height);
dstImg = src(rect).clone();
}
int cutLeft(Mat& src, Mat& leftImg, Mat& rightImg) //切掉左边空白和数字切割
{
int left, right;
left = 0;
right = src.cols;
int i;
for (i = 0; i < src.cols; i++)
{
int colValue = getColSum(src, i);
if (colValue > 0)
{
left = i;
break;
}
}
if (left == 0)
{
return 1;
}
for (; i < src.cols; i++)
{
int colValue = getColSum(src, i);
if (colValue == 0)
{
right = i;
break;
}
}
int width = right - left;
Rect rect(left, 0, width, src.rows);
leftImg = src(rect).clone();
Rect rectRight(right, 0, src.cols-right, src.rows);
rightImg = src(rectRight).clone();
cutTop(leftImg, leftImg);
return 0;
}
void getPXSum(Mat &src, int &a) //计算图像总和
{
threshold(src, src, 100, 255, CV_THRESH_BINARY);
a = 0;
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{
a += src.at<uchar>(i, j);
}
}
}
int getSubtract(Mat &src, int TemplateNum) //用于识别数字
{
Mat img_result;
int min = 1000000;
int serieNum = 0;
for (int i = 0; i <= TemplateNum; i++)
{
char name[20];
sprintf_s(name, "%d.png", i);
Mat Template = imread(name, CV_LOAD_IMAGE_GRAYSCALE);
threshold(Template, Template, 100, 255, CV_THRESH_BINARY);
threshold(src, src, 100, 255, CV_THRESH_BINARY);
resize(src, src, Size(50, 50), 0, 0, CV_INTER_LINEAR);
resize(Template, Template, Size(50, 50), 0, 0, CV_INTER_LINEAR);
absdiff(Template, src, img_result);
int diff = 0;
getPXSum(img_result, diff);
if (diff < min)
{
min = diff;
serieNum = i;
}
}
printf("最小距离是%d", min);
printf("匹配到第%d个模板匹配的数字是%d\n", serieNum, serieNum);
return serieNum;
}
int main()
{
//用于模板建立,建立模板的时候只需要将0-9的模板图片放入程序同一目录下即可,同时要注意命名!!
for (int i = 0; i < 10; i++)
{
char fileName[10];
sprintf_s(fileName, "%d.png", i);
Mat src = imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
threshold(src, src, 100, 255, CV_THRESH_BINARY_INV);
Mat rImg,dst;
cutLeft(src, dst, rImg);
imwrite(fileName, dst);
}
//用于识别
//Mat src = imread("z.png", CV_LOAD_IMAGE_GRAYSCALE);//图z就是要识别的印刷体数字
//threshold(src, src, 100, 255, CV_THRESH_BINARY_INV);
//imshow("origin", src);
//Mat leftImg, rightImg;
//int res = cutLeft(src, leftImg, rightImg);
//while (res == 0)
//{
// Mat srcTmp = rightImg;
// getSubtract(leftImg, 9);
// res = cutLeft(srcTmp, leftImg, rightImg);
//}
waitKey(0);
return 0;
}
注意:这块代码中制作匹配模板的时候要将用于识别的代码块注释掉,识别的时候,要将用于制作匹配模板的代码注释掉。
3.我将我使用的0-9数字的匹配模板制作的图片放上来,基本没什么问题,用这些图片就可以制作出匹配的模板。你想识别的图片在word上写出来就可以了,数字串和单个数字都可以识别。
2.印刷体数字识别(cnn卷积神经网络)
1.需要注意了,网上流传的mnist手写数字数据集是不可能识别出来印刷体数字的,但总有人认为手写数据集可以做到对印刷体数字的识别,目前初步认为是过拟合的原因。(因为手写体数据集光图片就有60000张,印刷体摸样太过于单调,很容易过拟合。)
2.我的办法就是自制数据集,自制印刷体数字的数据集,在这里我先感谢一下这一篇博客,这个大佬对自制数据集十分上道。(不是网上广泛流传的TFRecord,试了试比较难成功,而且并不好理解)点一下吧。
我先收集了很多张印刷体数字图片,感谢这个下载链接(他好像404了,等我找到)
制作数据集前我使用了将图片长和宽转化为28*28的代码以及将图片转化为黑底白字的代码(python代码)之后就可以制作数据集了:
#图片长和宽转化为28*28
import cv2
import numpy as np
import os
import glob
def convertpng(pngfile,outdir,width=310,height=16):
img=cv2.imread(pngfile,cv2.IMREAD_ANYCOLOR)
#try:
imgInfo=img.shape
height=imgInfo[0]
Width=imgInfo[1]
dstHeight=28
dstWidth=28
dstImage=np.zeros((dstHeight,dstWidth,3),np.uint8)
#最近领域插值法
for i in range(0,dstHeight):
for j in range(0,dstWidth):
iNew=int(i*(height*1.0/dstHeight))
jNew=int(j*(width*1.0/dstWidth))
dstImage[i,j]=img[iNew,jNew]
cv2.imwrite(os.path.join(outdir,os.path.basename(pngfile)),dstImage)
#print("123")
#except Exception as e:
#print(e)
for pngfile in glob.glob ('C:\ss.png'):
convertpng(pngfile,'D:')
#图片转化为黑底白字的代码
import cv2
import numpy as np
import os
import glob
def convertcolor(pngfile,outdir):
img=cv2.imread(pngfile,cv2.IMREAD_ANYCOLOR)
imgInfo=img.shape
height=imgInfo[0]
width=imgInfo[1]
dst=np.zeros((height,width,3),np.uint8)
for i in range(0,height):
for j in range(0,width):
(b,g,r)=img[i,j]
dst[i,j]=(255-b,255-g,255-r)
cv2.imwrite(os.path.join(outdir,os.path.basename(pngfile)),dst)
for pngfile in glob.glob ('C:\Samp3\*.png'):
convertcolor(pngfile,'C:\SampC3')
3.制作好的数据集想要直接用于卷积神经网络,可以说是困难重重(你怎么导入就是个问题!!),这是目前网络上较为流行的训练mnist手写数字数据集的卷积神经网络(但是,我做了改动,首先你读入mnist数据集使用的input_data.read_data_sets就是不太可行的,但是我仍然使用的是这个,为什么呢,哈哈哈哈,修改函数源代码,接着往下看吧):
#coding=utf-8
# 载入MINIST数据需要的库
from tensorflow.examples.tutorials.mnist import input_data
# 保存模型需要的库
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.framework import graph_util
# 导入其他库
import tensorflow as tf
import cv2
import numpy as np
#获取MINIST数据
#filenames=["YINSHUA_data/"]
#mnist=tf.data.TFRecordDataset(filenames)
mnist = input_data.read_data_sets("YINSHUA_data/",one_hot = True)
# 创建会话
sess = tf.InteractiveSession()
#占位符
x = tf.placeholder("float", shape=[None, 784], name="Mul")
y_ = tf.placeholder("float",shape=[None, 10], name="y_")
#变量
W = tf.Variable(tf.zeros([784,10]),name='x')
b = tf.Variable(tf.zeros([10]),'y_')
#权重
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
#偏差
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)#定义了一个常数
return tf.Variable(initial)
#卷积
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
#最大池化
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def reversePic(src): # 图像反转
for i in range(src.shape[0]):
for j in range(src.shape[1]):
src[i,j] = 255 - src[i,j]
return src
#相关变量的创建
W_conv1 = weight_variable([5, 5, 1, 32])#卷积核的高,宽,图像通道数,卷积核的个数
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])#一个batch的图片数量,图片高宽和通道数
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
#激活函数
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder("float",name='rob')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#用于训练用的softmax函数
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2) + b_fc2,name='res')
#用于训练作完后,作测试用的softmax函数
y_conv2=tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2,name="final_result")
#交叉熵的计算,返回包含了损失值的Tensor。
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
#优化器,负责最小化交叉熵
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
#计算准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
#初始化所有变量
sess.run(tf.global_variables_initializer())
# 保存输入输出,可以为之后用
tf.add_to_collection('res', y_conv)
tf.add_to_collection('output', y_conv2)
tf.add_to_collection('x', x)
#nnn=50
#训练开始
for i in range(20000):
batch = mnist.train.next_batch(50)#批量读取数据
#batch=mnist.batch(nnn)
#nnn+=50
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_: batch[1], keep_prob: 1.0})
print (("step %d, training accuracy %g")%(i, train_accuracy))
#run()可以看做输入相关值给到函数中的占位符,然后计算的出结果,这里将batch[0],给xbatch[1]给y_
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
#将当前图设置为默认图
graph_def = tf.get_default_graph().as_graph_def()
#将上面的变量转化成常量,保存模型为pb模型时需要,注意这里的final_result和前面的y_con2是同名,只有这样才会保存它,否则会报错,
# 如果需要保存其他tensor只需要让tensor的名字和这里保持一直即可
output_graph_def = tf.graph_util.convert_variables_to_constants(sess,
graph_def, ['final_result'])
#保存前面训练后的模型为pb文件
with tf.gfile.GFile("grf.pb", 'wb') as f:
f.write(output_graph_def.SerializeToString())
#用saver 保存模型
saver = tf.train.Saver()
saver.save(sess, "model_data/model")
#导入图片,同时灰度化
im = cv2.imread('4.bmp',cv2.IMREAD_GRAYSCALE)
#反转图像,因为e2.jpg为白底黑字
im =reversePic(im)
cv2.namedWindow("camera", cv2.WINDOW_NORMAL);
cv2.imshow('camera',im)
cv2.waitKey(0)
#调整大小
im = cv2.resize(im,(28,28),interpolation=cv2.INTER_CUBIC)
x_img = np.reshape(im , [-1 , 784])
#输出图像矩阵
# print x_img
#用上面导入的图片对模型进行测试
output = sess.run(y_conv2 , feed_dict={x:x_img })
# print 'the y_con : ', '\n',output
print ('the predict is : ', np.argmax(output))
print (("test accracy %g")%accuracy.eval(feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
4.靠,那篇给了我帮助的input_data.read_data_sets函数内部源码窥探文章找不到了,我现在不知怎么。。。反正我们要知道input_data.read_data_sets原理就是检查你的本地文件下是否存在mnist数据集,不存在就自动给你下载,我们首先需要注释掉自动下载的那一部分,同时修改函数读取时的参数,反正这是必须要去修改源码读取的(你们等我找到。。。)
时隔多日终于找到了,是另外一个大佬的处子文章中写的,我感到很开心!!!!
https://blog.csdn.net/yexu20190327/article/details/89415507