This is a simple security camera that records video frames when it detects motion.
1) capture a video frame with the webcam
2) convert the color image to a gray scale image (black and white)
3) apply an image processing filter (Gaussian blur, providing smoother image, reducing the sensor noise)
4) resize the image into a smaller one (for fast processing)
5) compare the image with the stored one (the previously captured image) -- subtract pixel values between two images and decide 1 or 0 depending on the magnitude of the difference (thresholding)
6) If the difference is big, save the captured frame as an image file
7) repeat it
import cv2
import datetime
import numpy as np
cap = cv2.VideoCapture(0)
FLAG_FIRST = 1
PAR_COMP_RATE = 0.05
DISP_STRING = 'Recording...'
ringname = 1
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
if FLAG_FIRST:
small_back = cv2.resize(gray, (0,0), fx=PAR_COMP_RATE, fy=PAR_COMP_RATE)
small_curr = cv2.resize(gray, (0,0), fx=PAR_COMP_RATE, fy=PAR_COMP_RATE)
FLAG_FIRST = 0
continue
small_back = small_curr
small_curr = cv2.resize(gray, (0,0), fx=PAR_COMP_RATE, fy=PAR_COMP_RATE)
diff = cv2.absdiff(small_curr, small_back)
thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,DISP_STRING,(50,50), font, 1,(0,0,255),2)
cv2.imshow("frame",frame)
if np.sum(thresh) > 10:
time = str(datetime.datetime.now())
time = time.replace(':','-')
print 'motion detected', time
cv2.imwrite('C:\\data\\' + str(ringname) + '.jpg',frame)
DISP_STRING = 'Recording...!'
else:
DISP_STRING = 'Detecting...'
if cv2.waitKey(100) & 0xFF == ord('q'):
break
if ringname > 10000:
ringname = 1
else:
ringname = ringname + 1
cap.release()
cv2.destroyAllWindows()
The python module cv2 is a collection of image processing and computer vision algorithms. It allows us to use the webcam of your computer.
ret, frame = cap.read()
The frame is a 640 x 480 x 3 array (by default). It is a color image array representing a 640 x 480 size picture. Each position in this array shows a color value of the image. To represent a color, we need a three values (ex: [100, 100, 100]). For instance, a "red" pixel can have [0, 0, 255] values.
For simplicity, we play with gray scale images. To convert a color image into a gray scale image, we use the opencv function,
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (21, 21), 0)
small_curr = cv2.resize(gray, (0,0), fx=PAR_COMP_RATE, fy=PAR_COMP_RATE)
diff = cv2.absdiff(small_curr, small_back)
thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]
if np.sum(thresh) > 10:
cv2.imwrite('C:\\data\\' + str(index) + '.jpg',frame)
DIY mini camera (hardware required, C programming language, 3D printing)