Python代码-相机异常画面自动检测和记录

设计思想:

对比相机前后两帧内容,并将前后两帧进行比较,如果差异较大,则进行图像保存,否则不记录,图像保存时随机命名。

使用须知:

部署者回看时需要按照时间查看保存图像,帧连成画达到录像效果

声明:

所有代码均非原创,乃拾人牙慧所得,具体链接遗忘,应该是站内大佬。

相机和代码要求:

使用两种常见相机:

IntelrealsenseD435i

奥比中光相机Astra s

在pycharm上进行部署,主要库有numpy、cv2、openni等,两种相机代码分别如下:

Intelrealsense相机:
import cv2
import time
import random
# 用于英特尔realsense相机,作变化画面记录
# 记录帧画面保存在同项目下img文件夹中
save_path = './img/'
camera = cv2.VideoCapture(0)

if (camera.isOpened()):
    print('Open')
else:
    print('摄像头未打开')
size = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print('size:' + repr(size))
fps = 20
pre_frame = None
while (1):
    start = time.time()
    ret, frame = camera.read()
    gray_lwpCV = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    if not ret:
        break
    end = time.time()
    seconds = end - start
    if seconds < 1.0 / fps:
        time.sleep(1.0 / fps - seconds)
    gray_lwpCV = cv2.resize(gray_lwpCV, (500, 500))
    gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
    if pre_frame is None:
        pre_frame = gray_lwpCV
    else:
        img_delta = cv2.absdiff(pre_frame, gray_lwpCV)
        thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for c in contours:
            if cv2.contourArea(c) < 100:
                continue
            else:
                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("出现目标物,请求核实")
                cv2.imwrite(save_path+str(random.random())+'.jpg', frame)
                break
        pre_frame = gray_lwpCV
        cv2.imshow("capture", frame)
        cv2.imshow("Frame Delta", img_delta)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
camera.release()
cv2.destroyAllWindows()
Astra s相机:
from openni import openni2
import numpy as np
import cv2
import time
import random
#用于奥比中光摄像机Astra s,作画面改变记录

if __name__ == "__main__":
    openni2.initialize()
    dev = openni2.Device.open_any()
    print("Astra s 色相头已开启")
    color_stream = dev.create_color_stream()
    color_stream.start()
    cv2.namedWindow('color')
    capture_flag = 0

    save_path = './img/'

    count = 1
    pre_frame = None
    while True:
        cframe = color_stream.read_frame()
        cframe_data = np.array(cframe.get_buffer_as_triplet()).reshape([480, 640, 3])
        R = cframe_data[:, :, 0]
        G = cframe_data[:, :, 1]
        B = cframe_data[:, :, 2]
        cframe_data = np.transpose(np.array([B, G, R]), [1, 2, 0])
        # print(cframe_data.shape)
        cv2.imshow('color', cframe_data)

        start = time.time()
        #image_data = np.array(frame,np.uint8)
        gray_lwpCV = cv2.cvtColor(cframe_data, cv2.COLOR_BGR2GRAY)
        gray_lwpCV = cv2.resize(gray_lwpCV, (500, 500))
        gray_lwpCV = cv2.GaussianBlur(gray_lwpCV, (21, 21), 0)
        if pre_frame is None:
            pre_frame = gray_lwpCV
        else:
            img_delta = cv2.absdiff(pre_frame, gray_lwpCV)
            thresh = cv2.threshold(img_delta, 25, 255, cv2.THRESH_BINARY)[1]
            thresh = cv2.dilate(thresh, None, iterations=2)
            contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            for c in contours:
                if cv2.contourArea(c) < 100:
                    continue
                else:
                    cv2.putText(cframe_data.copy(), "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("出现目标物,请求核实")

                    cv2.imwrite(save_path + str(random.random()) + '.jpg', cframe_data)
                    break
            pre_frame = gray_lwpCV
            cv2.imshow("capture", cframe_data)
            cv2.imshow("Frame Delta", img_delta)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    color_stream.stop()
    dev.close()

你可能感兴趣的:(python,opencv,目标检测,计算机视觉)