手写数字识别(图像,视频,实时摄像头)MNIST DATASET(手把手教程):Jupyter+Tensorflow

手写数字识别(图像,视频,实时摄像头)MNIST DATASET(手把手教程):Jupyter+Tensorflow

本实验要用到 Anaconda+Jupyter+Tensorflow没有环境的看这:链接: Anaconda+Jupyter+Opencv+tensorflow安装.有任何问题评论回复。
打开Jupyter:
在这里插入图片描述
注意:因为我们要做图像处理,我希望你需要处理的图像、视频和程序保存在同一位置。
比如:

在这里插入图片描述
我们不需要下载数据集,因为MNIST数据集在tensorflow里,我们只需要用Kares加载就可以了。
实验用了三层卷积和三层全连接。具体原理很多文章讲到,这里就直接上代码了:
代码有详细注释:
首先加载"MNIST Dataset"

在这里插入图片描述
训练和测试数据集:
在这里插入图片描述
正则化之前检查每个像素的值:

在这里插入图片描述

确定是灰度图后,正则化。正则化就是将0-255的数据转化到0-1之间。
在这里插入图片描述
检查标签
在这里插入图片描述
重置置图像大小,使它适合做卷积
在这里插入图片描述
创建一个深度神经网络
在这里插入图片描述
结果:
在这里插入图片描述
训练模型:
在这里插入图片描述
在测试集上预测
在这里插入图片描述
结果:
在这里插入图片描述
现在我手写一个,用来测试:
加载图片:
在这里插入图片描述
重设输入图像参数:
在这里插入图片描述
预测结果:
在这里插入图片描述
识别视频里的手写数字:

import numpy as np
font_scale=1.5 #字体大小
font=cv2.FONT_HERSHEY_PLAIN#字体类型

cap=cv2.VideoCapture('2021-04-04_182439.mp4')
if not cap.isOpened():
    cap=cv2.VideoCapture(0)
if not cap.isOpened():
    raise IOError('Can not open video')
    
text='Some text in a box!'
#获得box的长和宽
(text_width,text_height)=cv2.getTextSize(text,font,fontScale=font_scale,thickness=1)[0]
#设置box的开始位置
text_offset_x=10
text_offset_y=img.shape[0]-25
#设置box的坐标
box_coords=((text_offset_x,text_offset_y),(text_offset_x+text_width+2,text_offset_y-text_height-2))
cntr=0;
while True:
    ret,frame=cap.read()
    cntr=cntr+1;
    if((cntr%2)==0):
        gray=cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)#先将彩图转化为灰度图
        resized=cv2.resize(gray,(28,28),interpolation=cv2.INTER_AREA)#调整输入图片的尺寸
        newing=tf.keras.utils.normalize(resized,axis=1)#正则化
        newing=np.array(newing).reshape(-1,IMG_SIZE,IMG_SIZE,1)#kneral operation 
        predicions=model.predict(newing)
        status=np.argmax(predicions)
        
        print(status)
        print(type(status))
        
        x1,y1,w1,h1=0,0,175,75
        #画绿色的矩形
        cv2.rectangle(frame,(x1,x1),(x1+w1,y1+h1),(0,255,0),-1)
        #add text
        cv2.putText(frame,status.astype(str),(x1+int(w1/5),y1+int(h1/2)),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2)
        
        cv2.imshow('handwritten Digits Recognition Test',frame)
        if cv2.waitKey(2) & 0xFF==ord('q'):
            break
cap.replease()
cv2.destroyAllwimdows()

结果是视频,文章里传不了,请看链接: link.
视频截图:
在这里插入图片描述
在这里插入图片描述

实时摄像头:

import numpy as np
font_scale=1.5 #字体大小
font=cv2.FONT_HERSHEY_PLAIN#字体类型

cap=cv2.VideoCapture(1)
if not cap.isOpened():
    cap=cv2.VideoCapture(0)
if not cap.isOpened():
    raise IOError('Can not open video')
    
text='Some text in a box!'
#获得box的长和宽
(text_width,text_height)=cv2.getTextSize(text,font,fontScale=font_scale,thickness=1)[0]
#设置box的开始位置
text_offset_x=10
text_offset_y=img.shape[0]-25
#设置box的坐标
box_coords=((text_offset_x,text_offset_y),(text_offset_x+text_width+2,text_offset_y-text_height-2))
cntr=0;
while True:
    ret,frame=cap.read()
    cntr=cntr+1;
    if((cntr%2)==0):
        gray=cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)#先将彩图转化为灰度图
        resized=cv2.resize(gray,(28,28),interpolation=cv2.INTER_AREA)#调整输入图片的尺寸
        newing=tf.keras.utils.normalize(resized,axis=1)#正则化
        newing=np.array(newing).reshape(-1,IMG_SIZE,IMG_SIZE,1)#kneral operation 
        predicions=model.predict(newing)
        status=np.argmax(predicions)
        
        print(status)
        print(type(status))
        
        x1,y1,w1,h1=0,0,175,75
        #画绿色的矩形
        cv2.rectangle(frame,(x1,x1),(x1+w1,y1+h1),(0,255,0),-1)
        #add text
        cv2.putText(frame,status.astype(str),(x1+int(w1/5),y1+int(h1/2)),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2)
        
        cv2.imshow('handwritten Digits Recognition Test',frame)
        if cv2.waitKey(2) & 0xFF==ord('q'):
            break
cap.replease()
cv2.destroyAllwimdows()

这个你们自己玩去吧,我就不贴结果了。

  • 3
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,手写数字识别是一个非常经典的图像分类问题,MNIST数据集是一个非常常用的用于手写数字识别的数据集。那么我们可以通过构建一个基于神经网络的模型来实现手写数字的识别。 首先,我们需要加载MNIST数据集,并对数据进行预处理。MNIST数据集中包含了60000张训练图片和10000张测试图片,每张图片都是28*28的灰度图像。我们可以使用PyTorch中的torchvision来加载MNIST数据集: ```python import torch import torchvision import torchvision.transforms as transforms # 定义数据预处理方式 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 加载训练集 trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) # 加载测试集 testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2) ``` 在加载数据集时,我们使用了一个叫做transform的参数,它是用来定义数据预处理的方式的。在这里,我们使用了ToTensor()函数将图片从PIL类型转换成PyTorch中的Tensor类型,并使用了Normalize()函数对数据进行归一化处理,其中(0.1307,)和(0.3081,)是MNIST数据集中所有像素点的均值和标准差。 接下来,我们可以定义一个基于神经网络的模型。在这里,我们使用了一个包含两个隐藏层的全连接神经网络,每个隐藏层包含256个神经元,输出层包含10个神经元,分别代表数字0到9。我们使用ReLU作为激活函数,并使用交叉熵作为损失函数。 ```python import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 256) self.fc3 = nn.Linear(256, 10) def forward(self, x): x = x.view(-1, 784) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() ``` 最后,我们可以使用PyTorch中的优化器和损失函数对模型进行训练,并在测试集上进行测试: ```python import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # 训练模型 for epoch in range(10): # 训练数据集10次 running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 100 == 99: # 每100个batch输出一次loss print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 100)) running_loss = 0.0 print('Finished Training') # 在测试集上测试模型的准确率 correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) ``` 通过运行上述代码,我们可以得到一个在测试集上准确率约为98%的手写数字识别模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值