opencv摄像头识别手写数字的代码
时间: 2023-06-07 12:12:10 浏览: 105
Android开发APP实现实时识别手写数字+手机使用tensorflow训练+opencv实时图像识别+源码+使用文档说明
5星 · 资源好评率100%
以下是使用Opencv进行手写数字识别的代码示例:
```
import cv2
import numpy as np
def get_contour_precedence(contour, cols):
tolerance_factor = 10
origin = cv2.boundingRect(contour)
return ((origin[1]//tolerance_factor)*tolerance_factor)*cols + origin[0]
def main():
# Load the model
net = cv2.dnn.readNet("model.pb")
classes = []
with open("model.txt", "r") as f:
classes = [line.strip() for line in f.readlines()]
# Capture from the default camera
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
# Convert the captured frame into grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Apply adaptive thresholding to segment the foreground from the background
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 9, 2)
# Find contours in the binary image
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Sort the contours in the order of y-coordinate
contours.sort(key=lambda x:get_contour_precedence(x, frame.shape[1]))
for contour in contours:
# Get the bounding box for the contour
x, y, w, h = cv2.boundingRect(contour)
# Extract the digit from the binary image
digit_roi = thresh[y:y+h, x:x+w]
# Resize the digit image to (28, 28)
digit_roi = cv2.resize(digit_roi, (28, 28))
# Expand the image to (32, 32) for consistency with the training data
digit_roi = cv2.copyMakeBorder(digit_roi, 2, 2, 2, 2, cv2.BORDER_CONSTANT, value=0)
# Normalize the pixel values to the range (0, 1)
digit_roi = digit_roi.astype("float32") / 255.0
# Add an extra dimension to the image to make it compatible with the input shape of the model (1, 32, 32, 1)
digit_roi = np.expand_dims(digit_roi, axis=-1)
digit_roi = np.expand_dims(digit_roi, axis=0)
# Feed the image to the model and get the predicted class label
net.setInput(digit_roi)
preds = net.forward()
class_idx = np.argmax(preds)
# Convert the class label to the corresponding digit
digit = classes[class_idx]
# Draw the digit and the bounding box on the original frame
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame, digit, (x+int(w/4), y+int(h/2)), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)
# Show the output
cv2.imshow("Handwritten Digit Recognition", frame)
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
```
这段代码使用Opencv实现了从摄像头捕获图像,然后使用预训练好的模型对手写数字进行识别,并在屏幕上展示预测结果。在使用时,请确保正确设置模型的路径和模型的输入输出形状。
阅读全文