Interface編集部
12-1CameraInCarWebStream.py
000: import cv2
001: import numpy as np
002: import bottle
003: import time
004:
005: web = bottle.Bottle()
006:
007: frameCount = 0
008: thresRate = 150
009: speedList = np.array([])
010: aveSpeed = 0
011:
012: @web.route(‘/’)
013: def main():
014: return bottle.static_file(‘index.html’, root=’./’)
015:
016: @web.route(‘/video_recv’)
017: def video_recv():
018: bottle.response.content_type = ‘multipart/x-mixed-replace;boundary=frame’
019: return __main()
020:
021: def __main():
022: cap = cv2.VideoCapture(“MVI_1186_Trim.mp4”)
023:
024: if not cap.isOpened(): # ビデオキャプチャー可能か判断
025: print(“Not Opened Video Camera”)
026: exit()
027:
028: while True:
029: ret, img = cap.read()
030: if not ret: # キャプチャー画像取得に失敗したら終了
031: print(“Video Capture Err”)
032: break
033:
034: img = setSpeedMovie(img)
035:
036: # ここで処理を実行する
037: result, jpgImg = cv2.imencode(‘.jpg’, img=img, params=[int(cv2.IMWRITE_JPEG_QUALITY), 80]) # 0 – 100
038: yield b’–frame\r\n’ + b’Content-Type: image/jpeg\r\n\r\n’ + bytearray(jpgImg) + b’\r\n\r\n’
039: time.sleep(1 / 60)
040:
041: #cv2.imshow(“Speed”, img)
042: if cv2.waitKeyEx(10) > -1:
043: break
044:
045: cv2.destroyAllWindows()
046:
047: def setSpeedMovie(img):
048: global frameCount
049: global aveSpeed
050:
051: height = img.shape[0]
052: width = img.shape[1]
053: y = int(height * 0.8)
054: x = int(width * 0.5)
055: h = y + 5
056: w = x + int(width * 0.3)
057: monitor = img[y: h, x: w]
058: monitor = cv2.cvtColor(monitor, cv2.COLOR_BGR2GRAY)
059: ret, monitor = cv2.threshold(monitor, thresRate, 255, cv2.THRESH_BINARY)
060:
061: avePixelNum = np.average(monitor) # 全画素の平均値
062: if avePixelNum > 10: # 白線が見つかった場青
063: frameCount += 1
064: else:
065: print(frameCount)
066: if frameCount > 0:
067: aveSpeed = getSpeed(frameCount)
068: frameCount = 0
069:
070: img = getResize(img)
071: color = (255, 255, 255)
072: cv2.putText(img, “Speed {0}Km/h”.format(aveSpeed), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 1, cv2.LINE_AA)
073:
074: return img
075:
076: def getSpeed(num):
077: global speedList
078: whiteLine = 8 # 白線の長さは8m
079: oneFrameSec = 1 / 30
080: whiteLinePassingSec = num * oneFrameSec # 白線を何秒で通過したか
081: carSpeed = whiteLine / 1000 / whiteLinePassingSec * 60 * 60
082:
083: if carSpeed < 150:
084: speedList = np.append(speedList, carSpeed)
085:
086: if speedList.size > 10:
087: speedList = np.delete(speedList, 0)
088:
089: print(‘Speed = {0} Count = {1}’.format(np.average(speedList), speedList.size))
090:
091: return int(np.average(speedList))
092:
093: def getResize(img):
094: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
095: height = img.shape[0]
096: width = img.shape[1]
097:
098: largeSize = max(height, width) # 大きい方の辺のサイズ
099: resizeRate = basePixSize / largeSize # 変更比率を計算
100: img = cv2.resize(img, (int(width * resizeRate), int(height * resizeRate)))
101:
102: return img
103:
104: if __name__ == ‘__main__’:
105: print(cv2.__version__)
106: web.run(host=’0.0.0.0′, port=8080)