使用OpenCV測試攝影機解析度

攝影機解析度取決於攝影機驅動程式,因此不同的攝影機所支援的解析度均不相同。雖然在OpenCV中可以使用resize()改變影像解析度,但也可以直接告訴驅動程式我們要的解析度為何,這樣OpenCV取得的影像就不需要再透過resize()來改變了。但驅動程式所支援的解析度並無法隨意設定,若設定不正確,OpenCV所取得的影像解析度就會是預設的而不是我們設定的。有一些指令可以得到攝影機解析度,但這裡,我們使用OpenCV來測試所有標準的解析度找出哪些解析度是支援的。

維基百科上可以找到目前已經定義的各種解析度,把該網頁的原始碼抓回來,解析出所有解析度然後交給OpenCV去測試。

載入需要的函數庫。

import urllib.request as urllib
import re
import cv2

取得維基百科上網頁原始碼,並且解析出解析度所在的表格。

def getTable():
    url = 'https://en.wikipedia.org/wiki/List_of_common_resolutions'
    ret = urllib.urlopen(url)
    html = ret.read().decode('utf-8')
    match = re.search('<table class="wikitable sortable">(.|\n)*?</table>', html)
    table = match.group()
    return table

取出表格中的每筆解析度並放入一個字典陣列中。這一步跟上一步有很多種處理方式,這裡我用幾個正規表示法把資料解析出來,不會是最好的作法,但優點是不需要額外安裝第三方函數庫,反正能夠把 width x height 解析出來就好了。

def getAllResolution(table):
    resolution = []
    result = re.findall('<tr>((.|\n)*?)</tr>', table)
    for p in result:
        match_width = re.search('<td style="text-align:right;border-right:none">((.|\n)*?)</td>', str(p))
        match_height = re.search('<td style="text-align:left;border-left:none">((.|\n)*?)</td>', str(p))
        if match_width is None or match_height is None:
            continue

        width = int(match_width.group(1).replace('\\n', ''))
        height = int(match_height.group(1).replace('\\n', ''))

        resolution.append({"width": width, "height": height})
    return resolution

然後將想要測試的解析度交給OpenCV去設定看看,設定完成後再跟取出的解析度比較,如果兩者一樣就代表攝影機支援這個解析度。

def resolutionTest(width, height):
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    rw = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    rh = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
    if rw == width and rh == height:
        print('{} x {}: OK'.format(width, height))

主程式如下:

cap = cv2.VideoCapture(0)
_, frame = cap.read()
h, w, c = frame.shape
print('預設解析度為 {} x {}'.format(w, h))
print('準備從維基百科取得解析度資料')
table = getTable()
resolutionList = getAllResolution(table)
print('已解析出所有解析度')
print('開始測試攝影機支援的解析度')
for p in resolutionList:
    resolutionTest(p['width'], p['height'])

執行後可以得之目前所安裝的攝影機支援的解析度為何。

預設解析度為 640 x 480
準備從維基百科取得解析度資料
已取得所有解析度
開始測試攝影機支援的解析度
320 x 240: OK
640 x 480: OK
800 x 600: OK
1280 x 720: OK
1280 x 960: OK
1920 x 1080: OK

發表迴響