import cv2
import numpy as np# 定义回调函数
def callback(x):pass# 打开摄像头
cap = cv2.VideoCapture(0)# 创建窗口和控件
cv2.namedWindow('image')
cv2.createTrackbar('threshold', 'image', 0, 255, callback)# 初始化参数
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (0, 0, 1, 1)while True:# 获取当前帧ret, frame = cap.read()# 转换为灰度图像gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# 获取阈值threshold = cv2.getTrackbarPos('threshold', 'image')# 进行前景和背景的分割mask = np.zeros(gray.shape, np.uint8)mask[gray >= threshold] = 1cv2.imshow('mask', mask)# 对分割后的图像进行分水岭处理markers = cv2.watershed(frame, mask)# 绘制分割结果frame[markers == -1] = [255, 0, 0]# 显示结果cv2.imshow('image', frame)# 按下ESC键退出程序if cv2.waitKey(1) == 27:break# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()
cv2.VideoCapture()
函数打开摄像头,然后创建一个新窗口并添加一个用于调整阈值的滑动条。在每一帧图像中,我们通过cv2.cvtColor()
将其转换为灰度图像,然后根据阈值获取前景和背景的分割结果。接下来,我们将分割结果传递给cv2.watershed()
函数进行分水岭处理,然后将分水岭处理后的分割结果绘制到原图像中。最后,我们使用cv2.imshow()
显示结果,并在用户按下ESC键时退出程序。