opencv数字识别python代码
时间: 2023-04-20 08:03:22 浏览: 191
以下是一个使用 OpenCV 和 Python 进行数字识别的简单代码示例:
```
import cv2
import numpy as np
# Load the image
image = cv2.imread("numbers.jpg")
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Apply Otsu thresholding to binarize the image
thresholded = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours in the binary image
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Iterate through each contour and extract the rectangle bounding the digit
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
roi = thresholded[y:y + h, x:x + w]
roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
# Predict the digit using your machine learning model
prediction = model.predict(roi.reshape(1, 28 * 28))
prediction = np.argmax(prediction)
# Draw the digit on the original image
cv2.putText(image, str(prediction), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)
```
请注意,这仅是一个简单的示例,您可能需要调整代码以适应您的具体需求。
阅读全文