手把手教用摄像头识别数字
时间: 2023-11-19 18:05:15 浏览: 98
1.下载并安装OpenCV库
2.安装Python环境
3.导入OpenCV库
4.打开摄像头
5.读取摄像头中的图像
6.将图像转换为灰度图像
7.进行图像二值化处理
8.对数字进行分割
9.对数字进行预处理
10.将数字图像转换为28 * 28像素的图像
11.加载已经训练好的模型
12.使用模型对数字进行预测
13.将预测结果显示在图像上
14.关闭摄像头
代码实现如下:
import cv2
import numpy as np
# 导入已训练好的模型
from keras.models import load_model
model = load_model('model.h5')
# 定义识别函数
def predict(img):
# 将图像转换为28 * 28像素的图像
img = cv2.resize(img, (28, 28))
# 将图像转换为灰度图像
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
# 对数字进行分割
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 对数字进行预处理
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
if w < 10 or h < 10:
continue
y1 = y - 10 if y - 10 >= 0 else 0
y2 = y + h + 10 if y + h + 10 <= img.shape[0] else img.shape[0]
x1 = x - 10 if x - 10 >= 0 else 0
x2 = x + w + 10 if x + w + 10 <= img.shape[1] else img.shape[1]
digit = img[y1:y2, x1:x2]
# 将数字图像转换为28 * 28像素的图像
digit = cv2.resize(digit, (28, 28))
# 将图像从二维数组转换为一维数组
digit = np.reshape(digit, (1, 28, 28, 1))
# 使用模型对数字进行预测
pred = model.predict(digit)
# 将预测结果显示在图像上
cv2.putText(img, str(np.argmax(pred)), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
return img
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头中的图像
ret, frame = cap.read()
# 调用识别函数
img = predict(frame)
# 显示图像
cv2.imshow('camera', img)
# 按下'q'键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 关闭摄像头
cap.release()
cv2.destroyAllWindows()