How to store webcam video with OpenCV in Python - python

I've got a script in Python which reads out my webcam and shows it in a window. I now want to store the results, so following this tutorial I wrote the following code:
import cv2
import imutils
camera = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while True:
try:
(grabbed, frame) = camera.read() # grab the current frame
frame = imutils.resize(frame, width=640, height=480)
cv2.imshow("Frame", frame) # show the frame to our screen
key = cv2.waitKey(1) & 0xFF # I don't really have an idea what this does, but it works..
video_writer.write(frame) # Write the video to the file system
except KeyboardInterrupt:
break
# cleanup the camera and close any open windows
camera.release()
video_writer.release()
cv2.destroyAllWindows()
print "\n\nBye bye\n"
This perfectly shows the real time video footage from my webcam in a new window. But writing the video file seems to fail. It does create a file called output.avi, but the file is empty (zero bytes) and on the command line I see the following errors:
OpenCV: Frame size does not match video size.
OpenCV: Frame size does not match video size.
OpenCV: Frame size does not match video size.
etc.
I clearly resize the frame to the size in which I want to save the video (640x480) so I'm not sure why it wouldn't match.
When I run the script again (so in this case the empty output.avi already exists), it shows these errors:
2017-04-17 10:57:14.147 Python[86358:5848730] AVF: AVAssetWriter status: Cannot Save
2017-04-17 10:57:14.332 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
2017-04-17 10:57:14.366 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
2017-04-17 10:57:14.394 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
etc.
In the tutorial it says that the Four digit FourCC code is used to specify the video codec which is platform dependent and that the list of available codes can be found in fourcc.org. I'm on OSX so I tried a bunch of different codec-codes: DIVX, XVID, MJPG, X264, WMV1, WMV2. But unfortunately none of them work for me. They all give the same errors, except for MJPG, which gives me the following error:
OpenCV Error: Assertion failed (img.cols == width && img.rows == height && channels == 3) in write, file /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp, line 829
Traceback (most recent call last):
File "store_video.py", line 15, in <module>
video_writer.write(frame) # Write the video to the file system
cv2.error: /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp:829: error: (-215) img.cols == width && img.rows == height && channels == 3 in function write
Does anybody know what could be wrong here? All tips are welcome!

It's probably because you built OpenCV with AVFoundation and it doesn't support XVID or other codec. You can try mp4v and m4v extension.
import cv2
camera = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc('m','p','4','v')
video_writer = cv2.VideoWriter('output.m4v', fourcc, 30.0, (640, 480))
while True:
(grabbed, frame) = camera.read() # grab the current frame
frame = cv2.resize(frame, (640,480))
cv2.imshow("Frame", frame) # show the frame to our screen
key = cv2.waitKey(33) & 0xFF # I don't really have an idea what this does, but it works..
video_writer.write(frame) # Write the video to the file system
if key==27:
break;
# cleanup the camera and close any open windows
camera.release()
video_writer.release()
cv2.destroyAllWindows()
print("\n\nBye bye\n")
On the other note, the error
OpenCV Error: Assertion failed (img.cols == width && img.rows == height && channels == 3) in write, file /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp, line 829
means that you messed up the dimension with
frame = imutils.resize(frame, width=640, height=480)
You can try cv2.resize as I used in my code. There's no need to use another library when cv2 can do that already.

Related

How to capture video with an external camera using opencv

I'm trying to capture a video from my pixy2 camera.
I wrote this code:
import cv2 as cv
vid = cv.VideoCapture(1, cv.CAP_DSHOW)
while (True):
ret, frame = vid.read()
cv.imshow('frame', frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
vid.release()
cv.destroyAllWindows()
and I'm getting this error:
"C:\Users\User\PycharmProjects\OpenCV tutorial\venv\Scripts\python.exe" "C:/Users/User/PycharmProjects/OpenCV tutorial/OpenCV_1.py"
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\OpenCV tutorial\OpenCV_1.py", line 14, in <module>
cv.imshow('frame', frame)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-sn_xpupm\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
Process finished with exit code 1
Any help, please!!
actually this error doesn't base on your videocapture operation. -As properly u set the capture parameter as 1 -
Here are two tips that will you help to determine the reason behind this error;
First use this line right after vid = cv.VideoCapture(1, cv.CAP_DSHOW) this line on your code:
vid not cap.isOpened(): print("Cannot open camera") exit()
This code helps you to understand whether your external camera is on or off.
The second tip is about the reading stage.
if not ret: print("Can't receive frame (stream end?). Exiting ...") break
You will get the error at 1.st step or 2.nd step then, yes!
By the way Welcome :)

OpenCV cannot find webcam but Cheese can

