OpenCV处理摄像头实时流时按指定按键保存imgCanny窗口图像的实现方法问询
OpenCV摄像头流按键保存Canny画面修改方案
必改前置问题
先解决原有代码的运行错误:
- 删掉开头的
cv2.waitKey(0),这行会阻塞程序初始化流程 - 补充缺失的导入语句和变量定义,在
cap = cv2.VideoCapture(1)之后添加以下代码:
import numpy as np import cv2 frameWidth = 640 frameHeight = 480 font = cv2.FONT_HERSHEY_SIMPLEX save_cnt = 0 # 保存计数,避免文件被覆盖
核心功能修改
在主循环的按键判断逻辑里,新增指定按键触发保存的逻辑,示例用s键作为保存触发键,你可以自行替换为其他按键。
找到原来的按键判断部分:
key = cv2.waitKey(100) if key == 27: #kills with Esc break
修改为:
key = cv2.waitKey(100) if key == 27: # 按ESC退出程序 break if key == ord('s'): # 按s键保存Canny窗口画面 save_path = f"canny_capture_{save_cnt}.png" cv2.imwrite(save_path, imgCanny) print(f"画面已保存至:{save_path}") save_cnt += 1
逻辑说明
cv2.imwrite可以直接把当前帧的imgCanny对象写入本地,和cv2.imshow展示的内容完全一致- 保存的图片默认存放在你运行代码的同级文件夹下,文件名带递增序号,不会覆盖之前的保存结果
- 如果要更换触发按键,只需要把
ord('s')里的s换成你想要的按键字符即可,比如ord('c')就是按C键保存
完整修改后可运行代码
import cv2 import numpy as np cap = cv2.VideoCapture(1) frameWidth = 640 frameHeight = 480 font = cv2.FONT_HERSHEY_SIMPLEX save_cnt = 0 cap.set(3, frameWidth) cap.set(4, frameHeight) def empty(a): pass cv2.namedWindow("Parameters") cv2.resizeWindow("Parameters", 640, 240) cv2.createTrackbar("Threshold1", "Parameters", 150, 500, empty) cv2.createTrackbar("Threshold2", "Parameters", 255, 500, empty) def getContours(img, imgContour): contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) for cnt in contours: area = cv2.contourArea(cnt) approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True) n = approx.ravel() i = 0 for j in n: if (i % 2 == 0): x = n[i] y = n[i + 1] string = str(int(x / 3.5)) + " " + str(int(y / 3.5)) print(string) if (i == 0): cv2.putText(imgContour, "", (x, y), font, 0.5, (255, 0, 0)) else: cv2.putText(imgContour, string, (x, y), font, 0.5, (0, 255, 0)) i = i + 1 if area > 3000: cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 1) peri = cv2.arcLength(cnt, True) while True: success, img = cap.read() imgContour = img.copy() imgBlur = cv2.GaussianBlur(img, (31, 31), 1) imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY) threshold1 = cv2.getTrackbarPos("Threshold1", "Parameters") threshold2 = cv2.getTrackbarPos("Threshold2", "Parameters") imgCanny = cv2.Canny(imgGray, threshold1, threshold2) kernel = np.ones((5, 5)) imgDil = cv2.dilate(imgCanny, kernel, iterations=1) getContours(imgDil, imgContour) cv2.imshow("Canny", imgCanny) cv2.imshow("Dilated", imgContour) cv2.imshow("Test", imgDil) key = cv2.waitKey(100) if key == 27: break if key == ord('s'): save_path = f"canny_capture_{save_cnt}.png" cv2.imwrite(save_path, imgCanny) print(f"画面已保存至:{save_path}") save_cnt += 1 cap.release() cv2.destroyAllWindows()
内容的提问来源于stack exchange,提问作者Oliver Taylor
相关产品推荐
相关产品推荐

