概述
# -*- coding: utf-8 -*-
import cv2
import csv
import statistics as sts
import numpy as np
from PIL import Image
#设计一个类,进行异常值检测
class Detect:
def __init__(self):
self.path_read = ''
self.path_write = ''
self.filename = ''
self.dynamic_dataset = []
self.dynamic_volume = 1000
self.save_style = 'Orig'#'New'
self.threshold = 0
self.safe = 'y'
self.video_type = 'avi'
self.process_type = 'KNN'
def setup(self,path_read,filename,path_write,video_type='avi',process_type='KNN',save_style='Orig',dynamic_volume=1000):
self.path_read = path_read
self.path_write = path_write
self.filename = filename
self.video_type = video_type
self.process_type = process_type
self.save_style = save_style
self.dynamic_volume = dynamic_volume
def outlier(self,observ_data):
if len(self.dynamic_dataset) > 20:
Upper = max(sts.quantile(self.dynamic_dataset, 0.9),0.0)
Lower = max(sts.quantile(self.dynamic_dataset, 0.1),0.0)
Index1 = []
for data in self.dynamic_dataset:
if data <= Upper and data >= Lower:
Index1.append(0)
else:
Index1.append(1)
# 数据集中的异常值检测——拉依达法则
DATA = []
Count = 0
for ind in Index1:
if ind == 0:
DATA.append(self.dynamic_dataset[Count])
Count += 1
MEAN_ALL = np.mean(DATA)
Resid = []
Resid_Square = []
N = 0
N1 = 0
for data in self.dynamic_dataset:
Resid.append(np.abs(data - MEAN_ALL))
if Index1[N] == 0:
Resid_Square.append((data - MEAN_ALL) * (data - MEAN_ALL))
N1 += 1
N += 1
SUM = np.sum(Resid_Square)
S = np.sqrt(SUM / (N1 - 1))
##注意,这是本程序中,唯一在程序内部进行调整的参数,可以使用3*S,S/4
if np.abs(observ_data-MEAN_ALL) > S/2 :
#print(3 * S, observ_data, '---------------------')
self.safe = 'n'
else:
self.safe = 'y'
#判定是否将数据添加进来
Length_Dataset = len(self.dynamic_dataset)
if Length_Dataset < self.dynamic_volume:
self.dynamic_dataset.append(observ_data)
else:
self.dynamic_dataset.append(observ_data)
del self.dynamic_dataset[0]
else:
self.dynamic_dataset.append(observ_data)
def MatrixToImage(self,data):
data = data
new_im = Image.fromarray(data.astype(np.uint8))
return new_im
def video_process(self):
Filename_Read = self.path_read + '\' + self.filename + '.' + self.video_type
cap = cv2.VideoCapture(Filename_Read)
# 创建一个5*5的椭圆核
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
# 创建BackgroundSubtractorMOG2
if self.process_type == 'KNN':
fgbg = cv2.createBackgroundSubtractorKNN()
else:
fgbg = cv2.createBackgroundSubtractorMOG2()
# Define the codec and create VideoWriter object
Filename_Write = self.path_write + '\' + self.filename + '.avi'
print(Filename_Write)
fps = cap.get(cv2.CAP_PROP_FPS)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter(Filename_Write, cv2.VideoWriter_fourcc('I','4','2','0'), fps, size)
Filename_Write_csv = self.path_write + '\' + self.filename + '.csv'
zh_count_write = csv.writer(open(Filename_Write_csv, 'w', newline=''), dialect='excel')
Process_Order = 0
ZH_Count = 1
#处理视频
while (1):
ret, frame = cap.read(0)
if ret == True:
img_new = frame
fgmask = fgbg.apply(img_new)
# 形态学开运算去噪点
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# 平滑方式去除噪声,
blured1 = cv2.bilateralFilter(fgmask, 10, 5, 5)
blured2 = cv2.GaussianBlur(fgmask, (3, 3), 0)
blured3 = cv2.blur(fgmask, (5, 5))
blured4 = cv2.medianBlur(fgmask, 5)
fgmask = blured2
# 闭运算去噪点
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)
# 寻找视频中的轮廓
im, contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Count_Contour = 0
Whether_Write = False
for c in contours:
# 计算各轮廓的周长
perimeter = cv2.arcLength(c, True)
Count_Contour += 1
self.outlier(perimeter)
if self.safe == 'n':
# 找到一个直矩形(不会旋转)
x, y, w, h = cv2.boundingRect(c)
# 画出这个矩形
# cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),-1)#作出填充的矩形
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 1) # 做矩形框
Whether_Write = True
#截取图片保存
if Whether_Write == True:
Save_Filename = self.path_write + '\截图\' + self.filename + '\' + str(ZH_Count) + '.jpg'
Img = self.MatrixToImage(frame)
Img.save(Save_Filename)
zh_count_write.writerow([ZH_Count])
print(Count_Contour)
if self.save_style == 'Orig':
out.write(frame)
else:
out.write(fgmask)
# 保存截图
cv2.imshow('frame', frame)
cv2.imshow('fgmask', fgmask)
Process_Order += 1
else:
break
ZH_Count += 1
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
#-------------------------------------类的调用-----------------------------
ANS = Detect()
ANS.setup(path_read='/Users/vicky/Desktop/附件3-检测前景视频/campus',path_write='/Users/vicky/Desktop/附件3-检测前景视频/campus',filename='Campus',video_type='avi',process_type='MOG2',save_style='Orig',
dynamic_volume=10000)
ANS.video_process()
最后
以上就是漂亮百褶裙为你收集整理的Answer4.py-20170920的全部内容,希望文章能够帮你解决Answer4.py-20170920所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复