从摄像头获取图像
从摄像头获取图像并转换为二值化图,其基本操作与读取图像类似,但需要使用OpenCV调用摄像头。
在mnist_predict目录下新建文件,命名为camera.py,使用摄像头拍摄图像,处理为二值化图并显示,在PyCharm中编写以下代码。
import cv2
def start():
# 使用摄像头
cap = cv2.VideoCapture(0)
while (True):
# 读取一帧的图像
ret, frame = cap.read()
# 灰度化
img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, img_threshold = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('img_threshold', img_threshold)
key = cv2.waitKey(30) & 0xff
if key == 27:
sys.exit(0)
# 释放摄像头
cap.release()
cv2.destroyAllWindows()
if name == 'main':
start()
start()函数可调用摄像头,捕捉并显示视频帧。