簡體   English   中英

如何使用 opencv 和 python 訪問網絡攝像頭?

[英]How can a webcam be accessed using opencv with python?

這是我目前擁有的代碼:

import cv2, time

video=cv2.VideoCapture(0)
check, frame=video.read()

print(check)
print(frame)

cv2.imshow("Capturing", frame)
cv2.waitkey(0)
video.release()

代碼顯示語法錯誤。

錯誤:

False
None
Traceback (most recent call last):
  File "C:/Users/Stagiair/Desktop/aaa.py", line 9, in <module>
    cv2.imshow("Capturing", frame)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
import cv2

cap = cv2.VideoCapture(0)

# Check if the webcam is opened correctly
if not cap.isOpened():
    raise IOError("Cannot open webcam")

while True:
    ret, frame = cap.read()
    frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
    cv2.imshow('Input', frame)

    c = cv2.waitKey(1)
    if c == 27:
        break

cap.release()
cv2.destroyAllWindows()

這應該有效。

如果您在安裝CV2時遇到問題,可以嘗試以下步驟:

  1. 打開命令提示符。 (在 windows 搜索欄中搜索 CMD。)
  2. 運行以下命令:
python -m pip install –upgrade pip
  1. 使用以下命令安裝 opencv:
pip install opencv-python.

如果您使用的是 Anaconda,請按照以下步驟操作。

  1. 打開命令提示符。
  2. 使用以下命令更新 conda navigator:
conda update anaconda-navigator
conda update navigator-updater
  1. 使用以下命令安裝 opencv:
conda install -c conda-forge opencv

或者

conda install -c https://conda.binstar.org/menpo opencv

您的示例顯示video.read()正在返回(False, None) 這告訴您讀取失敗。 您看到的失敗是將None傳遞給cv2.imshow()的結果。

在我的一台筆記本電腦上,視頻需要幾次嘗試才能“預熱”並開始返回圖像。 安排忽略一些(False, None)返回通常就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM