使用python-openCV對攝像頭捕捉的鏡頭進行二值化並打上文字


  1. CaptureFromCAM函數對圖像進行提取: capture = cv.CaptureFromCAM(0) 讀取直接的視頻文件只需將語句改變為: capture = cv.VideoCapture('videoname.avi')

  2. 對每一幀圖像進行讀取: while True:

    img = cv.QueryFrame(capture)

    #如果按下 esc 鍵則終止程序退出 if cv.WaitKey(10) == 27:

    break

  3. 在循環中對讀取的每一幀圖像進行二值化處理:

    def binaryThreshold(Image, threshold):
    grey = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_8U, 1) out = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_8U, 1)

    cv.CvtColor(Image,grey,cv.CV_BGR2GRAY)
    cv.Threshold(grey, out , threshold , 255 ,cv.CV_THRESH_BINARY)

    return out
    其中,CreateImage 函數表示按原幀大小創建 256 1 通道的灰度圖像, CvtColor 函數將傳入的圖像從 RGB 圖像轉換成灰度圖,寫入 grey 圖像。 Threshold函數按程序開始時threshold = input("threshold=")語句獲取的用 戶輸入的的閾值將圖像進行二值化寫入 out 圖像。將 out 圖像作為函數返回 值傳入主函數。

  4. 在每一幀圖像上覆蓋“3100102592 menglixia”的文字:
    (width, height) = cv.GetSize(img)
    text_font = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 2, 2) cv.PutText(img, "3100102592 menglixia", (50, height / 2), text_font, 
    cv.RGB(255, 0, 0))

獲取圖像高度和寬度,並初始化文字字體,在 1/2 高度處寫入“3100102592 menglixia”的字符串,以顏色紅色(在二值化后的圖像中顯示為 黑色)

       5. 顯示每一幀圖像:

            cv.ShowImage("camera",img) 

#coding=utf-8
import cv2.cv as cv

def binaryThreshold(Image, threshold):
    grey = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_8U, 1)
    out = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_8U, 1)
 
    cv.CvtColor(Image,grey,cv.CV_BGR2GRAY)
    cv.Threshold(grey, out ,threshold , 255 ,cv.CV_THRESH_BINARY)

    return out

if __name__ == '__main__':

    #threshold = input("threshold=")
    cv.NamedWindow("camera",1)
    capture = cv.CaptureFromCAM(0)  

    
    while True:
        """ capture image from camera """
        img = cv.QueryFrame(capture)

        """ convert color image to grey """
        #img = binaryThreshold(img, threshold)

        """ Get the width and height of the image """
        (width, height) = cv.GetSize(img)

        """ put text id and name in image """        
        text_font = cv.InitFont(cv.CV_FONT_HERSHEY_DUPLEX, 2, 2)
        cv.PutText(img, "3100102592 menglixia", (50, height / 2), text_font, cv.RGB(255, 255, 0))

        """ show each frame """
        cv.ShowImage("camera",img)

        """ press esc to quit the script """
        if cv.WaitKey(10) == 27:
            break

    del(capture)
    cv.DestroyWindow("camera")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM