OpenCV學習之路(一)初識圖片與視頻

圖片

讀入圖片

構造函數爲:

cv2.imread()

函數接受兩個參數,第一個參數爲圖片所在路徑,第二個參數爲以何種方式顯示圖片。

  • cv2.IMREAD_COLOR:讀入彩色圖片
  • cv2.IMREAD_GRAYSCALE:以灰度模式讀入圖片
  • cv2.IMREAD_UNCHANGED:讀入一幅圖像並讀入圖像的alpha通道。

顯示圖片

構造函數爲:

cv2.imshow(windows_name,image_name)

使用imshow()函數可以爲讀取的圖片創建一個窗口來顯示圖片。
函數接受兩個參數:

  • windows_name:創建窗口的名字
  • image_name:圖片的名字。
    這裏介紹三個在顯示圖像時可能用到的函數
cv2.waitKey()

這是一個鍵盤綁定函數。需要指出的是它的時間尺度是毫 秒級。函數等待特定的幾毫秒,看是否有鍵盤輸入。特定的幾毫秒之內,如果 按下任意鍵,這個函數會返回按鍵的 ASCII 碼值,程序將會繼續運行。如果沒 有鍵盤輸入,返回值爲 -1,如果我們設置這個函數的參數爲 0,那它將會無限 期的等待鍵盤輸入。它也可以被用來檢測特定鍵是否被按下,例如按鍵 a 是否 被按下,這個後面我們會接着討論。

cv2.destroyAllWindows()

這個函數可以輕易刪除任何我們建立的窗口。如果你想刪除特定的窗口可以使用 cv2.destroyWindow(),在括號內輸入你想刪 除的窗口名。

cv2.nameWindows()

需要注意的是,我們在使用cv2.imshow()顯示圖像時,圖像窗口大小是不可以調的,但是有時候圖像維度過大,我們需要調整圖像大小,此時就需要cv2.nameWindows()。
函數接受兩個參數:

  • 第一個參數是圖像窗口的名字
  • 第二個參數默認爲 cv2.WINDOW_AUTOSIZE。我們只要改成cv2.WINDOWS_NORMAL。窗口大小就可以改動了。

保存圖片

構造函數:

cv2.imwrite()

函數接受兩個參數:

  • 第一個參數爲打算把圖片保存的路徑及文件名
  • 第二個參數爲待保存的圖片名

以灰度圖形式讀取一張圖片,並且可以改變圖片大小。按s鍵退出並保存,按d鍵則直接退出。

import numpy as np
import cv2
def main():
    img=cv2.imread('D:\\xidada.jpg',cv2.IMREAD_GRAYSCALE)
    cv2.namedWindow('image',cv2.WINDOW_NORMAL)
    cv2.imshow('image',img)
    k=cv2.waitKey(0)
    if k==ord('d'):
        cv2.destroyAllWindows()
    elif k==ord('s'):
        cv2.imwrite('D://a3',img)
        cv2.destroyAllWindows()
if __name__=='__main__':
    main()

視頻

用攝像頭捕獲視頻

爲了獲取視頻,我們需要創建一個VideoCapture對象:

cap=VideoCapture()

筆記本電腦都有內置攝像頭,如果想用內置攝像頭:

cap=VideoCapture(0)

如果調用USB攝像頭的話:

cap=VideoCapture(1)

簡言之就是通過設置VideoCapture的參數是0或1來改變調用的攝像頭。
爲了便於理解,舉個栗子

例1

從攝像頭捕獲彩色視頻

import numpy as np
import cv2
def main():
   cap=cv2.VideoCapture(0)
   while(True):
       ret,frame=cap.read()#一幀一幀的獲取圖像
       cv2.imshow('capture',frame)#按幀顯示圖像
       if cv2.waitKey(1)&0xFF == ord('e'):#按e退出
            break
   cap.release()#別忘了用完了吧cap釋放
   cv2.destroyAllWindows()
if __name__=='__main__':
    main()

例2

用攝像頭捕獲灰度視頻

import numpy as np
import cv2
def main():
   cap=cv2.VideoCapture(0)
   while(True):
       ret,frame=cap.read()#一幀一幀的獲取圖像
       grayfilme=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
       cv2.imshow('frame',grayfilme)#按幀顯示圖像
       if cv2.waitKey(1)&0xFF == ord('e'):#按e退出
            break
   cap.release()#別忘了用完了吧cap釋放
   cv2.destroyAllWindows()
