Skip to content

Instantly share code, notes, and snippets.

@lefirea
Created April 1, 2018 10:14
Show Gist options
  • Save lefirea/9d549a160be1e783bc4b4b0a8972b7a7 to your computer and use it in GitHub Desktop.
Save lefirea/9d549a160be1e783bc4b4b0a8972b7a7 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import time
cap=cv2.VideoCapture(1)
cap.set(cv2.CAP_PROP_FPS,30) #カメラのFPSを30に指定
cap.set(cv2.CAP_PROP_FRAME_WIDTH,360) #カメラ映像の横幅を360に指定
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,240) #カメラ映像の縦幅を240に指定
while(True):
if(cap.isOpened()==False): #カメラが起動できなかったら
print("camera error")
break;
ret,img=cap.read() #カメラ読み込み
img=cv2.resize(img,(360,240)) #画像のリサイズ
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #グレスケ変換
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) #HSV変換
retval,bw=cv2.threshold(gray,50,255,cv2.THRESH_BINARY | cv2.THRESH_OTSU) #2値化
src,contours,hierarchy=cv2.findContours(bw,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE) #輪郭を抽出
#左辺は3つの変数を用意する
#黄色の範囲(HSV)
low_color = np.array([20, 100, 100]) #黄色の範囲の下限
upper_color = np.array([45, 255, 255]) #黄色の範囲の上限
# 黄色以外にマスク
mask_color = cv2.inRange(hsv, low_color, upper_color) #黄色の範囲の点のみ残す。それ以外は全部黒に。(=マスク処理)
res_color = cv2.bitwise_and(img,img, mask= mask_color) #元画像とマスク画像をアンド合成
for i in range(0,len(contours)): #各輪郭に対する処理
start=time.time()
area=cv2.contourArea(contours[i]) #輪郭の領域を計算
#小さすぎたり、大きすぎる物は除外
if area<2e2 or 1e4<area: #2*10^2~1*10^4 までの大きさ(面積)の四角のみ
continue
if(len(contours[i]))>0: #外接矩形
rect=contours[i] #検出した矩形を一つ取り出す
x,y,w,h=cv2.boundingRect(rect) #矩形の座標とか辺の長さとかを取得
print("area=",area)
WhitePoint_count=0 #マスク画像の白点の個数
for i in range(x,x+w): #検出した四角のx範囲
for j in range(y,y+h): #検出した四角のy範囲
if(mask_color[j,i]!=0): #四角内の点の色が黒で無いなら(=点が白なら)
WhitePoint_count+=1; #カウントを増やす
print(WhitePoint_count)
if(WhitePoint_count>0 and WhitePoint_count<=250): #個数が0~500までなら(大きさフィルターを通過した缶以外の四角を除外する)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) #その矩形を合成
cv2.rectangle(res_color,(x,y),(x+w,y+h),(0,0,255),2) #その矩形を合成
end=time.time()
print('処理時間=',(end-start)*1000,"[ms]")
#各矩形の中心座標(対角線の中心)を計算
#tX=x+(w/2)
#tY=y+(h/2)
#cv2.circle(img,(tX,tY),2,(0,255,0),2) #中心点を表示
#print ('中心:',tX,' ',tY)
# フレームを表示する
cv2.namedWindow('PCカメラ',cv2.WINDOW_NORMAL)
cv2.imshow('PCカメラ', img)
cv2.namedWindow('黄色抽出',cv2.WINDOW_NORMAL)
cv2.imshow('黄色抽出',res_color)
if(cv2.waitKey(1)==27):
cap.release()
cv2.destroyAllWindows()
break;
print("Program End.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment