How to make a surveillance camera (Security Camera) with Opencv and Python

0. First

If you want to see how the things you make this time work, please see here (youtube video).

1. Write the process

security_cam.py


import cv2
from datetime import datetime
import requests
import time

token = 'Your Token'

cap = cv2.VideoCapture(0)
lastframe = None

def send_msg():
    url = 'https://notify-api.line.me/api/notify'
    headers = {'Authorization':'Bearer '+token}
    data = {"message":"Someone in your room."}
    image = '/home/igor-bond/image.jpg'
    file = {'imageFile': open(image, 'rb')}
    r = requests.post(url, headers=headers, params=data, files=file,)
    
while cap.isOpened():
    ret,frame = cap.read()
    if ret == True:
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

        if lastframe is None:
            lastframe = gray.astype("float")
        
        cv2.accumulateWeighted(gray,lastframe,0.6)
        frame_diff = cv2.absdiff(gray,cv2.convertScaleAbs(lastframe))
        thresh = cv2.threshold(frame_diff,3,255,cv2.THRESH_BINARY)[1]
        contours,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

        for c in contours:
            if cv2.contourArea(c) > 30:
                time.sleep(0.2)
                now = datetime.now()
                img = cv2.resize(frame,(int(frame.shape[1]*0.5),int(frame.shape[0]*0.5)))
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(img,f'{now}',(100,350),font,1,(0,0,255),4,cv2.LINE_AA)
                cv2.imwrite('/home/igor-bond/image.jpg',img)
                send_msg()
                lastframe = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY).astype("float")
                break

        cv2.imshow('frame',frame)  
           
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

cv2.destroyAllWindows()
cap.release()

The first function is the one that sends an image to the line, which I've introduced before, so I'll omit it here. It is also introduced in here (youtube video). Then, this time, the difference between the frames is calculated, and if the pixel value is 3 or more, it is set to 255, and the contour is calculated there. If there is a contour that exceeds a certain area, it is considered to have moved. This is to prevent even very small changes from being detected. Then, add the time to the lower right so that it looks like a surveillance camera and save it as an image. The reason why I didn't change the name of the image is that if I change it, a lot of images will be accumulated, and this time I will activate the function to send to the line immediately after saving, so there is no problem even if I do this. Finally, repeat this with the frame at that time as the last one.

Finally

How to make this surveillance camera is also explained in Youtube, so please have a look if you like it. If you have any questions or advice, please comment.

Recommended Posts

How to make a surveillance camera (Security Camera) with Opencv and Python
[Python] How to make a class iterable
Fractal to make and play with Python
Make a simple OMR (mark sheet reader) with Python and OpenCV
I tried to make a periodical process with Selenium and Python
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
How to read a CSV file with Python 2/3
How to make a dictionary with a hierarchical structure.
I want to make a game with Python
How to crop an image with Python + OpenCV
Try to make a "cryptanalysis" cipher with Python
Try to make a dihedral group with Python
[Python] How to handle Japanese characters with openCV
How to upload a file to Cloud Storage using Python [Make a fixed point camera with Raspberry PI # 1]
How to make Python 3.x and 2.x coexist on Mac (I also included opencv as a bonus)
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
How to convert / restore a string with [] in python
[Python] How to draw a line graph with Matplotlib
Try to make a command standby tool with python
Explain in detail how to make sounds with python
Camera capture with Python + OpenCV
How to make a shooting game with toio (Part 1)
Let's make a simple game with Python 3 and iPhone
Make a function to describe Japanese fonts with OpenCV
How to make a Python package using VS Code
Make a fortune with Python
WEB scraping with python and try to make a word cloud from reviews
How to loop and play gif video with openCV
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
How to generate a QR code and barcode in Python and read it normally or in real time with OpenCV
I made a program to convert images into ASCII art with Python and OpenCV
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
How to make a Cisco Webex Teams BOT with Flask
How to install NPI + send a message to line with python
How to convert an array to a dictionary with Python [Application]
Associate Python Enum with a function and make it Callable
[Python] How to play with class variables with decorator and metaclass
Experiment to make a self-catering PDF for Kindle with Python
How to make a Python package (written for an intern)
How to make a simple Flappy Bird game with pygame
Try to bring up a subwindow with PyQt5 and Python
How to do Bulk Update with PyMySQL and notes [Python]
How to build a python2.7 series development environment with Vagrant
How to write a metaclass that supports both python2 and python3
Convert video to black and white with ffmpeg + python + opencv
I tried to make GUI tic-tac-toe with Python and Tkinter
Shoot time-lapse from a PC camera using Python and OpenCV
How to log in to AtCoder with Python and submit automatically
Shining life with Python and OpenCV
How to make a Japanese-English translation
How to write a Python class
Python: How to use async with
Let's make a GUI with python.
How to make a slack bot
How to make a crawler --Advanced
How to make a recursive function
How to get started with Python
Make a recommender system with python
How to make a deadman's switch