Interface編集部
12-1CameraInCar.py
000: import cv2
001: import numpy as np
002:
003: frameCount = 0
004: thresRate = 150
005: speedList = np.array([])
006: aveSpeed = 0
007:
008: def setSpeedMovie(img):
009: global frameCount
010: global aveSpeed
011:
012: height = img.shape[0]
013: width = img.shape[1]
014: y = int(height * 0.8)
015: x = int(width * 0.5)
016: h = y + 5
017: w = x + int(width * 0.3)
018:
019: monitor = img[y: h, x: w]
020: cv2.imshow(“Monitor”, monitor)
021: monitor = cv2.cvtColor(monitor, cv2.COLOR_BGR2GRAY)
022: _, monitor = cv2.threshold(monitor, thresRate, 255, cv2.THRESH_BINARY)
023:
024: avePixelNum = np.average(monitor) # 全画素の平均値
025:
026: if avePixelNum > 10: # 白線が見つかった場合
027: frameCount += 1
028: else:
029: print(frameCount)
030: if frameCount > 0:
031: aveSpeed = getSpeed(frameCount)
032: frameCount = 0
033:
034: cv2.imshow(“Monitor”, monitor)
035: img = getResize(img)
036: color = (255, 255, 255)
037: cv2.putText(img, “Speed {0}Km/h”.format(aveSpeed), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 1, cv2.LINE_AA)
038:
039: return img
040:
041: def getSpeed(num):
042: global speedList
043: whiteLine = 8 # 白線の長さは8m
044: oneFrameSec = 1 / 30 # 映像のフレームレートが30
045: whiteLinePassingSec = num * oneFrameSec # 白線を何秒で通過したか
046: carSpeed = whiteLine / 1000 / whiteLinePassingSec * 60 * 60
047:
048: if carSpeed < 150:
049: speedList = np.append(speedList, carSpeed)
050:
051: if speedList.size > 10:
052: speedList = np.delete(speedList, 0)
053:
054: print(‘Speed = {0} Count = {1}’.format(np.average(speedList), speedList.size))
055:
056: return int(np.average(speedList))
057:
058: def getResize(img):
059: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
060: height = img.shape[0]
061: width = img.shape[1]
062:
063: largeSize = max(height, width) # 大きい方の辺のサイズ
064: resizeRate = basePixSize / largeSize # 変更比率を計算
065: img = cv2.resize(img, (int(width * resizeRate), int(height * resizeRate)))
066:
067: return img
068:
069:
070: if __name__ == ‘__main__’:
071:
072: cap = cv2.VideoCapture(“MVI_1186_Trim.mp4”)
073:
074: if not cap.isOpened(): # ビデオキャプチャー可能か判断
075: print(“Not Opened Video Camera”)
076: exit()
077:
078: while True:
079: ret, img = cap.read()
080: if not ret: # キャプチャー画像取得に失敗したら終了
081: print(“Video Capture Err”)
082: break
083:
084: img = setSpeedMovie(img)
085:
086: cv2.imshow(“Speed”, img)
087: if cv2.waitKeyEx(10) > -1:
088: break
089:
090: cv2.destroyAllWindows()