import numpy as np
import cv2
class BackGroundSubtractor:
# When constructing background subtractor, we
# take in two arguments:
# 1) alpha: The background learning factor, its value should
# be between 0 and 1. The higher the value, the more quickly
# your program learns the changes in the background. Therefore,
# for a static background use a lower value, like 0.001. But if
# your background has moving trees and stuff, use a higher value,
# maybe start with 0.01.
# 2) firstFrame: This is the first frame from the video/webcam.
def __init__(self,alpha,firstFrame):
self.alpha = alpha
self.backGroundModel = firstFrame
def getForeground(self,frame):
# apply the background averaging formula:
# NEW_BACKGROUND = CURRENT_FRAME * ALPHA + OLD_BACKGROUND * (1 - APLHA)
self.backGroundModel = frame * self.alpha + self.backGroundModel * (1 - self.alpha)
# after the previous operation, the dtype of
# self.backGroundModel will be changed to a float type
# therefore we do not pass it to cv2.absdiff directly,
# instead we acquire a copy of it in the uint8 dtype
# and pass that to absdiff.
return cv2.absdiff(self.backGroundModel.astype(np.uint8),frame)
cam = cv2.VideoCapture('C:/Users/heyuc/Desktop/111/input1.avi')
c=1
# Just a simple function to perform
# some filtering before any further processing.
#def denoise(frame):
# frame = cv2.medianBlur(frame,5)
# frame = cv2.GaussianBlur(frame,(5,5),0)
# return frame
# Get the width and height of frame
width = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH) + 0.5)
height = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT) + 0.5)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Be sure to use the lower case
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (width, height))
ret,frame = cam.read()
if ret is True:
backSubtractor = BackGroundSubtractor(0.93,frame)
run = True
else:
run = False
while(run):
# Read a frame from the camera
ret,frame = cam.read()
# If the frame was properly read.
if ret is True:
# Show the filtered image
cv2.imshow('input',frame)
# get the foreground
foreGround = backSubtractor.getForeground(frame)
# Apply thresholding on the background and display the resulting mask
ret, mask = cv2.threshold(foreGround, 1.5, 255, cv2.THRESH_BINARY)
# Note: The mask is displayed as a RGB image, you can
# display a grayscale image by converting 'foreGround' to
# a grayscale before applying the threshold.
cv2.imshow('mask',mask)
out.write(mask)
cv2.imwrite('image/'+str(c)+'.jpg',mask)
c=c+1
key = cv2.waitKey(1) & 0xFF
else:
break
if key == 27:
break
cam.release()
cv2.destroyAllWindows()
评论0