12-2CarCount.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: cap = cv2.VideoCapture(‘PXL_20201011_005931739.mp4’)
005:
006: while True:
007: ret, img = cap.read()
008: if not ret: # キャプチャー画像取得に失敗したら終了
009: print(“Video Capture Err”)
010: break
011:
012: # ここで処理を実行する
013: img = getResize(img)
014: # –ここに解析処理を記述 戻り値を imgにする
015: img = getArea(img)
016:
017: cv2.imshow(“Final result”, img) # 画面表示
018: if cv2.waitKey(10) > -1:
019: break
020:
021: cap.release()
022: cv2.destroyAllWindows()
023:
024: def getArea(img):
025: # 判定サイズ
026: w = 310
027: h = 5
028: # 内側
029: x1 = 570
030: y1 = 630
031: x2 = x1 + w
032: y2 = y1 + h
033:
034: # 外側
035: x3 = 930
036: y3 = 630
037: x4 = x3 + w
038: y4 = y3 + h
039:
040: area1 = img[y1:y2, x1:x2] # 内側車線
041: area2 = img[y3:y4, x3:x4] # 外側車線
042: area1 = getBackgroundSubMog(img, area1, 1) # 1はIN
043: area2 = getBackgroundSubMog(img, area2, 2) # 2はOUT
044: img[y1:y2, x1:x2] = cv2.cvtColor(area1, cv2.COLOR_GRAY2BGR)
045: img[y3:y4, x3:x4] = cv2.cvtColor(area2, cv2.COLOR_GRAY2BGR)
046:
047: return img
048:
049: def getBackgroundSubMog(img, area, loadLine):
050: global inside
051: global outside
052: global outsideZeroCount
053: global insideZeroCount
054:
055: monitor = fgbg.apply(area)
056: avePixelNum = np.average(monitor) # 全画素の平均値
057: print(“Averege = {0}”.format(avePixelNum))
058: # outside(外側判定)
059: if loadLine == 2:
060: if avePixelNum < 5: #平均値が5/255以下の場合はノイズとみなす 061: outsideZeroCount += 1 # 未通過フレームのカウント 062: else: 063: if outsideZeroCount > 5: # 未通過フレームが5枚以上続いて変化があれば通過したとみなす
064: outside += 1
065: outsideZeroCount = 0
066: #inside(内側判定)
067: if loadLine == 1:
068: if avePixelNum < 5: #平均値が5/255以下の場合はノイズとみなす 069: insideZeroCount += 1 # 未通過フレームのカウント 070: else: 071: if insideZeroCount > 5: # 未通過フレームが5枚以上続いて変化があれば通過したとみなす
072: inside += 1
073: insideZeroCount = 0
074:
075: cv2.putText(img=img, text=”{0}”.format(outside), org=(1100, 680), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
076: fontScale=1.5, color=(255, 255, 255), lineType=cv2.LINE_AA)
077: cv2.putText(img=img, text=”{0}”.format(inside), org=(700, 680), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
078: fontScale=1.5, color=(255, 255, 255), lineType=cv2.LINE_AA)
079:
080: return monitor
081:
082: def getResize(src):
083: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
084: height = src.shape[0]
085: width = src.shape[1]
086:
087: largeSize = max(height, width) # 大きい方の辺のサイズ
088: resizeRate = basePixSize / largeSize # 変更比率を計算
089:
090: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)), interpolation=None)
091:
092: return dst
093:
094: if __name__ == ‘__main__’:
095: outside = 0 # 外側の通過カウント
096: inside = 0 # 内側の通過カウント
097: outsideZeroCount = 0
098: insideZeroCount = 0
099: # 背景差分のフィルター作成
100: fgbg = cv2.bgsegm.createBackgroundSubtractorMOG(history=120)
101: __main()