摄像头数字识别python
时间: 2024-04-07 13:27:12 浏览: 15
以下是使用Python进行摄像头数字识别的示例代码[^1]:
```python
import cv2
import numpy as np
import tensorflow as tf
# 加载训练好的模型
model = tf.keras.models.load_model('digit_recognition_model.h5')
# 定义数字标签
labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头画面
ret, frame = cap.read()
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 对图像进行二值化处理
_, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)
# 寻找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 获取轮廓的边界框
x, y, w, h = cv2.boundingRect(contour)
# 提取数字区域
digit_region = threshold[y:y+h, x:x+w]
# 调整数字区域的大小
resized_digit = cv2.resize(digit_region, (28, 28))
# 将图像转换为模型所需的输入格式
input_data = np.reshape(resized_digit, (1, 28, 28, 1))
input_data = input_data.astype('float32') / 255.0
# 使用模型进行预测
prediction = model.predict(input_data)
predicted_label = np.argmax(prediction)
predicted_digit = labels[predicted_label]
# 在图像上绘制识别结果
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame, predicted_digit, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果图像
cv2.imshow('Digit Recognition', frame)
# 按下'q'键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和窗口
cap.release()
cv2.destroyAllWindows()
```
请注意,上述代码假设您已经训练了一个数字识别模型,并将其保存为`digit_recognition_model.h5`文件。您可以根据自己的需求进行模型训练和保存。