Error in opencv python whie loading Video - python

Actually I was loading a video Using k=cv2.VideoCapture("it.mp4") which is in the same folder but when I check it is opened or not it shows "False". and when i use k.open() to open it, it shows me this error:
Traceback (most recent call last):
File "", line 1, in
TypeError: Required argument 'filename' (pos 1) not found
As I think it is not getting the file but the video is in the same folder. I am stuck on this since a long time.
Here is the code:-
import numpy as np
import cv2
cap=cv2.VideoCapture("it.mp4")
k=cap.isOpened()
if k==False:
cap.open()
And it shows the below error:-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Required argument 'filename' (pos 1) not found

By looking at your code it is easy to figure out why you are getting this error. The reason is that you are using cap.open() without any arguments. You need to pass the filename to cap.open() in order to initialize the cv2.VideoCapture. So your code should be
import numpy as np
import cv2
cap=cv2.VideoCapture("it.mp4")
k=cap.isOpened()
if k==False:
cap.open("it.mp4")
In order to read the frames from cap you can use a loop like this
while(True):
ret, frame = cap.read()
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

You need to pass an argument for the cap.open(). In your case-
cap.open("it.mp4")
It must either be the device id in case you are using a camera or a filename which you want to read. Check out the page here.
But the actual issue here i think is that your opencv is not able to read the video you passed and which is the issue you are trying to fix. Either the file name or the extension is wrong.
If its neither, simply go to the path C:\opencv\build\x86\vc12\bin , copy the opencv_ffmpegabcd.dll and paste it in your python root directory. abcd here is your opencv version. If its a 64bit setup, copy the corresponding one.

Related

AttributeError: 'NoneType' object has no attribute 'copy' opencv error coming when running code [duplicate]

This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed last year.
I am having an issue with this Python code:
Code And Other Things
The Error Is:
Traceback (most recent call last):
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 156, in <module>
predict_age(image_path)
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 113, in predict_age
frame = img.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
I Was trying opencv as learning python. the project was to predict age but as this error came my days are wasted so please help me..
To Run The Code: python .\predict_age.py /tmp
or some new errors come
def predict_age(input_path: str):
"""Predict the age of the faces showing in the image"""
# Read Input Image
img = cv2.imread(input_path)
# Take a copy of the initial image and resize it
frame = img.copy()
Seems your error happens here because img is None, so it has no method copy() to call.
You said you are running the code like this:
.\predict_age.py /tmp
I can see that the code initialises img with the input_path which is passed as sys.argv[1]. well, /tmp is not really an image, could you try passing an image like .\predict_age.py /tmp/my_image.png
The error means that the img variable from cv2.imread(input_path) is None. I.e., something went wrong with reading the image from input_path.
In your main code, you write
import sys
image_path = sys.argv[1]
predict_age(image_path)
So the image path is given by the first argument to the program. Are you running the code as python predict_age.py 3-people.jpg?

Second video source /dev/video1 not working in python ubuntu

I am trying to use epiphan SDI2USB with ubuntu 18.04. I downloaded the correct driver from their support site and the driver is correctly installed. My kernel version is 4.15.0.
If I try to run vlc and i go to media menu --> Open Capture Device --> video device name --> Here I see both my /dev/video0 (integrated camera) and /dev/video1 (epiphan video) When I select /dev/video1 and click play, I can see it works fine.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
However when I write a simple python program from internet (i changed source from 0 to 1) and run it, I get an error
compass-admin#Alienware-13-R3:~$ sudo python3 cam.py
Insufficient buffer memory on /dev/video1 – decreasing buffers
Insufficient buffer memory on /dev/video1 – decreasing buffers
mmap: Invalid argument
munmap: Invalid argument
VIDEOIO ERROR: V4L: can’t open camera by index 1
munmap: Invalid argument
Traceback (most recent call last):
File “/home/compass-admin/.local/lib/python3.6/site-packages/numpy/lib/shape_base.py”, line 843, in split
len(indices_or_sections)
TypeError: object of type ‘int’ has no len()
I dont know if it is because of permissions or if you have to use a specific function in opencv. No matter what I do, I get the same error.
I changed permissions of /dev/video1 to 777, I also added the current user to video group but no luck. I also tried video source in opencv as 0, 1, -1 but no luck. Any help please.

How to use caffe convnet for object detection in video frames?