if __name__=='__main__':
    main()
這裏介紹幾個功能性函數
cap.read()

返回一個布爾值(True/False)。如果幀讀取的是正確的, 就是 True。所以最後你可以通過檢查他的返回值來查看視頻文件是否已經到 了結尾。

cap.isOpen()

用來檢查攝像頭是否正常初始化,如果正常則返回爲True,否則返回爲False,需要使用cap.open()函數。

cap.get(propld)

這個函數用來獲取視頻的各種屬性,接受參數爲1到18的數字,每一種數字代表一種屬性。對應關係如下。當然,也可以直接在get函數中傳入下列參數來獲得對應屬性。

  • CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
  • CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
  • CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film
  • CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
  • CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
  • CV_CAP_PROP_FPS Frame rate.
  • CV_CAP_PROP_FOURCC 4-character code of code.
  • CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
  • CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
  • CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
  • CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
  • CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
  • CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
  • CV_CAP_PROP_HUE Hue of the image (only for cameras).
  • CV_CAP_PROP_GAIN Gain of the image (only for cameras).
  • CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
  • CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
  • CV_CAP_PROP_WHITE_BALANCE Currently unsupported
  • CV_CAP_PROP_RECTIFICATIONRectificationflagforstereo cameras (note: only supported by DC1394 v 2.x backend currently)
cap.set(propld,value)

這個函數是用來修改上述屬性的,value就是要修改成的值

獲得視頻每一幀的寬和高,則應該

 print(cap.get(3),cap.get(4))
 #輸出爲640.0 480.0

我想把寬和高分別變成320和240.

ret=cap.set(3,320)
ret=cap.set(4,240)

播放已保存的視頻

opencv似乎只能播放avi格式的視頻啊,所以如果是別的格式需要先轉成avi格式。

import numpy as np
import cv2
def main():
  cap=cv2.VideoCapture('D://guoyujiaoxue.MP4')
  fps=int(cap.get(cv2.CAP_PROP_FPS))#獲得視頻幀率
  VideoWriter=cv2.VideoWriter('D://guoyujiaoxue.avi',cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),20.0,(640,480))
#20.0代表播放速度,(640,480)代表幀大小

  while(cap.isOpened()):
    ret,frame=cap.read()
    if(ret==True):
      VideoWriter.write(frame)
      cv2.imshow('frame',frame)
      if cv2.waitKey(fps)&0xFF==ord('e'):
        break
    else:
      break
if __name__=='__main__':
  main()

對幾個函數進行解釋:

  • cv2.waitkey()
    這裏要設置合適的持續時間,如果設置的太低就會導致視頻播放過快,如果設置的太高就會導致視頻播放太慢,一般來說
    比較合適。
  • cv2.VideoWriter_fourcc
    顧名思義,四個編碼,代表的是視頻格式。下面羅列幾個常見的編碼:

#cv2.VideoWriter_fourcc(‘I’, ‘4’, ‘2’, ‘0’),該參數是YUV編碼類型,文件名後綴爲.avi
#cv2.VideoWriter_fourcc(‘P’, ‘I’, ‘M’, ‘I’),該參數是MPEG-1編碼類型,文件名後綴爲.avi
#cv2.VideoWriter_fourcc(‘X’, ‘V’, ‘I’, ‘D’),該參數是MPEG-4編碼類型,文件名後綴爲.avi
#cv2.VideoWriter_fourcc(‘T’, ‘H’, ‘E’, ‘O’),該參數是Ogg Vorbis,文件名後綴爲.ogv
#cv2.VideoWriter_fourcc(‘F’, ‘L’, ‘V’, ‘1’),該參數是Flash視頻,文件名後綴爲.flv

如果想知道完整的,請訪問:http://www.fourcc.org/codecs.php

保存視頻

從攝像頭讀取圖像並逐幀保存

import numpy as np
import cv2
def main():
  cap=cv2.VideoCapture(0)#獲取攝像頭
  out=cv2.VideoWriter('D://aviaxi.avi',cv2.VideoWriter_fourcc('X','V','I','D'),20,(640,480))
  while(True):
    ret,frame=cap.read()
    out.write(frame)#逐幀保存
    cv2.imshow('capture',frame)
    if cv2.waitKey(1)&0xFF==ord('e'):
      break
  cap.release()
  out.release()
  cv2.destroyAllWindows()
if __name__=='__main__':
  main()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章