Python + OpenCVで青い物体だけ検出

色空間の変換
WEBカメラの画像から青い物体だけ抽出できる。凄い。
青い物体抽出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import cv2
import numpy as np
 
cap = cv2.VideoCapture(0)
 
while(1):
 
    # Take each frame
    _, frame = cap.read()
 
    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
 
    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])
 
    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
 
    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)
 
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
 
cv2.destroyAllWindows()

追跡する色(HSV)を調べる方法
タイトル
1
2
3
4
>>> green = np.uint8([[[0,255,0 ]]])
>>> hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
>>> print hsv_green
[[[ 60 255 255]]]
下界と上界をそれぞれ [H-10, 100,100]と[H+10, 255, 255] に設定
HSVの各成分はそれぞれ,Hueが色相,Saturation(Chroma)が彩度,Value(Lightness)が明度を意味します.
それぞれuHeは[0,179], Saturationは[0,255],Valueは[0,255]の範囲の値をとります.
使用するソフトウェアによって値の範囲が異なるので,OpenCVで得られた値と
別ソフトウェアで得られた値を比較する場合は,値の正規化をしなければいけません
赤画像だけ表示
タイトル
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import cv2
import numpy as np
 
cap = cv2.VideoCapture(0)
 
while(1):
    _,frame = cap.read()
 
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
 
    #lower_blue = np.array([110,50,50])
    #upper_blue = np.array([130,255,255])
 
    lower_red1 = np.array([0,50,50])
    upper_red1 = np.array([10,255,255])
    lower_red2 = np.array([169,50,50])
    upper_red2 = np.array([179,255,255])
 
    #mask = cv2.inRange(hsv,lower_blue,upper_blue)
 
    mask1 = cv2.inRange(hsv,lower_red1,upper_red1)
    mask2 = cv2.inRange(hsv,lower_red2,upper_red2)
 
    mask = cv2.bitwise_or(mask1,mask2)
 
    res = cv2.bitwise_and(frame,frame,mask = mask)
 
    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xff
    if k == 27:
        break
 
cv2.destroyAllWindows()

コメント

このブログの人気の投稿

Python OpenCVとWebカメラでバーコードリーダー

VB.net Dictionaryクラスの初期化