I just started playing around with OpenCV in Python and am running into an assertion error. I copied the following code from a tutorial, but it's not working for me.
import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0) # use first webcam
if not cap.isOpened(): cap.open()
while True:
# capture frame-by-frame
ret, frame = cap.read()
# our operations on the frame come here
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
# display the resulting frame
cv.imshow('frame', gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
# when everything is done, release the capture
cap.release()
cv.destroyAllWindows()
When running, I get OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor
When printing the variables ret and frame from above, I get (False,None), so it's not even capturing the frame correctly.
What exactly is the issue, and how can I resolve it?
Thank you.
After ret, frame = cap.read(), add if not ret: continue.
Some cam-drivers return an invalid first frame.
Related
Unable to import video media folder into program to convert to gray-scale.
import cv2
import numpy as np
# The video feed is read in as a VideoCapture object
cap = cv2.VideoCapture(r'C:\Users\Mark\Desktop\Research\Source\Video\Traffic01.mp4')
# ret = a boolean return value for getting the frame
ret, first_frame = cap.read()
# Converts frame to grayscale
prev_gray = cv2.cvtColor(cv2.UMat(first_frame), cv2.COLOR_RGB2GRAY)
while(cap.isOpened()):
# ret = a boolean return value from getting the frame
ret, frame = cap.read()
# Converts each frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Frames are read by intervals of 10 milliseconds.
#The programs breaks out of the while loop when the user presses the 'q' key
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Error:
OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error:
(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Why is that UMat there? That would seem to answer the question src.empty()
from the docs at openCV UMat is/does :-
constructs 2D matrix and fills it with the specified value _s.
whereas cvtcolor wants a source image/frame
Also why is the first frame so important it has to be outside the main loop?
My advice comment out that first cap.read() and cv2.cvtcolor() lines just before your while loop.
HTH
What would you have to do to get a single frame from a live webcam feed and update it repeatedly to a output file? I have seen this done before so i know it is possible. I want to use something like Python if possible but any help is welcome. Maybe this is possible using OpenCV?
This should meet your requirements of "Saving each frame from the video feed "
import numpy as np
import cv2
import random
cap = cv2.VideoCapture(0)
i=0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
i+=1
cv2.imwrite('database/{index}.png'.format(index=i),frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
In Code . database is the directory where every frame will be saved through index(i) iteration.
OpenCV should be able to do this pretty easily:
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()
Source: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
I'm trying to play a video file using python opencv this is my code , but it is not showing the vidfeo file when I run the code
import numpy as np
import cv2
cap = capture =cv2.VideoCapture('C2.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
cv2.waitKey(1)
cap.release()
cv2.destroyAllWindows()
I tried the answer in : link but not working again
I think u just have to increase the number inside cv2.waitKey() function to may be 25 or 30. You should get the desired result.
Also, there is no need to write cap = capture = cv2.......
Simply, writing,
cap = cv2.videoCapture('path of the video')
should work as well . Hope it works.
import numpy as np
import cv2
cap = cv2.VideoCapture('C2.mp4')
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
# & 0xFF is required for a 64-bit system
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
This code worked for me. It shows both the original and the grayscale video output. Press 'q' to exit. I also didnt see the need for cap = capture... in your code.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',frame)
cv2.imshow('grayF',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Try using this
cv.CaptureFromFile()
and also check out this link http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html
First of all, there is no need of capture as you are not using capture in your code. The reason why your video file is not showing because you haven't saved it in the same directory, where you have saved the code.
You can either give the path where your file is saved as shown below
cap = cv2.VideoCapture('(path to the video file)/cv2.mp4')
Again you need to change the argument inside waitKey otherwise the program will not close the window that shows the video correctly.
Try out the following, it will definitely work. Put an if statement with waitKey() function and increase the argument which indicates the number of milliseconds it will wait for a key function to 25 or whatever number you may like so that when you press ESC key, the window will be destroyed:
if cv2.waitKey(25) & 0xFF == 27:
break
The problem in my code was in the part (While). It should be while (True) instead the one in your code
ren opencv_ffmpeg.dll to opencv_ffmpeg2413.dll on your project dir if opencv-2.4.13.exe
I am trying to capture the video through openCV and then applying Adaptive thresholding on the video (to convert to black and white). The problem is this code throws up error very frequently. I am playing around with the last two numbers in the adaptive threshold function.
cv2.error: /tmp/opencv-UA2sOU/opencv-2.4.9/modules/imgproc/src/thresh.cpp:797: error: (-215) blockSize % 2 == 1 && blockSize > 1 in function adaptiveThreshold
I can't seem to understand what causes this issue.
import numpy as np
import cv2
import pylab as pl
cap = cv2.VideoCapture(0)
# take first frame of the video
ret,frame = cap.read()
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,40,15)
cv2.imshow('frame',thresh)
if cv2.waitKey(1) & 0xFF == ord('q'):
#cv2.imwrite("snap.jpg", thresh)
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
cv2.adaptiveThreshold requires an odd blockSize. So you'd need to use 39 or 41 instead of 40.
blockSize – Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
This is indicated by the error message: It says "blockSize % 2 == 1", which means blockSize is not divisible by 2.
I used the following code to capture a video file, flip it and save it.
#To save a Video File
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
This program saves the output as output.avi
Now, to playback the video file I used the following program
#Playing Video from File
import numpy as np
import cv2
cap = cv2.VideoCapture('output.avi')
print cap.get(5) #to display frame rate of video
#print cap.get(cv2.cv.CV_CAP_PROP_FPS)
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #convert to grayscale
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
This program plays the video file output.avi saved from the first program. The thing is, this video appears fast forward. So, I tried changing the delay value for cv2.waitKey(). The video looked fine when I put 100. How do I know which value to put there? Should it be related to the frame rate? I checked the frame rate of output.avi (see line cap.get(5) in second program) and got 20. But if I use 20 as delay for cv2.waitKey() the video is still too fast.
Any help would be appreciated.
From the OpenCV documentation:
The function cv.waitKey([, delay]) waits for a key event infinitely
(when delay <= 0) or for delay milliseconds, when it is positive.
If the FPS is equal to 20, then you should wait 0,05 seconds between displaying the consecutive frames. So just put waitKey(50) after imshow() in order to have the desired speed for the playback.
For what it is worth, I have tried all sorts of tricks with setting the cv2.waitKey() delay time and they have all failed. What I have found to work is to try something like:key = cv2.waitKey(1) inside of your while(cap.isOpened()) like so:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
key = cv2.waitKey(1)
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if key & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
I hope this helps someone out there.
put waitKey(60) after imshow() and it will be displayed at normal speed.