用opencv实现数字的识别的代码
时间: 2023-06-10 07:02:37 浏览: 108
以下是使用opencv实现数字识别的Python代码示例:
```python
import cv2
import numpy as np
# 加载训练好的MNIST数据集模型
model = cv2.ml.KNearest_create()
model.train(trainData, cv2.ml.ROW_SAMPLE, trainLabels)
# 获取输入图像并进行预处理
image = cv2.imread('digit.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = np.ones((3, 3), np.uint8)
dilated = cv2.dilate(thresh, kernel, iterations=1)
# 在输入图像中查找轮廓
contours, _ = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 提取每个数字的特征并进行分类
[x, y, w, h] = cv2.boundingRect(contour)
if h < 20:
continue
roi = dilated[y:y + h, x:x + w]
resized_roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
feature = resized_roi.reshape((1, 784)).astype(np.float32)
_, result, _, _ = model.findNearest(feature, k=1)
digit = int(result[0][0])
# 在输入图像中绘制数字及边界框
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, str(digit), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# 显示包含识别结果的输入图像
cv2.imshow("Result", image)
cv2.waitKey(0)
```
此代码利用OpenCV对数字图像进行预处理和提取特征,并使用机器学习模型对其进行分类以进行数字识别。
阅读全文