cv2.VideoCapture can not read remote video file - python

I have a video file and need to load it with OpenCV.
import cv2
cap = cv2.VideoCapture('http://xx.xx.xxx.xxx:8080/xxx/2019-11-29.3gp')
print(vc.isOpened()) # get False
However, I get the following error
[tcp # 000001a19a548b00] Connection to tcp://xx.xx.xxx.xxx:8080 failed: Error number -138 occurred
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://xx.xx.xxx.xxx:8080/xxx/2019-11-29.3gp
(/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)
How can I solve?

Related

deploy.prototxt in Caffe model

I am running into this problem when running my code:
model = cv2.dnn.readNetFromCaffe("deploy.prototxt", "res10_300x300_ssd_iter_140000.caffemodel")
cv2.error: OpenCV(4.7.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\caffe\caffe_io.cpp:1126: error: (-2:Unspecified error) FAILED: fs.is_open(). Can't open "deploy.prototxt" in function 'cv::dnn::ReadProtoFromTextFile'
I Believe it is coming from when I run this line of code and am not sure what to do about it. I thought it was because I didn't have this file saved with the code but I am not entirely sure what this file is and does:
# Load the SSD model
model = cv2.dnn.readNetFromCaffe("deploy.prototxt", "res10_300x300_ssd_iter_140000.caffemodel")

Speech Recognition module in python throwing OSError

I am trying to transcribe text from an audio file with the speech recognition module in python. However, whenever I try to run the code, the module throws an OSError. I have disabled the lines of code that say “try” and “except”, since the code returns “Sorry... run again...” if I don’t. I have made sure that the audio sample is 16 bit, but even then I can’t get it to work. I am running Pythonista on an iPad Air, but I get the same results when using a MacBook Air. Is there a problem with software compatibility? I am also new to python, so can anybody help me with this issue?
The code:
#import library
import os
import speech_recognition as sr
import wave
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
# Reading Audio file as source
# listening the audio file and store in audio_text variable
with sr.AudioFile('audio1.wav') as source:
audio_text = r.listen(source)
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
#try:
# using google speech recognition
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
print(text)
#except:
#print('Sorry.. run again...')
The Traceback:
Traceback (most recent call last):
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/program/program.py", line 21, in <module>
text = r.recognize_google(audio_text)
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 828, in recognize_google
convert_width=2 # audio samples must be 16-bit
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 445, in get_flac_data
flac_converter = get_flac_converter()
File "/private/var/mobile/Containers/Shared/AppGroup/34AFF89C-1113-4021-BF04-27338D54F87B/Pythonista3/Documents/site-packages-3/speech_recognition/__init__.py", line 1196, in get_flac_converter
raise OSError("FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent")
OSError: FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent

Exit with code 1 due to network error: HostNotFoundError in Python

I am trying to convert HTML to pdf and I am using "wkhtmltopdf"
code is as follows
import pdfkit
path_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)
urls= ['https://www.amazon.com/','https://www.google.com/']
pdfkit.from_url(urls, 'out.pdf', configuration=config)
It was working fine and suddenly I am getting this error
Exit with code 1 due to network error: HostNotFoundError
What should I do to avoid this error.

How to correctly check if a camera is available?

I am using OpenCV to open and read from several webcams. It all works fine, but I cannot seem to find a way to know if a camera is available.
I tried this code (cam 2 does not exist):
import cv2
try:
c = cv2.VideoCapture(2)
except:
print "Cam 2 is invalid."
But this just prints a lot of errors:
VIDEOIO ERROR: V4L: index 2 is not correct!
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
failed to open /usr/lib64/dri/hybrid_drv_video.so
Failed to wrapper hybrid_drv_video.so
GStreamer Plugin: Embedded video playback halted; module v4l2src0 reported: Internal data stream error.
OpenCV Error: Unspecified error (GStreamer: unable to start pipeline
) in cvCaptureFromCAM_GStreamer, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp, line 832
VIDEOIO(cvCreateCapture_GStreamer(CV_CAP_GSTREAMER_V4L2, reinterpret_cast<char *>(index))): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_gstreamer.cpp:832: error: (-2) GStreamer: unable to start pipeline
in function cvCaptureFromCAM_GStreamer
OpenCV Error: Unspecified error (unicap: failed to get info for device
) in CvCapture_Unicap::initDevice, file /builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp, line 139
VIDEOIO(cvCreateCameraCapture_Unicap(index)): raised OpenCV exception:
/builddir/build/BUILD/opencv-3.2.0/modules/videoio/src/cap_unicap.cpp:139: error: (-2) unicap: failed to get info for device
in function CvCapture_Unicap::initDevice
CvCapture_OpenNI::CvCapture_OpenNI : Failed to enumerate production trees: Can't create any node of the requested type!
<VideoCapture 0x7fa5b5de0450>
No exception is thrown. When using c.read() later, I do get False, but I would like to do this in the initialisation phase of my program.
So, how do I find out how many valid cameras I have or check if a certain number 'maps' to a valid one?
Using cv2.VideoCapture( invalid device number ) does not throw exceptions. It constructs a <VideoCapture object> containing an invalid device - if you use it you get exceptions.
Test the constructed object for None and not isOpened() to weed out invalid ones.
For me this works (1 laptop camera device):
import cv2 as cv
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
testDevice(0) # no printout
testDevice(1) # prints message
Output with 1:
Warning: unable to open video source: 1
Example from: https://github.com/opencv/opencv_contrib/blob/master/samples/python2/video.py
lines 159ff
cap = cv.VideoCapture(source)
if 'size' in params:
w, h = map(int, params['size'].split('x'))
cap.set(cv.CAP_PROP_FRAME_WIDTH, w)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, h)
if cap is None or not cap.isOpened():
print 'Warning: unable to open video source: ', source
Another solution, which is available in Linux is to use the /dev/videoX device in the VideoCapture() call. The devices are there when the cam is plugged in. Together with glob(), it is trivial to get all the cameras:
import cv2, glob
for camera in glob.glob("/dev/video?"):
c = cv2.VideoCapture(camera)
Of course a check is needed on c using isOpened(), but you are sure you only scan the available cameras.
Here is a "NOT working" solution to help you prevent tumbling over in this pitfall:
import cv2 as cv
import PySpin
print (cv.__version__)
# provided by Patrick Artner as solution to be working for other cameras than
# those of Point Grey (FLIR).
def testDevice(source):
cap = cv.VideoCapture(source)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', source)
# ... PySpin / Spinnaker (wrapper/SDK libary) ...
system = PySpin.System.GetInstance()
cam_list = system.GetCameras()
cam = ''
cam_num = 0
for ID, cam in enumerate(cam_list):
# Retrieve TL device nodemap
if ID == cam_num:
print ('Got cam')
cam = cam
cam.Init()
# ... CV2 again ...
for i in range(10):
testDevice(i) # no printout
You can try this code:
from __future__ import print_function
import numpy as np
import cv2
# detect all connected webcams
valid_cams = []
for i in range(8):
cap = cv2.VideoCapture(i)
if cap is None or not cap.isOpened():
print('Warning: unable to open video source: ', i)
else:
valid_cams.append(i)
caps = []
for webcam in valid_cams:
caps.append(cv2.VideoCapture(webcam))
while True:
# Capture frame-by-frame
for webcam in valid_cams:
ret, frame = caps[webcam].read()
# Display the resulting frame
cv2.imshow('webcam'+str(webcam), frame)
k = cv2.waitKey(1)
if k == ord('q') or k == 27:
break
# When everything done, release the capture
for cap in caps:
cap.release()
cv2.destroyAllWindows()

