1. 程式人生 > >樹莓派檢測運動目標並辨識類別程式碼備忘

樹莓派檢測運動目標並辨識類別程式碼備忘

rgbhistogram.py

import cv2
class RGBHistogram:
    def __init__(self, bins):
        self.bins = bins

    def describe(self, image, mask = None):
        image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        hist = cv2.calcHist([image], [0, 1, 2],
        mask, self.bins, [0, 256, 0, 256, 0, 256])
        cv2.normalize(hist, hist)
        return
hist.flatten()

classifier.py

from __future__ import print_function
from rgbhistogram import RGBHistogram
from sklearn.preprocessing import LabelEncoder
from sklearn import svm
###from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics
import classification_report from sklearn.externals import joblib import numpy as np import argparse import glob import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--images", required = True, help = "path to the image dataset") ap.add_argument("-m", "--masks", required = True, help = "path to the image masks"
) args = vars(ap.parse_args()) print(args) imagePaths = sorted(glob.glob(args["images"] + "/*.jpg")) maskPaths = sorted(glob.glob(args["masks"] + "/*.jpg")) data = [] target = [] #print(imagePaths) desc = RGBHistogram([16, 16, 16]) for (imagePath, maskPath) in zip(imagePaths, maskPaths): image = cv2.imread(imagePath) if image.ndim==2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) features = desc.describe(image) data.append(features) target.append('A') print(imagePath) mask = cv2.imread(maskPath) if mask.ndim==2: mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) features = desc.describe(mask) data.append(features) target.append('B') print(maskPath) #print(target) targetNames = np.unique(target) le = LabelEncoder() target = le.fit_transform(target) (trainData, testData, trainTarget, testTarget) = train_test_split(data, target,test_size = 0.1, random_state = 1) model = smv.SVC(gamma=0.5, C=1.) ###model = RandomForestClassifier(n_estimators = 25, random_state = 42) model.fit(trainData, trainTarget) joblib.dump(model, "svm_model.model") model = joblib.load("svm_model.model") print(classification_report(testTarget, model.predict(testData),target_names = targetNames)) for i in np.random.choice(np.arange(0, len(maskPaths)), 10): imagePath = maskPaths[i] image = cv2.imread(imagePath) #mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) features = desc.describe(image) type = le.inverse_transform(model.predict([features]))[0] print(imagePath) print("I think this type is a {}".format(type.upper())) cv2.imshow("image", image) cv2.waitKey(0)

執行方式:
python classify.py –image train_data /A –mask train_data /B
準備訓練資料如下:
A類資料:
這裡寫圖片描述
B類資料:
這裡寫圖片描述
執行訓練結果如下:
這裡寫圖片描述

detectCamera.py

from sklearn.externals import joblib
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestClassifier
from rgbhistogram import RGBHistogram
import argparse
import datetime
import imutils
import time
import numpy as np
import cv2


# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the video file")
ap.add_argument("-a", "--min-area", type=int, default=500, help="minimum area size")
args = vars(ap.parse_args())


model = joblib.load("svm_model.model")
target = []
target.append('A')
target.append('B')
targetNames = np.unique(target)
le = LabelEncoder()
target = le.fit_transform(target)
desc = RGBHistogram([16, 16, 16])


# if the video argument is None, then we are reading from webcam
if args.get("video", None) is None:
    camera = cv2.VideoCapture(0)
    time.sleep(0.25)

# otherwise, we are reading from a video file
else:
    camera = cv2.VideoCapture(args["video"])

