Created
February 1, 2016 15:40
-
-
Save TonyMooori/25490470c56f5d51ff90 to your computer and use it in GitHub Desktop.
緑色の物体の座標を検出するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import numpy as np | |
import cv2 | |
import time | |
cap = cv2.VideoCapture(0) | |
f = open("output.csv","w") | |
f.write("t,x,y\n") | |
start = time.time() | |
while(True): | |
# フレームをキャプチャする | |
ret, frame = cap.read() | |
# hsv色空間に変換 | |
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) | |
# 0 <= h <= 179 (色相) OpenCVではmax=179なのでR:0(180),G:60,B:120となる | |
# 0 <= s <= 255 (彩度) 黒や白の値が抽出されるときはこの閾値を大きくする | |
# 0 <= v <= 255 (明度) これが大きいと明るく,小さいと暗い | |
# ここでは緑色を抽出するので60±20を閾値とした | |
low_color = np.array([40, 75, 75]) | |
upper_color = np.array([80, 255, 255]) | |
# 色を抽出する | |
ex_img = cv2.inRange(hsv,low_color,upper_color) | |
# 縦,横方向の和の中で最も大きいインデックスを抽出 | |
x = np.argmax(np.sum(ex_img,axis=0)) | |
y = np.argmax(np.sum(ex_img,axis=1)) | |
# 時間と座標の保存 | |
t = time.time() - start | |
f.write(str(t)+","+str(x)+","+str(y)+"\n") | |
print(str(t)+","+str(x)+","+str(y)+"\n") | |
# 抽出した座標に丸を描く | |
cv2.circle(frame,(x,y),10,(0,255,0)) | |
# 画面に表示する | |
cv2.imshow('frame',frame) | |
if t > 120: | |
break | |
key = cv2.waitKey(1) & 0xFF | |
# qが押された場合は終了する | |
if key == ord('q'): | |
break | |
# 後始末 | |
cap.release() | |
cv2.destroyAllWindows() | |
f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment