# -*- coding: UTF-8 -*-
import datetime
from collections import deque
import cv2
import numpy as np
import math
import time
font = cv2.FONT_HERSHEY_PLAIN
camera = cv2.VideoCapture(0,cv2.CAP_DSHOW)
pre_frame = None
file_path = "D:/test"
while(1):
start = time.time()
# 读取视频流
ret, frame = camera.read()
timer = cv2.getTickCount()
# 转灰度图
gray_lwpCV = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if not ret:
break
end = time.time()
# 用高斯滤波进行模糊处理
gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (7, 7), 0)
# 如果没有背景图像就将当前帧当作背景图片
if pre_frame is None:
pre_frame = gray_lwpCV
else:
# absdiff把两幅图的差的绝对值输出到另一幅图上面来
img_delta = cv2.absdiff(pre_frame, gray_lwpCV)
# threshold阈值函数(原图像应该是灰度图,对像素值进行分类的阈值,当像素值高于(有时是小于)阈值时应该被赋予的新的像素值,阈值方法)
thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
# 膨胀图像
thresh = cv2.dilate(thresh, None, iterations=2)
# findContours检测物体轮廓(寻找轮廓的图像,轮廓的检索模式,轮廓的近似办法)
contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# 设置敏感度
# contourArea计算轮廓面积
if cv2.contourArea(c) < 100:
continue
else:
# 画出矩形框架,返回值x,y是矩阵左上点的坐标,w,h是矩阵的宽和高
(x, y, w, h) = cv2.boundingRect(c)
# rectangle(原图,(x,y)是矩阵的左上点坐标,(x+w,y+h)是矩阵的右下点坐标,(0,255,0)是画线对应的rgb颜色,2是所画的线的宽度)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 截图保存到指定目录下
cv2.putText(frame,
"now time: {}".format(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))),
(10, 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
print("出现目标物,请求核实")
image_name = (file_path + '/IMAGE/{0}{1}.jpg'.format('Image', datetime.datetime.now().strftime(
"%Y-%m-%d-%H-%M-%S"))) # 根据你的实际保存路径填写,Image+时间
print(image_name)
cv2.imwrite(image_name, frame)
break
pre_frame = gray_lwpCV
# 显示图像实时帧数
fps1 = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
cv2.putText(frame, "FPS : " + str(int(fps1)), (5, 450), font, 1, (0, 0, 255), 1)
# 显示图像
cv2.imshow("capture", frame)
# 进行阀值化来显示图片中像素强度值有显著变化的区域的画面
cv2.imshow("Frame Delta", img_delta)
if cv2.waitKey(1) & 0xFF == ord('q') :
break
camera.release()
cv2.destroyAllWindows()
报错1:
ValueError: not enough values to unpack (expected 3, got 2)
解决:
导致这个问题,实际是因为opencv版本不一致引起的
opencv3在调用findContours时需要三个参数
opencv4在调用findContours时只需要两个参数
查看本地opencv版本
import cv2
print(cv2.__version__)
调整本地版本或代码
pip3 install --upgrade opencv-python==4.x.x