常用的手机图像处理框架有:OpenCV、TensorFlow Lite、Core ML、Keras、PyTorch Mobile、Neural Network API(NAPI)等。
首先需要导入opencv-python 这个库,输入命令(从阿里云镜像云盘中下载)
pip install -U opencv-python -i https://mirrors.aliyun.com/pypi/simple
也可以从清华镜像云中下载,地址:Simple Index
import cv2
import numpy as np
# 读取图片
img = cv2.imread('number.jpg')
# 灰度处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化处理
ret, binary = cv2.threshold(gray, 0, 25, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
# 膨胀处理
kernel = cv2.getStructuringElement(cv2.MORPH_RECT(3, 3))
dilate = cv2.dilate(binary, kernel, iterations=2)
# 轮廓检测
contours, hierarchy = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APROX_SIMPLE)
# 循环每一个轮廓
for c in contours:
# 获取轮廓的外接矩形
x, y, w, h = cv2.boundingRect(c)
# 裁剪图片
roi = binary[y:y + h, x:x + w]
# 将图片缩放到28*28
roi = cv2.resize(roi, (28, 28))
# 将图片转换为一维数组
roi_ar = roi.reshape([1, 784])
# 加载模型
model = load_model('model.h5')
# 预测
result = model.predict(roi_ar)
# 获取预测结果
number = np.argmax(result)
# 绘制外接矩形
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 25), 2)
# 显示预测结果
cv2.putText(img, str(number), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 25), 2)
# 显示图片
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAlWindows()