12-2CarCountWebStream.py

import cv2
import numpy as np
import bottle
import time

web = bottle.Bottle()

@web.route(‘/’)
def main():
return bottle.static_file(‘index.html’, root=’./’)

@web.route(‘/video_recv’)
def video_recv():
bottle.response.content_type = ‘multipart/x-mixed-replace;boundary=frame’
return __main()

def __main():
cap = cv2.VideoCapture(‘../PXL_20201011_005931739.mp4’)

while True:
ret, img = cap.read()
if not ret: # キャプチャー画像取得に失敗したら終了
print(“Video Capture Err”)
break

# ここで処理を実行する
img = getResize(img)
# –ここに解析処理を記述 戻り値を imgにする
img = getArea(img)

result, jpgImg = cv2.imencode(‘.jpg’, img=img, params=[int(cv2.IMWRITE_JPEG_QUALITY), 80]) # 0 – 100
yield b’–frame\r\n’ + b’Content-Type: image/jpeg\r\n\r\n’ + bytearray(jpgImg) + b’\r\n\r\n’
time.sleep(1 / 60)

if cv2.waitKey(10) > -1:
break

cap.release()

def getArea(img):
# 判定サイズ
w = 310
h = 5
# 内側
x1 = 570
y1 = 630
x2 = x1 + w
y2 = y1 + h

# 外側
x3 = 930
y3 = 630
x4 = x3 + w
y4 = y3 + h

area1 = img[y1:y2, x1:x2] # 内側車線
area2 = img[y3:y4, x3:x4] # 外側車線
area1 = getBackgroundSubMog(img, area1, 1) # 1はIN
area2 = getBackgroundSubMog(img, area2, 2) # 2はOUT
img[y1:y2, x1:x2] = cv2.cvtColor(area1, cv2.COLOR_GRAY2BGR)
img[y3:y4, x3:x4] = cv2.cvtColor(area2, cv2.COLOR_GRAY2BGR)

return img

def getBackgroundSubMog(img, area, loadLine):
global inside
global outside
global outsideZeroCount
global insideZeroCount

monitor = fgbg.apply(area)
avePixelNum = np.average(monitor) # 全画素の平均値
print(“Averege = {0}”.format(avePixelNum))
# outside(外側判定)
if loadLine == 2:
if avePixelNum < 5: # 平均値が5/255以下の場合はノイズとみなす outsideZeroCount += 1 # 未通過フレームのカウント else: if outsideZeroCount > 5: # 未通過フレームが5枚以上続いて変化があれば通過したとみなす
outside += 1
outsideZeroCount = 0
# inside(内側判定)
if loadLine == 1:
if avePixelNum < 5: # 平均値が5/255以下の場合はノイズとみなす insideZeroCount += 1 # 未通過フレームのカウント else: if insideZeroCount > 5: # 未通過フレームが5枚以上続いて変化があれば通過したとみなす
inside += 1
insideZeroCount = 0

cv2.putText(img=img, text=”{0}”.format(outside), org=(1100, 680), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1.5, color=(255, 255, 255), lineType=cv2.LINE_AA)
cv2.putText(img=img, text=”{0}”.format(inside), org=(700, 680), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1.5, color=(255, 255, 255), lineType=cv2.LINE_AA)

return monitor

def getResize(src):
basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
height = src.shape[0]
width = src.shape[1]

largeSize = max(height, width) # 大きい方の辺のサイズ
resizeRate = basePixSize / largeSize # 変更比率を計算

dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)), interpolation=None)

return dst

if __name__ == ‘__main__’:
outside = 0 # 外側の通過カウント
inside = 0 # 内側の通過カウント
outsideZeroCount = 0
insideZeroCount = 0
# 背景差分のフィルター作成
fgbg = cv2.bgsegm.createBackgroundSubtractorMOG(history=120)
web.run(host=’0.0.0.0′, port=8080)