Rio
Rio

Reputation: 77

Access phone camera using opencv

I'm trying to connect my phone camera using IP webcam application but I get when error when I run the code.

Also, the URL keeps changing. Is there a method so that I don't need to change the URL every time?

This is the code I am using:

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

And this is the error message I get when I run it:

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'

Upvotes: 0

Views: 947

Answers (2)

Rio
Rio

Reputation: 77

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()

Upvotes: 0

Wazaki
Wazaki

Reputation: 899

This answer will not directly solve the issue, but it will allow you to detect the cause and it's a good practice when reading a video, image or from a camera. Always check if the value of ret is True because if it is not, it means there was a problem reading the data.

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")

If the code prints the message in the else statement, that means there is an issue with the link. Check if it is the correct one and whether you need to add a username and password or not.

Upvotes: 1

Related Questions