# initialize the first frame in the video stream
firstFrame = None
frameCount = 0
# loop over the frames of the video
while True:
    # grab the current frame and initialize the occupied/unoccupied
    # text
    #d1 = datetime.datetime.now()
    (grabbed, org_frame) = camera.read()

    #d = datetime.datetime.now() - d1
    #print("#consuming %dms" % (d.microseconds/1000))
    text = "Unoccupied"

    # if the frame could not be grabbed, then we have reached the end
    # of the video
    if not grabbed:
        break

    frameCount = frameCount+1
    if frameCount%10 > 0:
            continue

        d1 = datetime.datetime.now()
    # resize the frame, convert it to grayscale, and blur it
    #frame = imutils.resize(frame, width=640)
    frame = cv2.resize(org_frame,(320,240),interpolation=cv2.INTER_LINEAR)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)

    # if the first frame is None, initialize it
    if firstFrame is None:
        firstFrame = gray
        continue
    # compute the absolute difference between the current frame and
    # first frame
    frameDelta = cv2.absdiff(firstFrame, gray)
    thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]

    # dilate the thresholded image to fill in holes, then find contours
    # on thresholded image
    thresh = cv2.dilate(thresh, None, iterations=2)
    (_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        area = 0;

    # loop over the contours
    for c in cnts:
        # if the contour is too small, ignore it
        if cv2.contourArea(c) < args["min_area"]:
            continue

        # compute the bounding box for the contour, draw it on the frame,
        # and update the text

        (x, y, w, h) = cv2.boundingRect(c)
        if area < w * h:
                    area = w * h
                    (bx,by,bw,bh) = (x,y,w,h);                    

        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        text = "Occupied"

    # draw the text and timestamp on the frame
    #cv2.putText(frame, "Room Status: {}".format(text), (10, 20),
    #   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    #cv2.putText(frame, datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S"),
    #   (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)

        if area > 0:
            print("x %d, y %d, w %d, h %d" % (bx, by, bw,by))
            cropImg = frame[by:by+bh, bx:bx+bw]
            features = desc.describe(cropImg)
            type = le.inverse_transform(model.predict([features]))[0]
            print("I think this is a {}".format(type.upper()))
            cv2.imwrite(datetime.datetime.now().strftime("captured_imgs/sub_%Y%m%d_%I%M%S_img.jpg"),cropImg)
    d = datetime.datetime.now() - d1

    print("consuming %dms" % (d.microseconds/1000))
    if cmp(text,"Occupied") == 0 :
            cv2.imwrite(datetime.datetime.now().strftime("captured_imgs/%Y%m%d_%I%M%S_img.jpg"),frame)
    # show the frame and record if the user presses a key
    cv2.imshow("Security Feed", frame)
    #cv2.imshow("Thresh", thresh)
    #cv2.imshow("Frame Delta", frameDelta)
    key = cv2.waitKey(1) & 0xFF

    # if the `q` key is pressed, break from the lop
    if key == ord("q"):
        break

# cleanup the camera and close any open windows
camera.release()
cv2.destroyAllWindows()

執行方式:

python detectCamera.py

相關推薦

樹莓檢測運動目標辨識類別程式碼

rgbhistogram.py import cv2 class RGBHistogram: def __init__(self, bins): self.bins = bins def describe(self, im

樹莓檢測ip指令碼

在樹莓派上執行web伺服器,但有時候開機完網路沒有啟動成功,需要重啟networking服務,所以寫了一個指令碼來檢測IP是否為192.168.x.x,如果不是則重啟networking #!/bin/bash while true do IP="$(ip addr show

樹莓建立wifi熱點開機自啟

1.建立熱點 建立WiFi熱點使用的GitHub上一個開源專案: https://github.com/oblique/create_ap #將程式碼copy到本地,安裝 sudo git clo

樹莓安裝vnc server設定自啟動

樹莓派初始化設定並安裝VNC SSH上去之後第一件事就是更新debian: sudo apt-get update, 升級完成後重啟一下; 在SSH終端輸入sudo raspi-config, 這裡需要開啟幾個選項: expand_rootfs – 將根分割槽擴充套件

基於樹莓的實時目標識別與移動目標監測系統

        本文主要分為兩部分,分別是基於樹莓派的實時目標識別與移動監測系統。兩部分主要根據兩個具體的教程進行講解。本篇重點講解配置過程,其中第一個主要是由mxnet官方的文件而來,起初進行這次測試的目的是因為看到了機器之心公眾號推的文章《亞馬遜詳解如何使用MXNet在

OpenCV之幀差法檢測運動目標

今天的目標是用OpenCV實現對運動目標的檢測,這裡選用三幀幀差法。程式碼如下: #include <opencv2/opencv.hpp> #include <cv.h> #include <highgui.h> #include &l

樹莓安裝vnc server設定自啟動

在SSH終端輸入sudo raspi-config, 這裡需要開啟幾個選項: expand_rootfs – 將根分割槽擴充套件到整張SD卡; change_pass – 預設的使用者名稱是pi,密碼是raspberry; change_timezone –

製作樹莓映象img,在其他新板上使用,實現批量克隆樹莓

1.      將現有的系統製作成映象img 2.      配置網路 1. 將現有的系統製作成映象img 1.1    先將新買的sd卡用SDFormatter工具格式化,以作備用 1.2    將帶有系統的sd卡用Win32DiskImager.exe工具Read成

幾種操作樹莓2B GPIO的方法附參考程式碼

硬體:樹莓派2B系統:Raspbian Debian Wheezy 2014-02-16環境:wiringPi、BCM2835 C Library、Python2.7、C注意:以下操作均在root許可權下操作這裡總結下操作GPIO的幾種方法,希望給新手做個參考,首先準備

在Linux上安裝XAMPP配置虛擬主機

1. 到https://www.apachefriends.org/zh_cn/index.html去下載最新版本,注意x86還是x64 2. 下載存放到任意位置,我這裡存到 /home下,接下來修改安裝檔案許可權,為方便直接賦予777  chmod 777 xampp-linux-

Python調用OpenCV實現攝像頭的運動檢測[樹莓版]

then see pip port wid warning number 12px ram [硬件環境] RaspberryPi 3代B型(英國版) [軟件環境] 操作系統:Raspbian Python版本:2.7.3 Python庫: 1.1) opencv-pytho

Python中呼叫OpenCV介面中的高斯混合模型,實現對運動目標檢測保存錄制視訊

Python中呼叫OpenCV介面中的高斯混合模型(GMM),實現對運動目標的檢測   import numpy as np import cv2 # TODO: 本程式碼使用OpenCV介面中的高斯混合模型,實現對運動目標的檢測 cap = cv2.VideoCapture(

樹莓實現目標實時檢測opencv-Moblenet

1、opencv3.3以上版本安裝 忽略,見部落格 效果圖 在OpenCV3.3版本釋出中把DNN模組從擴充套件模組移到了OpenCV正式釋出模組中,當前DNN模組最早來自Tiny-dnn,可以載入預先訓練好的Caffe模型資料,OpenCV做了近一步擴充套

基於樹莓與YOLOv3模型的人體目標檢測小車(一)

#### 專案介紹: 本科畢業選的深度學習的畢設,一開始只是學習了一下YOLOv3模型, 按照作者的指示在官網上下載下來權重,配好環境跑出來Demo,後來想著只是跑模型會不會太單薄,於是想了能不能做出來個比較實用的東西(因為模型優化做不了)。於是乎做一個可以檢測人體的可操控移動小車的想法就誕生了。

樹莓系列教程:1.環境與系統,無顯示器無鍵盤無網線聯網使用PuTTy與VNC圖形界面遠程登錄

工具 樹莓派 分享 clas http dev vnc圖形界面 gpo 遠程連接 本文所需物品清單: Raspberry Pi 3 Model B 主板、SD卡與讀卡器(用於燒錄系統) 資料整理來源在文尾 需要下載的資源與工具: 推薦系統-Raspbian 樹莓

毫秒級檢測!你見過帶GPU的樹莓嗎?

load 定義 interval += 編譯 lena 驗證 iss 另一個 樹莓派3B+英特爾神經計算棒進行高速目標檢測 轉載請註明作者夢裏茶 代碼: 訓練數據預處理: https://gist.github.com/ahangchen/ae1b7562c1f93f

樹莓是安裝配置NTP服務

all 配置 結果 sts restrict 1.9 nan .net 5.1 我們都知道樹莓派的小巧和省電節省空間等太多的優勢,這裏就不一一列舉了,那麽樹莓派就需要長時間的運行,可以7×24的方式運行,那麽我們就把樹莓派當作一個小的服務器來運行,可以跑一些小的

樹莓簡單攝像頭錄像保存視頻文件

mep lin line poi reat path wait pen ini 一、簡介   本文講使用OpenCV,不使用FFMPEG的方法進行保存視頻。 二、代碼   1、引用 <?xml version="1.0" encoding="utf-8"?

vs2015+opencv3.3.1+ c++實現 靜態背景下多運動目標提取,檢測

href alt obj opener wss opencv3.3 動物 lib ast 靜止背景下運動物體的提取,跟蹤出運動軌跡 下載地址 https://download.csdn.net/download/li_haoren/10761361 前景提取:

【資訊科技】【2014.01】智慧交通監控中運動目標檢測與跟蹤方法研究

本文為日本大學(作者:XiaofengLU)的博士論文,共143頁。 視訊監控已成為近年來影象處理和計算機視覺技術的一個重要研究領域,它嘗試從影象序列中檢測、識別、跟蹤某些物體,並瞭解、描述目標的行為。視訊交通監控系統為智慧交通系統(ITS)的交通控制和管理提供最有效的交通訊息,為