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

opencv人臉追蹤

Haar-cascade Detection 

OpenCV中已經包含了許多預訓練的分類臉部,眼睛,微笑等,這些XML文件存儲在opencv/data/haarcascades/文件夾中。

本次實驗所需兩個XML檔

臉部

眼睛



import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

img = cv2.imread('face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 3)
for (x,y,w,h) in faces:
    img2 = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
     cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


參考資料:
http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_objdetect/py_face_detection/py_face_detection.html#face-detection
https://realpython.com/blog/python/face-recognition-with-python/
http://stackoverflow.com/questions/29316590/face-detection-using-haar-opencv-python

Wednesday, July 15, 2015

python script

我需要開啟webcam使用MJPG,再開啟一個python檔所以就寫了一個簡單的腳本建立一個
vi XXX.sh檔

寫指令流程

執行
sh XXX.sh

但有個問題我無法關閉webcam

解決辦法:

查看執行狀態

ps -aux |grep mjpg

砍掉執行狀態
sudo killall mjpg_streamer 

Thursday, July 9, 2015

使用raspberry pi 相機模組捕捉畫面

首先要啟用相機,開啟pi終端機下
sudo raspi-config

智能相機,之後pi版會要求重開機,就可使用

# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (160,120)
camera.framerate = 32
rawCapture = PiRGBArray(camera)

# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
        # grab the raw NumPy array representing the image, then initialize the timestamp
        # and occupied/unoccupied text
        image = frame.array

        # show the frame
        cv2.imshow("Frame", image)
        # clear the stream in preparation for the next frame
        rawCapture.truncate(0)

        # if the `q` key was pressed, break from the loop
        key = cv2.waitKey(1) & 0xFF
        if key == ord("q"):
                break

參考資料: http://www.pyimagesearch.com/2015/03/30/accessing-the-raspberry-pi-camera-with-opencv-and-python/ http://picamera.readthedocs.org/en/latest/recipes1.html#capturing-to-a-stream

Sunday, July 5, 2015

OPENCV Python 使用webcam錄影

從鏡頭中捕捉影像

要捕獲視頻,您需要創建一個VideoCapture對象。它的參數可以是該設備的索引或視頻文件的名稱。在此之後,可以捕獲幀接一幀。但最後,不要忘了釋放捕獲。


import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

從文件播放頻

只需更改視頻文件名 ​​稱相機索引。使用適當的時間cv2.waitKey() 如果過少,視頻會非常快,如果它是太高,視頻將是緩慢的。
import  numpy  as  np 
import  cv2 

cap  =  cv2 . VideoCapture ( 'vtest.avi' ) 

while ( cap . isOpened ()): 
    ret ,  frame  =  cap . read () 

    gray  =  cv2 . cvtColor ( frame ,  cv2 . COLOR_BGR2GRAY ) 

    cv2 . imshow ( 'frame' , gray ) 
    if  cv2 . waitKey ( 1 )  &  0xFF  ==  ord ( 'q' ): 
        break 

cap . release () 
cv2 . destroyAllWindows ()

保存視頻

 因此,我們捕捉視頻,過程中,我們要保存的視頻。這是非常簡單,只需使用cv2.imwrite() 。在這裡,更多一點的工作是必需的。 這一次,我們創建了一個VideoWriter對象。我們應當指定輸出文件名 ​​(如:output.avi)。那麼我們就應該指定的FourCC代碼,然後每秒(fps)的和幀大小幀的數量應傳遞。而最後一個是isColor標誌。如果這是真的,編碼器期望彩色幀,否則它與灰度框架。
FourCC是用於指定視頻編解碼器4字節代碼。
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

參考資料:
https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html http://stackoverflow.com/questions/26452909/opencv-write-frame-to-file-python

Thursday, July 2, 2015

開啟Webcam

import cv2
import numpy as np
WINDOW_NAME=("WEBCAM")
webcam = cv2.VideoCapture(0)
#Read Shooting images
while 1:
   ret, Shooting_images = webcam.read()
   cv2.imshow(WINDOW_NAME,Shooting_images)
   k = cv2.waitKey(5) & 0xFF
   if k == 27:
      break
#press ESC leave
cv2.destroyAllWindows()

opencv cv與cv2

一開始安裝最新的opencv3.0.0但需要用到cv這個函式庫,但在3版cv被拿掉,所以需灌2.4.X版以上的
參考資料:

http://stackoverflow.com/questions/26132081/is-cv2-cv-missing-in-opencv-3-0

http://blog.cavedu.com/raspberrypi-%E5%96%AE%E6%9D%BF%E9%9B%BB%E8%85%A6/%E6%84%9F%E8%AC%9D%E7%A5%AD%EF%BC%8C%E6%9C%89%E4%B8%8B%E6%9C%89%E6%8E%A8raspbian-opencv-img-%E6%AA%94%E4%B8%8B%E8%BC%89-%E5%8F%AF%E7%94%A8%E6%96%BC-raspberry-pi-b%E3%80%81b-%E4%BB%A5%E5%8F%8A-ban/