My opencv installation recently stopped working for reasons I'm not sure of. I have two scripts that all give different errors:
Script A:
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.imshow('frame', rgb)
gives me this error:
select timeout
VIDIOC_DQBUF: Resource temporarily unavailable
Traceback (most recent call last):
File "camera.py", line 19, in <module>
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.error: OpenCV(4.0.1-dev) /home/me/Packages/opencv/modules/imgproc/src/color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.imshow('frame', rgb)
And Script B:
import cv2
def show_webcam(mirror=False):
cam = cv2.VideoCapture(0)
while True:
ret_val, img = cam.read()
if mirror:
img = cv2.flip(img, 1)
cv2.imshow('my webcam', img)
if cv2.waitKey(1) == 27:
break # esc to quit
cv2.destroyAllWindows()
def main():
show_webcam(mirror=True)
gives me this error:
select timeout
VIDIOC_DQBUF: Resource temporarily unavailable
Traceback (most recent call last):
File "camera3.py", line 26, in <module>
main()
File "camera3.py", line 22, in main
show_webcam(mirror=True)
File "camera3.py", line 15, in show_webcam
cv2.imshow('my webcam', img)
cv2.error: OpenCV(4.0.1-dev) /home/david/Packages/opencv/modules/highgui/src/window.cpp:352: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
Here's the main issue: I've used OpenCV before and both of those errors usually occur when opencv can't find the webcam. But I do have a webcam attached, and when I open Cheese Webcam Booth it works fine, and takes pictures fine. Is there a way to repair this without reinstalling OpenCV?
I'm on Ubuntu 18.04.
I would review the OpenCV installation, since Script A works just fine by me, on the same version of the library and similar OS (Mint 19).
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
cv2.imshow('frame', rgb)
cv2.waitKey(10)
The installation through
pip install opencv-python
is known for having "problems" with 3rd party modules (https://github.com/opencv/opencv/issues/8471).
Try building and installing from source, this way the interface modules will be built and linked as well (V4L, FFMpeg, etc).
Two possible solutions: 1) set the correct fps; 2) upgrade to the newer version of opencv for python.
in both cases, the camera was activated but is now occupied. So now, in the main "while" loop try putting
while(True):
ret_val, img = cap.read()
if(ret_val==False)
cap.open(0)
continue
...

Opencv error init done

I have been running python script with nodejs using python-shell package.. and i am getting this error:
Error: init done
at PythonShell.parseError (F:\github\pythonShellDemo\node_modules\python-shell\index.js:191:17)
at terminateIfNeeded (F:\github\pythonShellDemo\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (F:\github\pythonShellDemo\node_modules\python-shell\index.js:89:9)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
after some debugging and research i got to know that this error is with opencv but i cant find any solution..
here is the code:
import cv2
import zbar
from PIL import Image
import sys
video = cv2.VideoCapture(0)
count=0
qrcode=[]
while True:
ret, frame = video.read()
cv2.imshow('Camera', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
grayscale = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
image = Image.fromarray(grayscale)
width, height = image.size
zbarimage = zbar.Image(width, height,'Y800', image.tobytes())
scanner = zbar.ImageScanner()
scanner.scan(zbarimage)
for x in zbarimage:
if count == 0:
qrcode=x.data
count=count+1
if qrcode:
break
video.release()
cv2.destroyAllWindows()
print(qrcode)
sys.stdout.flush()
I am using python 2.7
UPDATE:
nodejs code for calling python script:
PythonShell.run('python/scan.py', options, function (err, results) {
if (err) {
console.log(err)
reject(err)
}
// results is an array consisting of messages collected during execution
console.log(results)
resolve(results)
})
UPDATE:
i tried running opencv only without zbar.. still got the error
import cv2
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The OpenCV library prints init done to the standard error output. It's not an error, but just a debug print. python-shell then turns this into an error. From the python-shell documentation:
If the script writes to stderr or exits with a non-zero code, an error will be thrown.
Suppressing the output seems to be only possible by recompiling the library with a parameter set.

Resizing video resolution in OpenCV python

I want to reduce the resolution of video that I am getting from my webcam to half(i.e from 640x480 to 320x240) but I am getting error.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,320)
cap.set(4,240)
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',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
The error that I am getting is
Traceback (most recent call last): File
"C:\Users\Nemi\Desktop\bbb.py", line 17, in
cv2.imshow('frame',frame) error: ......\opencv-2.4.13.2\modules\highgui\src\window.cpp:269: error:
(-215) size.width>0 && size.height>0 in function cv::imshow
I am new to this and could not find the solution. Could someone please tell me what am I doing wrong?

OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow

I am running the following code on Raspberry Pi with pi camera, I have the broadcom drivers for it and all, but I am getting an error. Perhaps something to do with the dimensions of the video feed, but I do not know how to set it on Linux.
Code:
import cv2
import numpy as np
cap = cv2.VideoCapture()
while True:
ret, img = cap.read()
cv2.imshow('img', img)
if cv2.waitKey(0) & 0xFF == ord('q):
break
Error:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow,
file /home/pi/opencv-3.3.0/modules/highgui/src/window.cpp, line 325
Traceback (most recent call last):
File "check_picam_with_opencv.py", line 10, in <module>
cv2.imshow('img', img)
cv2.error: /home/pi/opencv-3.3.0/modules/highgui/src/window.cpp:325: error:
(-215) size.width>0 && size.height>0 in function imshow
Provide an id to VideoCapture.
cap = cv2.VideoCapture(0)
Also check the value of ret, see if it's TRUE or FALSE
print (ret)
Edit:
To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. Device index is just the number to specify which camera.
cap = cv2.VideoCapture(0)
To check whether the cap has been initialized or not, you can use cap.isOpened() function, which returns True for successful initialization and False for failure.
if cap.isOpened() == False:
print ("VideoCapture failed")
cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value.
ret, frame = cap.read()
if ret == False:
print("Frame is empty")
Further reading here.

Categories