我的目标是检测IP摄像机流中特定区域的运动。我已经写出了可行的代码,但是它基于我的个人理解。
import cv2
import numpy as np
import os
import time
import datetime
import urllib
import pynotify
stream=urllib.urlopen('http://user:pass@192.168.198.120/video.mjpg')
bytes=''
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
bytes+=stream.read(16384)
a = bytes.find('\xff\xd8')
b = bytes.find('\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
rows,cols,c = img.shape
mask = np.zeros(img.shape, dtype=np.uint8)
roi_corners = np.array([[(940,220),(1080,240), (1080,310), (940,290)]], dtype=np.int32)
channel_count = img.shape[2]
ignore_mask_color = (255,)*channel_count
cv2.fillPoly(mask, roi_corners, ignore_mask_color)
masked_image = cv2.bitwise_and(img, mask)
fgmask = fgbg.apply(masked_image)
iii = fgmask[220:310,940:1080]
hist,bins = np.histogram(iii.ravel(),256,[0,256])
black, white, cnt1, cnt2 = 0,0,0,0
for i in range(0,127):
black += hist[i]
cnt1+=1
bl = float(black / cnt1)
for i in range(128,256):
white += hist[i]
cnt2+=1
wh = float(white / cnt2)
finalResult = ((bl+1) / (wh+1))/10
if finalResult < 1.0:
pynotify.init("cv2alert")
notice = pynotify.Notification('Alert', 'Alert text')
try:
notice.show()
except gio.Error:
print "Error"
这段代码是有效的,但由于我对直方图的理解不太好,因此无法直接获取值,但通过一些“技巧”(例如左侧为黑色,右侧为白色),black/white
给出了我想要的结果。 我知道这并不完全正确,但它给出了ROI中没有元素时4-9的结果,当有人进入这个ROI时给出0.5-2.0的结果。
我的问题是: 是否有其他方法读取直方图并比较数据,或者其他方法? 阅读文档并没有帮助我。