I have use codes from this link and sucessfully done the detection but the problem is it is only from webcam. I tried to modify the code so that it can read from file. the part I have modified is : I have written this
print("[INFO] starting video stream...")
vs= cv2.VideoCapture('cars.avi')
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
instead of this (code from the above link)
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
fps = FPS().start()
# loop over the frames from the video stream
while True:
# grab the frame from the threaded video stream and resize it
# to have a maximum width of 400 pixels
frame = vs.read()
For running the program from terminal I am using this command for both the cases:
python real_time_object_detection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
The error I am getting when reading from file is
the error I am getting is :
C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\real-time-object-
detection>python videoobjectdetection.py --prototxt
MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
[INFO] loading model...
Traceback (most recent call last):
File "videoobjectdetection.py", line 54, in <module>
frame = imutils.resize(frame, width=400)
File "C:\Users\DEBASMITA\AppData\Local\Programs\Python\Python35\lib\site-
packages\imutils\convenience.py", line 69, in resize
(h, w) = image.shape[:2]
AttributeError: 'tuple' object has no attribute 'shape'
I don't know where I am doing wrong. Please guide me.
I am unfamiliar with any of the code you are referencing, but the error is straightforward and similar errors hav been answered in other questions: You're trying to do a fancy method on a plain tuple object. Here's an example of this python concept using a common package, numpy for arrays:
#an example of the error you are getting with a plain tuple
>>>tup = (1,2,3,4)
>>>len(tup)
4
>>> tup.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
#an example that uses an attribute called 'shape'
>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> x.shape.shape
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'shape'
As you can see in my last two lines, the first time I call .shape on the numpy array, the call is valid. This call returns a tuple, so the last call to .shape.shape is invalid, it is operating on (4,). As for how to fix it? I don't know. For example, in this question the original poster thought that they were getting back some kind of image object, instead they were getting a tuple (maybe a tuple of image objects). Something similar is happening to you: Your VideoStream.read() call is returning a tuple. So when you call imutils.resize(frame, width=400) you are passing in a tuple, not an image or frame. So when that method tries to call .shape you get the error. VideoStream.read() may return a tuple by design, or an error condition. You'd have to read up on VideoStream to be sure.

Error when using scipy.misc.imread inside the loop

I have a case similar to this question.
Faced it when training deep learning model and reading images inside the loop.
scipy.misc.imread(rawImagePath).astype(numpy.float32)
The code above is working perfectly the vast majority of the time, but sometimes I get the error:
batch 90, loading batch data...
x path: /path_to_dataset/train/9.png
2017-10-31 20:23:34.531221: W tensorflow/core/kernels/queue_base.cc:294] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed
Traceback (most recent call last):
File "train.py", line 452, in <module>
batch_X = load_data(batch_X_paths)
File "/path_to_my_script/utilities.py", line 85, in load_data
x = misc.imread(batch_X_paths[i]).astype(np.float32)
TypeError: float() argument must be a string or a number
The difference is: I have a fixed set of files and I do not write new ones to the directory.
I made a little research and figured out that error comes not from
numpy.astype()
but from
PIL.Image.open()
scipy.misc uses PIL under the hood.
Also, I managed to reproduce this bug in Jupyter Notebook. I made a loop with reading/astype code inside. After few seconds (the size of my test .png is about 10MB) I interrupt cell's execution and voila!
error reproduced in Jupyter Notebook
Inside scipy.misc sources there is a code like this:
def imread(name, flatten=False, mode=None):
im = Image.open(name)
return fromimage(im, flatten=flatten, mode=mode)
Image here is a PIL object. And Image.open() gives us 0-dimension list when interrupting cell.
I have tried Evert's advice and made a loop with try/except, but sometimes it fails even after 5 attempts.
Also I tried OpenCV imread() method instead of scipy.misc and sometimes it fails too. Error text:
libpng error: incorrect data check
So... I ran out of ideas.

cv2.videocapture.read() does not return a numpy array

I have this code trying to capture a frame from my webcam on raspberry pi, and saving it as an image. I use opencv 2, but I get strange errors when I run the code..
import time
import sys
from subprocess import call
import cv2
cam = cv2.VideoCapture()
while True:
cam.open(-1)
image = cam.read()
cv2.imwrite("current.jpeg",image)
time.sleep(10);
This is what the program returns:
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
VIDIOC_QUERYMENU: Invalid argument
Traceback (most recent call last):
File "kvamskogen.py", line 18, in <module>
cv2.imwrite("current.jpeg",image)
TypeError: <unknown> is not a numpy array
What is wrong here?
Reading (cam.read()) from a VideoCapture returns a tuple (return value, image). With the first item you check wether the reading was successful, and if it was then you proceed to use the returned image.
This is documented at https://opencv-tutorial.readthedocs.io/en/latest/intro/intro.html#capture-live-video
Everything mmgp said is spot-on; cam.read() returns first a boolean indicating whether the read was successful, and then the image itself (which will be empty if the return value was False). Also note that if you're not using the return value for anything, you can just set that portion to _, which tells Python "ignore me"; that line would then look something like _, image = cam.read(). Additionally, it is generally good practice to specify the index at which your camera is located (usually 0 if you have only one camera connected) when calling cv2.VideoCapture(), so that, in the event that you do have multiple cameras connected, OpenCV knows which camera to read from (otherwise it might just crash because it doesn't know what to do).
You should use arguments in cv2.VideoCapture()
Try this to capture from the default camera
cam = cv2.VideoCapture(0)
Try this to capture from ip camera
cam = cv2.VideoCapture('http://ip-address') # to check video source's ip address right click video and select "copy image address" and put the exact address in above line of code
If you are trying to capture video using inbuilt webcam then following code line will give you best results
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

Categories

Resources