12-5HIstCamera.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: cap = cv2.VideoCapture(0, cv2.CAP_V4L)
005: cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
006: cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
007:
008: if not cap.isOpened():
009: print(‘Not Opend Video Camera’)
010: exit()
011:
012: while True:
013: ret, img = cap.read()
014: org = img.copy()
015: img = getResize(img)
016: base = aveImg(img)
017: rbRate = getCompHist(img, base)
018: setMessage(org, rbRate)
019: cv2.imshow(‘Histgram Camera’, org)
020: cv2.imshow(‘base Camera’, base)
021: if cv2.waitKey(10) > -1:
022: break
023: cap.release()
024: cv2.destroyAllWindows()
025:
026: def aveImg(img):
027: global frame
028: global buffer
029: global baseImg
030:
031: baseImg = np.zeros_like(img, dtype=’int32′)
032: buffer.append(img)
033: frame += 1
034: print(frame)
035: if frame > 100:
036: buffer.pop(0)
037: i = 0
038: for tempImg in buffer:
039: baseImg += tempImg # 過去のフレームを重ねて画素ごとの合計値をとる
040: i += 1
041: dst = np.uint8(baseImg // i) # 合計画素の平均をとることで静止画の映像を作る
042: return dst
043:
044: def getCompHist(Targetimg, baseImg):
045: Targetimg = cv2.cvtColor(Targetimg, cv2.COLOR_BGR2GRAY)
046: baseImg = cv2.cvtColor(baseImg, cv2.COLOR_BGR2GRAY)
047:
048: hist1 = cv2.calcHist(images=[Targetimg], channels=[0], mask=None, histSize=[256], ranges=[0, 256]) # (イメージ画,チャンネル,マスク,ビン数(全画素値の場合は256),画素値の範囲(0-255)
049: hist2 = cv2.calcHist(images=[baseImg], channels=[0], mask=None, histSize=[256], ranges=[0, 256]) # (イメージ画,チャンネル,マスク,ビン数(全画素値の場合は256),画素値の範囲(0-255)
050:
051: histResult = cv2.compareHist(H1=hist1, H2=hist2, method=cv2.HISTCMP_CORREL)
052: compRata = np.uint8(histResult * 100)
053:
054: return compRata
055:
056: def getResize(src):
057:
058: basePixSize = 640 # 縦横で大きい辺の変更したいサイズ
059: height = src.shape[0]
060: width = src.shape[1]
061:
062: largeSize = max(height, width) # 大きい方の辺のサイズ
063: resizeRate = basePixSize / largeSize # 変更比率を計算
064: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
065:
066: return dst
067:
068: def setMessage(img, compRate):
069: if compRate < 90 or compRate > 100:
070: color = (0, 0, 255)
071: else:
072: color = (0, 0, 0)
073: cv2.rectangle(img, (5, 5), (200, 50), color, -1)
074: cv2.putText(img=img, text=”R/B={0}%”.format(compRate), org=(18, 35), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
075: fontScale=1, color=(255, 255, 255), lineType=cv2.LINE_AA)
076:
077: if __name__ == ‘__main__’:
078: buffer = list()
079: frame = 0
080: __main()