使用opencv访问手机摄像头



我正试图使用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:UsersappveyorAppDataLocalTemp1pip-req-build-9gpsewphopencvmodulesimgprocsrcresize.cpp:3929: error: 
(-215:Assertion failed) !ssize.empty() in function 'cv::resize'

这个答案不会直接解决问题,但它可以让您检测原因,在读取视频、图像或相机时,这是一个很好的做法。始终检查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()

最新更新