Tuesday, April 26, 2016

多個追蹤

import cv2
import numpy as np
#create a VideoCapture object
cap = cv2.VideoCapture(0)

while(1):

 # Capture Video from Camera
 _, frame = cap.read()

 # Convert BGR to HSV
 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

 # define range of blue color in HSV
 lower = np.array([0,0,0])
 upper = np.array([255,70,70])

 # Threshold the HSV image to get only blue colors
 mask_black = cv2.inRange(hsv, lower, upper)
 _, contours, _ = cv2.findContours(mask_black, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
 for cnt in contours: 
   x,y,w,h = cv2.boundingRect(cnt)
   cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
   # cv2.rectangle(frame,(x,y),((x+w),(y-h)),(255,0,0),2)
   # cv2.rectangle(frame,(x+(w/2),y+(h/2)-10),(x+(w/2),y+(h/2)+10),(255,0,0),2)
 # contours, hierarchy = cv2.findContours(Anti_White,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
 cv2.imshow('frame',frame)
 cv2.imshow('mask_black)',mask_black)
 k = cv2.waitKey(5) & 0xFF
 if k == 27:
  break

cv2.destroyAllWindows()

參考資料:
http://stackoverflow.com/questions/25504964/opencv-python-valueerror-too-many-values-to-unpack

Tuesday, August 11, 2015

raspberry pi 進入X-window自動執行腳本

如果您使用的Raspbian操作系統在你的樹莓派,你會知道,當你鍵入startx就啟動該圖形用戶界面“LXDE”。在這樣的環境中也有大量的應用程序和工具。在你的項目,你可能想要自動加載的一個或多個這些應用程序在運行startx的,以節省您不必手動啟動它們。

自動啟動程序
vi .config/lxsession/LXDE-pi/autostart

執行.sh腳本
@/bin/sh /home/pi/opencv_script.sh


參考資料:
http://www.raspberrypi-spy.co.uk/2014/05/how-to-autostart-apps-in-rasbian-lxde-desktop/

Wednesday, August 5, 2015

用滑鼠再圖片上畫框框

import cv2
import numpy as np
global px,py    

drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1

# mouse callback function
def draw_circle(event,x,y,flags,param):
    
    global ix,iy,drawing,mode
    #Click 
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix,iy = x,y
        print "ix=",ix,"iy=",iy

    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if mode == True:
  cv2.rectangle(img,(ix,iy),(x,y),(0,255,255),0)

img = cv2.imread('room.jpg')
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
 
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break

cv2.destroyAllWindows()



Friday, July 31, 2015

安裝raspberry opencv python 環境

STEP1:
打開pi板終端機

 sudo apt-get update
 sudo apt-get upgrade
 sudo rpi-update


STEP2:
安装所需的安装工具和包

sudo apt-get install build-essential cmake pkg-config

STEP3:
安裝必要的圖像I/O包,這樣你才可以讀入JPEG,PNG,TIFF等這些格式的圖像


sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-dev

STEP4:
安裝GTK開發庫,這個庫用來構建GUI。同時OpenCV中的highgui庫也需要它來在屏幕上顯示圖像


sudo apt-get install libgtk2.0-dev

STEP5:
安裝必要的視頻I/O包,OpenCV需要它們來讀入視頻文件

sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev

STEP6:
安裝OpenCV優化操作時所需庫
sudo apt-get install libatlas-base-dev gfortran

STEP7:
安裝pip
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py

STEP8:
現在我們安裝Python 2.7開發工具
sudo apt-get install python2.7-dev
我們也需要安裝NumPy,因為OpenCV的Python接口通過Numpy的多維數組來表示圖像

pip install numpy

STEP9:
下載和解壓OpenCV


wget http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip
unzip opencv-2.4.9.zip
cd opencv-2.4.9

安裝
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_NEW_PYTHON_SUPPORT=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON  -D BUILD_EXAMPLES=ON ..
編譯OpenCV 編譯OpenCV
make

最後,我們安裝OpenCV
 sudo make install


參考資料:
http://python.jobbole.com/81106/

Tuesday, July 28, 2015

RGB Trackbar

我們將創建一個簡單的應用程序,它顯示了你指定的顏色。你有一個窗口,其中顯示的顏色和三個trackbars指定每個的B,G,R的色彩。你滑動的TrackBar和相應的窗口顏色變化



import cv2
import numpy as np

def nothing(x):
    pass

# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')

# create trackbars for color change
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)

# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R','image')
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    print " R=",r,
    print " G=",g,
    print " B=",b
    s = cv2.getTrackbarPos(switch,'image')

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b,g,r]

cv2.destroyAllWindows()

http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_trackbar/py_trackbar.html#trackbar

Drawing Functions in OpenCV

  • 寫入數據
  • 位置坐標,你想要把它(即左下邊角數據開始)
  • 字體類型(檢查cv2.putText()文檔支持的字體)
  • 字體量表(指定字體的大小)
  • 喜歡的顏色,厚度,線型等。對於更好看規律性的東西,線型 cv2.CV_AA建議

import cv2
import numpy as np

img = np.zeros((512,512,3), np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.CV_AA)
cv2.namedWindow('image')

while(1):
    cv2.imshow('image',img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()
參考資料:
http://stackoverflow.com/questions/21899555/circle-detection-in-open-cv-using-python
http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html#drawing-functions

Thursday, July 23, 2015

顏色區塊取重心座標

不規則區域的矩,表示把一個歸一化的灰度級圖像函數理解為一個二維隨機變量的概率密度,這個隨機變量的屬性可以用統計特徵--矩(Moments)來描述。通過假設非零的像素值表示區域,矩可以用於二值或灰度級的區域描述
       M pq = sigma(i)sigma(j) i  j  f(i,j)
       其中x,y,i,j是區域點的坐標(在數字圖像中的像素坐標)。
       令Xc,Yc表示區域重心的坐標,則:
              Xc = M 10 /M 00 ;
              Yc = M 01 /M 00 ;

import cv2
import numpy as np
def  track(frame):
    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    cv2.imshow('hsv',hsv)
    # 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)
    moments = cv2.moments(mask)
    
    m00 = moments['m00']
    centroid_x, centroid_y = None, None
    if m00 != 0:
        centroid_x = int(moments['m10']/m00)#Take X coordinate
        centroid_y = int(moments['m01']/m00)#Take Y coordinate
 print 'x=',centroid_x,
 print 'y=',centroid_y

    ctr = (-1,-1) 
    if centroid_x != None and centroid_y !=None:
     ctr = (centroid_x, centroid_y)

     # Put black circle in at centroid in image
     cv2.circle(frame, ctr, 15, (0,0,255))
    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)
    #cv2.imshow('mask',mask)
    #cv2.imshow('res',res)
    cv2.imshow('frame',frame)

    return ctr
#cv2.destroyAllWindows()

if __name__ == '__main__':
 cap = cv2.VideoCapture(0)

 while True:
  # Take each frame
      _, frame = cap.read()
      track(frame)
      if cv2.waitKey(1) & 0xFF == 27:
            break
參考資料: http://blog.csdn.net/fengbingchun/article/details/6938895