使用opencv访问手机摄像头

2024-09-29 23:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用IP网络摄像头应用程序连接手机摄像头,但运行代码时出现错误

而且,URL不断变化。有没有一种方法可以让我不必每次都更改URL

这是我正在使用的代码:

import cv2

cap = cv2.VideoCapture("http://192.168.43.1:8080/shot.jpg")
while True:        
    ret, frame = cap.read()  
    cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))

    if cv2.waitKey(20) & 0xFF == ord('q'):
        break

这是我运行它时收到的错误消息:

Traceback (most recent call last):
  File ".\phone_cam.py", line 15, in <module>
    cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-9gpsewph\opencv\modules\imgproc\src\resize.cpp:3929: error: 

(-215:Assertion failed) !ssize.empty() in function 'cv::resize'

Tags: 代码inip网络应用程序url错误error
2条回答

这个答案不会直接解决问题,但它可以让你检测出原因,在阅读视频、图像或照相机时,这是一个很好的做法。始终检查ret的值是否为True,因为如果不是,则表示读取数据时出现问题

import cv2

cap = cv2.VideoCapture("http://192.168.43.1:8080/shot.jpg")
while True:        
    ret, frame = cap.read()  
    if ret:
        cv2.imshow("IPWebcam", cv2.resize(frame, (600, 400)))

        if cv2.waitKey(20) & 0xFF == ord('q'):
            break
    else:
        print("cap.read() returned False")

如果代码在else语句中打印消息,则表示链接存在问题。检查是否正确,是否需要添加用户名和密码

import cv2
import urllib.request
import numpy as np

URL = "http://192.168.43.1:8080/shot.jpg"


while(True):

    img_arr = np.array(
        bytearray(urllib.request.urlopen(URL).read()), dtype=np.uint8)
    frame = cv2.imdecode(img_arr, -1)

    # Display the image
    cv2.imshow('IPWebcam', cv2.resize(frame, (1100, 800)))

    if cv2.waitKey(20) & 0xFF == ord('q'):
        break

cv2.release()
cv2.destroyAllWindows()

相关问题 更多 >

    热门问题