Interface編集部
12-5HIstCameraWebStream.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(0, cv2.CAP_V4L)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
if not cap.isOpened():
print(‘Not Opend Video Camera’)
exit()
while True:
ret, img = cap.read()
org = img.copy()
img = getResize(img)
base = aveImg(img)
rbRate = getCompHist(img, base)
setMessage(org, rbRate)
result, jpgImg = cv2.imencode(‘.jpg’, img=org, 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 aveImg(img):
global frame
global buffer
global baseImg
baseImg = np.zeros_like(img, dtype=’int32′)
buffer.append(img)
frame += 1
print(frame)
if frame > 100:
buffer.pop(0)
i = 0
for tempImg in buffer:
baseImg += tempImg # 過去のフレームを重ねて画素ごとの合計値をとる
i += 1
dst = np.uint8(baseImg // i) # 合計画素の平均をとることで静止画の映像を作る
return dst
def getCompHist(Targetimg, baseImg):
Targetimg = cv2.cvtColor(Targetimg, cv2.COLOR_BGR2GRAY)
baseImg = cv2.cvtColor(baseImg, cv2.COLOR_BGR2GRAY)
hist1 = cv2.calcHist(images=[Targetimg], channels=[0], mask=None, histSize=[256],
ranges=[0, 256]) # (イメージ画,チャンネル,マスク,ビン数(全画素値の場合は256),画素値の範囲(0-255)
hist2 = cv2.calcHist(images=[baseImg], channels=[0], mask=None, histSize=[256],
ranges=[0, 256]) # (イメージ画,チャンネル,マスク,ビン数(全画素値の場合は256),画素値の範囲(0-255)
histResult = cv2.compareHist(H1=hist1, H2=hist2, method=cv2.HISTCMP_CORREL)
compRata = np.uint8(histResult * 100)
return compRata
def getResize(src):
basePixSize = 640 # 縦横で大きい辺の変更したいサイズ
height = src.shape[0]
width = src.shape[1]
largeSize = max(height, width) # 大きい方の辺のサイズ
resizeRate = basePixSize / largeSize # 変更比率を計算
# shotSize = min(height, width) * resizeRate
dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
return dst
def setMessage(img, compRate):
if compRate < 90 or compRate > 100:
color = (0, 0, 255)
else:
color = (0, 0, 0)
cv2.rectangle(img, (5, 5), (200, 50), color, -1)
cv2.putText(img=img, text=”R/B={0}%”.format(compRate), org=(18, 35), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1, color=(255, 255, 255), lineType=cv2.LINE_AA)
if __name__ == ‘__main__’:
buffer = list()
frame = 0
web.run(host=’0.0.0.0′, port=8080)