Error occuring while connecting USB camera and two arduino with raspberry pi simultaneously

I have the following code for connecting one usb camera and two arduino board with raspberry pi.
import cv2.cv as cv, time
import numpy as np
import serial,time
ser1 = serial.Serial('/dev/ttyUSB0')
ser2 = serial.Serial('/dev/ttyUSB1')
capture = cv.CaptureFromCAM(0)
while True:
try:
for i in range(10):
x = ser1.readline()
with open("test1.txt", "a") as myfile:
myfile.write(x)
img = cv.QueryFrame(capture)
print("Taking image...")
cv.SaveImage('pic{:>05}.jpg'.format(i), img)
time.sleep(2)
y = ser2.readline()
with open("test2.txt", "a") as myfile:
myfile.write(y)
cv.WaitKey(1)
except:
continue
The camera is for taking continuous image frame and storing the latest 10 images in the current folder in each 2sec(Overwriting previous data). The datas from the arduino also logging into two separate text file. While running the code i am getting error messages as shown below.
pi#raspberrypi ~ $ sudo python accident.py
libv4l2: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl S_FMT
libv4l2: error setting pixformat: Device or resource busy
libv4l1: error setting pixformat: Device or resource busy
HIGHGUI ERROR: libv4l unable to ioctl VIDIOCSPICT
Taking image...
Taking image...
Taking image...
^Z
[4]+ Stopped
While I searched for this problem , I found that, all the USB port of rasp-pi having the same serial port.
Can anybody help me to solve this issue...

Categories