利用pytorch CNN手写字母识别神经网络模型识别多手写字母(A-Z)
ztj100 2024-10-31 16:14 17 浏览 0 评论
往期的文章,我们分享了手写字母的训练与识别
使用EMNIST数据集训练第一个pytorch CNN手写字母识别神经网络
利用pytorch CNN手写字母识别神经网络模型识别手写字母
哪里的文章,我们只是分享了单个字母的识别,如何进行多个字母的识别,其思路与多数字识别类似,首先对图片进行识别,并进行每个字母的轮廓识别,然后进行字母的识别,识别完成后,直接在图片上进行多个字母识别结果的备注
Pytorch利用CNN卷积神经网络进行多数字(0-9)识别
搭建神经网络
根据上期文章的分享,我们搭建一个手写字母识别的神经网络
import torch
import torch.nn as nn
from PIL import Image # 导入图片处理工具
import PIL.ImageOps
import numpy as np
from torchvision import transforms
import cv2
import matplotlib.pyplot as plt
# #####设置参数#######################
widthImg = 640
heightImg = 480
kernal = np.ones((5, 5))
minArea = 800
# 定义神经网络
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Sequential( # input shape (1, 28, 28)
nn.Conv2d(
in_channels=1, # 输入通道数
out_channels=16, # 输出通道数
kernel_size=5, # 卷积核大小
stride=1, #卷积步数
padding=2, # 如果想要 con2d 出来的图片长宽没有变化,
# padding=(kernel_size-1)/2 当 stride=1
), # output shape (16, 28, 28)
nn.ReLU(), # activation
nn.MaxPool2d(kernel_size=2), # 在 2x2 空间里向下采样, output shape (16, 14, 14)
)
self.conv2 = nn.Sequential( # input shape (16, 14, 14)
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
nn.ReLU(), # activation
nn.MaxPool2d(2), # output shape (32, 7, 7)
)
self.out = nn.Linear(32 * 7 * 7, 37) # 全连接层,A/Z,a/z一共37个类
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1) # 展平多维的卷积图成 (batch_size, 32 * 7 * 7)
output = self.out(x)
return output
第一层,我们输入Eminist的数据集,Eminist的数据图片是一维 28*28的图片,所以第一层的输入(1,28,28),高度为1,设置输出16通道,使用5*5的卷积核对图片进行卷积运算,每步移动一格,为了避免图片尺寸变化,设置pading为2,则经过第一层卷积就输出(16,28,28)数据格式
再经过relu与maxpooling (使用2*2卷积核)数据输出(16,14,14)
第二层卷积层是简化写法nn.Conv2d(16, 32, 5, 1, 2)的第一个参数为输入通道数in_channels=16,其第二个参数是输出通道数out_channels=32, # n_filters(输出通道数),第三个参数为卷积核大小,第四个参数为卷积步数,最后一个为pading,此参数为保证输入输出图片的尺寸大小一致
self.conv2 = nn.Sequential( # input shape (16, 14, 14)
nn.Conv2d(16, 32, 5, 1, 2), # output shape (32, 14, 14)
nn.ReLU(), # activation
nn.MaxPool2d(2), # output shape (32, 7, 7)
)
全连接层,最后使用nn.linear()全连接层进行数据的全连接数据结构(32*7*7,37)以上便是整个卷积神经网络的结构,
大致为:input-卷积-Relu-pooling-卷积
-Relu-pooling-linear-output
卷积神经网络建完后,使用forward()前向传播神经网络进行输入图片的识别
step 2:图片预处理
# 预处理函数
def preProccessing(img):
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1)
imgCanny = cv2.Canny(imgBlur, 200, 200)
imgDial = cv2.dilate(imgCanny, np.ones((5, 5)), iterations=2) # 膨胀操作
imgThres = cv2.erode(imgDial, np.ones((5, 5)), iterations=1) # 腐蚀操作
return imgThres
这里我们使用腐蚀,膨胀操作对图片进行一下预处理操作,方便神经网络的识别,当然,我们往期的字母数字识别也可以添加此预处理操作,方便神经网络进行预测,提高精度
step 3:图片轮廓检测获取每个数字的坐标位置
def getContours(img):
x, y, w, h, xx, yy, ss = 0, 0, 10, 10, 20, 20, 10 # 因为图像大小不能为0
imgGet = np.array([[], []]) # 不能为空
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # 检索外部轮廓
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 800: # 面积大于800像素为封闭图形
cv2.drawContours(imgCopy, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt, True) # 计算周长
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) # 计算有多少个拐角
x, y, w, h = cv2.boundingRect(approx) # 得到外接矩形的大小
a = (w + h) // 2
dd = abs((w - h) // 2) # 边框的差值
imgGet = imgProcess[y:y + h, x:x + w]
if w <= h: # 得到一个正方形框,边界往外扩充20像素,黑色边框
imgGet = cv2.copyMakeBorder(imgGet, 20, 20, 20 + dd, 20 + dd, cv2.BORDER_CONSTANT, value=[0, 0, 0])
xx = x - dd - 10
yy = y - 10
ss = h + 20
cv2.rectangle(imgCopy, (x - dd - 10, y - 10), (x + a + 10, y + h + 10), (0, 255, 0),
2) # 看看框选的效果,在imgCopy中
print(a + dd, h)
else: # 边界往外扩充20像素值
imgGet = cv2.copyMakeBorder(imgGet, 20 + dd, 20 + dd, 20, 20, cv2.BORDER_CONSTANT, value=[0, 0, 0])
xx = x - 10
yy = y - dd - 10
ss = w + 20
cv2.rectangle(imgCopy, (x - 10, y - dd - 10), (x + w + 10, y + a + 10), (0, 255, 0), 2)
print(a + dd, w)
Temptuple = (imgGet, xx, yy, ss) # 将图像及其坐标放在一个元组里面,然后再放进一个列表里面就可以访问了
Borderlist.append(Temptuple)
return Borderlist
getContours函数主要是进行图片中数字区域的区分,把每个数字的坐标检测出来,这样就可以 把每个字母进行CNN卷积神经网络的识别,进而实现多个字母识别的目的
step 4模型处理
Borderlist = [] # 不同的轮廓图像及坐标
Resultlist = [] # 识别结果
img = cv2.imread('55.png')
imgCopy = img.copy()
imgProcess = preProccessing(img)
Borderlist = getContours(imgProcess)
train_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Grayscale(),
transforms.Resize((28, 28)),
transforms.ToTensor(),
])
model = CNN()
model.load_state_dict(torch.load('./model/Eminist.pth', map_location='cpu'))
model.eval()
首先,输入一张需要检测的图片,通过preProccessing图片预处理与getContours函数获取图片中的每个字母的轮廓位置
transforms.Compose此函数可以 把输入图片进行pytorch相关的图片操作,包括转换到torch,灰度空间转换,resize,缩放等等操作
然后加载我们前期训练好的模型
step 5 UTF8字符转换
def get_mapping(num, with_type='letters'):
"""
根据 mapping,由传入的 num 计算 UTF8 字符。
"""
if with_type == 'byclass':
if num <= 9:
return chr(num + 48) # 数字
elif num <= 35:
return chr(num + 55) # 大写字母
else:
return chr(num + 61) # 小写字母
elif with_type == 'letters':
return chr(num + 64) # 大写/小写字母
elif with_type == 'digits':
return chr(num + 96)
else:
return num
由于神经网络识别完成后,反馈给程序的是字母的UTF-8编码,我们通过查表来找到对应的字母
字符编码表(UTF-8)
step 6 神经网络识别
if len(Borderlist) != 0: # 不能为空
for (imgRes, x, y, s) in Borderlist:
cv2.imshow('imgCopy', imgRes)
cv2.waitKey(0)
imgRes = cv2.flip(imgRes,1)
(h, w) = imgRes.shape[:2]
(cX,cY) = (w // 2, h // 2)
M = cv2.getRotationMatrix2D((cX,cY), 90, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
imgRes = cv2.warpAffine(imgRes, M, (nW, nH))
cv2.imshow('imgThres',imgRes)
cv2.waitKey(0)
img = train_transform(imgRes)
img = torch.unsqueeze(img, dim=0)
with torch.no_grad():
pre = model(img)
output = torch.squeeze(pre)
predict = torch.softmax(output, dim=0)
predict_cla = torch.argmax(predict).numpy()
print(get_mapping(predict_cla), predict[predict_cla].numpy())
result = get_mapping(predict_cla)
cv2.rectangle(imgCopy, (x, y), (x + s, y + s), color=(0, 255, 0), thickness=1)
cv2.putText(imgCopy, result, (x + s // 2 - 5, y + s // 2 - 5), cv2.FONT_HERSHEY_COMPLEX, 1.5, (0, 0, 255), 2)
cv2.imshow('imgCopy', imgCopy)
cv2.waitKey(0)
通过上面的操作,我们已经识别出了图片中包括的字母轮廓,我们遍历每个字母轮廓,获取单个字母图片数据,这里需要特殊提醒一下:我们知道EMNIST数据库左右翻转图片后,又进行了图片的逆时针旋转90度
这里我们使用cv2.flip(imgRes,1)函数,进行图片的镜像,并使用getRotationMatrix2D函数与warpAffine函数配合来进行图片的旋转操作,这里就没有PIL来的方便些
imgRes = cv2.flip(imgRes,1)
(h, w) = imgRes.shape[:2]
(cX,cY) = (w // 2, h // 2)
M = cv2.getRotationMatrix2D((cX,cY), 90, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
imgRes = cv2.warpAffine(imgRes, M, (nW, nH))
然后,我们对图片数据进行torch转换train_transform(imgRes),并传递给神经网络进行识别
待识别完成后,就可以把结果备注在原始图片上
相关推荐
- 如何将数据仓库迁移到阿里云 AnalyticDB for PostgreSQL
-
阿里云AnalyticDBforPostgreSQL(以下简称ADBPG,即原HybridDBforPostgreSQL)为基于PostgreSQL内核的MPP架构的实时数据仓库服务,可以...
- Python数据分析:探索性分析
-
写在前面如果你忘记了前面的文章,可以看看加深印象:Python数据处理...
- C++基础语法梳理:算法丨十大排序算法(二)
-
本期是C++基础语法分享的第十六节,今天给大家来梳理一下十大排序算法后五个!归并排序...
- C 语言的标准库有哪些
-
C语言的标准库并不是一个单一的实体,而是由一系列头文件(headerfiles)组成的集合。每个头文件声明了一组相关的函数、宏、类型和常量。程序员通过在代码中使用#include<...
- [深度学习] ncnn安装和调用基础教程
-
1介绍ncnn是腾讯开发的一个为手机端极致优化的高性能神经网络前向计算框架,无第三方依赖,跨平台,但是通常都需要protobuf和opencv。ncnn目前已在腾讯多款应用中使用,如QQ,Qzon...
- 用rust实现经典的冒泡排序和快速排序
-
1.假设待排序数组如下letmutarr=[5,3,8,4,2,7,1];...
- ncnn+PPYOLOv2首次结合!全网最详细代码解读来了
-
编辑:好困LRS【新智元导读】今天给大家安利一个宝藏仓库miemiedetection,该仓库集合了PPYOLO、PPYOLOv2、PPYOLOE三个算法pytorch实现三合一,其中的PPYOL...
- C++特性使用建议
-
1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...
- Qt4/5升级到Qt6吐血经验总结V202308
-
00:直观总结增加了很多轮子,同时原有模块拆分的也更细致,估计为了方便拓展个管理。把一些过度封装的东西移除了(比如同样的功能有多个函数),保证了只有一个函数执行该功能。把一些Qt5中兼容Qt4的方法废...
- 到底什么是C++11新特性,请看下文
-
C++11是一个比较大的更新,引入了很多新特性,以下是对这些特性的详细解释,帮助您快速理解C++11的内容1.自动类型推导(auto和decltype)...
- 掌握C++11这些特性,代码简洁性、安全性和性能轻松跃升!
-
C++11(又称C++0x)是C++编程语言的一次重大更新,引入了许多新特性,显著提升了代码简洁性、安全性和性能。以下是主要特性的分类介绍及示例:一、核心语言特性1.自动类型推导(auto)编译器自...
- 经典算法——凸包算法
-
凸包算法(ConvexHull)一、概念与问题描述凸包是指在平面上给定一组点,找到包含这些点的最小面积或最小周长的凸多边形。这个多边形没有任何内凹部分,即从一个多边形内的任意一点画一条线到多边形边界...
- 一起学习c++11——c++11中的新增的容器
-
c++11新增的容器1:array当时的初衷是希望提供一个在栈上分配的,定长数组,而且可以使用stl中的模板算法。array的用法如下:#include<string>#includ...
- C++ 编程中的一些最佳实践
-
1.遵循代码简洁原则尽量避免冗余代码,通过模块化设计、清晰的命名和良好的结构,让代码更易于阅读和维护...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)