I am trying to capture and save a video file by Open-CV but it's not playing - python-3.x

here is my code which i tried. video file is creating after the code run but video file is not playing. i have trouble to understand?
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,(1920,1000))
while(cap.isOpened()):
ret, frame = cap.read()
out.write(frame)
if ret==True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

Try this.
It might help
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,(1920,1000))
out = cv2.VideoWriter('C:/Users/DarkLord/Downloads/output1.avi', -1, 20,(1920,1000))
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()

The size of your video must be the same as the size of your camera reading frame.
Fix the code like this.
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
out = cv2.VideoWriter(r'C:/Users/DarkLord/Downloads/output1.avi',fourcc, 20,size)
while(cap.isOpened()):
ret, frame = cap.read()
out.write(frame)
if ret==True:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()

Related

How to close OpenCV window (Python 3) in macOS?

I am first time using macOS High Sierra and Spider IDE for Python Programming.
The window does not close when I press q key on the keyboard. The output window freezes with the last frame and control returns to the Python prompt.
Any solution or workaround will be much appreciated. I would also love to know the reason.
Following are the details of versions of Python and OpenCV.
Python 3.9.7
OpenCV 4.5.3
Spyder 5import cv2
The code is as follows,
import cv2
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)
cap.set(4, frameHeight)
cap.set(10,150)
window_name = "Result"
cv2.namedWindow(window_name)
while cap.isOpened():
success, img = cap.read()
if success:
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindow(window_name)
notice: success variable - is a boolean flag that tells you if the next frame is available to read.
if success is false, you probably reached the end of the video. Then, your program will be stuck in infinite loop because you never meet the conditions of if success: ... so you cant reach the command if cv2.waitKey(1) & 0xFF == ord('q'): break.
so first thing, you have to change the conditions in your while loop.
change
while cap.isOpened():
success, img = cap.read()
if success:
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
to
while cap.isOpened():
success, img = cap.read()
if not success:
break
cv2.imshow(window_name, img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
If you still have the same problem, as I had with my Jupyter Notebook, try to add cv2.waitKey(1) after destroying the window.
cv2.destroyAllWindows()
cv2.waitKey(1)
cap.release()

why is this attribute error showing up and what is the solution to it

i m running a code and its giving this attribute error pls help
the error that is shows while running the code
the code i am using:_
import cv2
from deepface import DeepFace
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError("Cannot open webcam")
while True:
ret, frame = cap.read()
result = DeepFace.analyze(frame, actions = ["emotion"])
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,1.1,4)
for(x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText('video',frame)
if cv2.waitKey(2) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

OpenCV do not want to stop video recording with cv2.COLOR_BGR2GRAY

when i run this code:
from cv2 import *
image = cv2.VideoCapture(0, cv2.CAP_DSHOW)
fourcc_cod = cv2.VideoWriter_fourcc(*"XVID")
name = input()
video = cv2.VideoWriter(f"{name}.AVI",fourcc_cod,60,(640,480))
while (True):
check,frame = image.read()
frame1 = cvtColor(frame, cv2.COLOR_BGR2GRAY)
video.write(frame1)
cv2.imshow('myimage',frame1)
if waitKey(1) ord('q'):
cv2.destroyAllWindows()
video.release()
image.release()
it does not stop recording the video Even if I press "q"
Try this snippet.
import cv2
cap = cv2.VideoCapture(0)
name = input()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(f'{name}.avi', fourcc, 20.0, (640, 480))
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 0)
# uncomment belove line for grayscale
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# write the flipped frame
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release() # video file writer
cv2.destroyAllWindows()

Python CV2 slow response time on keys

I have been coding a video player to test if I can play and pause a video in Python. My problem is that whenever I press a key, its irresponsive and needs continuous presses to work, and the effect is random.
If anyone knows what could be causing this, it would be of great help.
import cv2
cap = cv2.VideoCapture('testvideo.mp4')
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
isPlaying = False
def onchange(trackbar_value):
cap.set(cv2.CAP_PROP_POS_FRAMES, trackbar_value)
err, vid = cap.read()
cv2.imshow('player', vid)
pass
start = 0
cv2.namedWindow('player')
cv2.createTrackbar('test', 'player', start, length, onchange)
onchange(1)
while cap.isOpened():
if cv2.waitKey(1) & 0xFF == ord('q'):
break
elif cv2.waitKey(1) & 0xFF == ord('p'):
isPlaying = not isPlaying
ret, player = cap.read()
if cv2.waitKey(20) == 27:
break
if isPlaying:
cv2.imshow('test', 'frame')
elif cap.get(cv2.CAP_PROP_POS_FRAMES) >= length:
break
cap.release()
cv2.destroyAllWindows()
I fixed it by changing this part in the while cap.isOpened() loop:
keyPress = cv2.waitKey(20)
ret, player = cap.read()
if keyPress & 0xFF == ord('q'):
break
elif keyPress & 0xFF == ord('p'):
isPlaying = not isPlaying
once I removed the
if cv2.waitKey(20) == 27:
break
line, it worked much better than before too.
All of this sped up the project, and everything works fine now

Save image in Full HD size using OpenCv Python

When i try to save a image using cv2.imwrite() method, it save a file in 640x480 pixel size. My web cam is FUll HD (1920×1080 px). How can i save the picture in this FHD size.
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', frame)
cv2.imwrite('a.jpg',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap.set(3, 1920)
cap.set(4, 1080)
cap.set(6, cv2.VideoWriter.fourcc('M', 'J', 'P', 'G'))
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)
cv2.imwrite('a.jpg',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Resources