Skip to content

Instantly share code, notes, and snippets.

@smd877
Last active January 14, 2021 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smd877/d1189c31235364af038e55563f7297d8 to your computer and use it in GitHub Desktop.
Save smd877/d1189c31235364af038e55563f7297d8 to your computer and use it in GitHub Desktop.
OpenCVを使ってビデオキャプチャの画像が指定の画像と類似するか
import cv2
import numpy as np
# 環境で変わると思うので変数として持つ
DEVICE_ID = 0
# 高さ40幅120の切り取り画像の要素のうち一致している許容値
THRESHOLD = 4600
# 比較用画像を読み込み二値化しておく
hook_img = cv2.imread('hook.jpg', 0)
ret, thresh_hook_img = cv2.threshold(hook_img, 0, 255, cv2.THRESH_OTSU)
# キャプチャの読み込み(最初の方のframeは読み飛ばす)
cap = cv2.VideoCapture(DEVICE_ID)
for i in range(60):
ret,frame = cap.read()
# frameそのものを画像保存 デバッグ活用等
cv2.imwrite('temp.jpg', frame)
# frameから画像切り取り(高さ40幅120)
trim_img = frame[390 : 430, 120 : 240]
# 二値化させる
gray_trim_img = cv2.cvtColor(trim_img, cv2.COLOR_BGR2GRAY)
ret, thresh_trim_img = cv2.threshold(gray_trim_img, 0, 255, cv2.THRESH_OTSU)
# 切り取り画像の保存 デバッグ活用等
cv2.imwrite('trim.jpg', trim_img)
# 二値化した画像も念の為保存 デバッグ活用等
cv2.imwrite('thresh_trim.jpg', thresh_trim_img)
# 比較用画像とキャプチャした画像の全要素を比較し一致するものをカウント。
ret = np.count_nonzero(thresh_hook_img == thresh_trim_img)
if ret >= THRESHOLD:
print('Hatched !!!! ret is {}'.format(ret))
else:
print('Not Hatched. ret is {}'.format(ret))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment