Python cv2.VideoCapture() has wrong resolution and read cropped images - python

I'm trying to read images from an IDS GV-5240CP camera plugged to my laptop via ethernet using Python and OpenCV.
This is what I am supposed to get :
A 1280x1024 image (here resized for upload)
But using this code:
import cv2
cap = cv2.VideoCapture(1)
_, frame = cap.read()
print(frame.shape)
cv2.imshow("Out", frame)
cv2.waitKey(2000)
cap.release()
cv2.destroyAllWindows()
cv2.imwrite('Test2.png', frame)
I get:
A 640x480 cropped image
How can I set my video capture to the native resolution?

VideoCapture uses 640x480 by default.
If you want a different resolution, specify it in the constructor or use the set() method with CAP_PROP_FRAME_WIDTH and so on. Details in the docs.
cap = cv2.VideoCapture(1, apiPreference=cv2.CAP_ANY, params=[
cv2.CAP_PROP_FRAME_WIDTH, 1280,
cv2.CAP_PROP_FRAME_HEIGHT, 1024])

out = cv2.VideoWriter(("E:", 'output.avi'), fourcc, 20.0, (640, 480))
try using this and change the resolution according to your need,
tho it will download or use
cv2.resize(frame,(w,h),fx=0,fy=0, interpolation = cv2.INTER_CUBIC)
since you don't want to do this then use set() module in OpenCV to set specific resolution. docs.opencv.org/4.x/d8/dfe/… this link for the full info about set()

Related

Cannot view video after writing in python/OpenCV

Edit: The problem was fixed after using VLC media player. The standard windows media player could not read the videos.
I am attempting to take a video, run it through an object detector, add the bounding boxes, and output the video with the bounding boxes. However, I'm having a strange problem where the video I output cannot be viewed. I get a "Server execution failed" error when attempting to play the video on my local windows 10 machine. I am developing through SSH on ubuntu 20.04 with the vs code remote development extension.
Here is some OpenCV code that does not work with my setup. The video is written to the disk, and OpenCV is able to read frames from output5.avi, however the output5.avi file cannot be opened as I described.
import cv2
cap = cv2.VideoCapture("video.mov")
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
out = cv2.VideoWriter('output5.avi', fourcc, 30, (width, height), isColor=True)
while cap.isOpened():
# get validity boolean and current frame
ret, frame = cap.read()
# if valid tag is false, loop back to start
if not ret:
break
else:
frame = cv2.resize(frame, (width, height))
out.write(frame)
cap.release()
out.release()
I have also attempted to save the video through torchvision.io.write_video, but the exact same problem occurs. Tensorboard similarly doesn't work.
It must be something wrong with how the remote machine is set up, but I have no idea what could be wrong.

the fastest method of capturing full screen with python?

I was using ImageGrab from PIL, but this is too slow to use for the project.
Are there any alternatives without using PIL?
Capturing an image is equivalent to capture a single frame of a video. You can do it using the VideoCapture method of OpenCV.
import cv2
cap = cv2.VideoCapture(0) # video capture source camera (Here webcam of laptop)
ret,frame = cap.read() # return a single frame in variable `frame`
while(True):
cv2.imshow('img',frame) #display the captured image
if cv2.waitKey(1) & 0xFF == ord('y'): #save on pressing 'y'
cv2.imwrite('images/test.png',frame)
cv2.destroyAllWindows()
break
cap.release()
Check the OpenCV tutorial for more information.

Python/OpenCV camera capture resulting in blank/black images

I have a webcam and I have installed the camera drivers and it is using the vendor's drivers (not UVC). I am trying to capture an image and it is resulting in an array of zeros (frame). I have used another software on windows and it is able to get the video without issues. Any ideas on how to fix this issue?
import cv2
cam = cv2.VideoCapture(1)
f1 = cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
f2 = cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
f2 = cam.set(cv2.CAP_PROP_FPS, 1)
print(cam.get(3),cam.get(4))
if cam.isOpened():
_,frame = cam.read()
cv2.imshow('',frame)
Edit: Please check the comments. I tried a few suggestions and they didn't work. I changed the camera, but with the new camera, I get noise.

OpenCV load video from url

I have a video file (i.e. https://www.example.com/myvideo.mp4) and need to load it with OpenCV.
Doing the equivalent with an image is fairly trivial:
imgReq = requests.get("https://www.example.com/myimage.jpg")
imageBytes = np.asarray(bytearray(data), dtype=np.uint8)
loadedImage = cv2.imdecode(image, cv2.IMREAD_COLOR)
I would like to do something similar to the following (where loadedVideo will be similar to what OpenCV returns from cv2.VideoCapture):
videoReq = requests.get("https://www.example.com/myimage.mp4")
videoBytes = np.asarray(bytearray(data), dtype=np.uint8)
loadedVideo = cv2.videodecode(image, cv2.IMREAD_COLOR)
But cv2.videodecode does not exist. Any ideas?
Edit: Seeing as this may be a dead end with only OpenCV, I'm open for solutions that combine other imaging libraries before loading into OpenCV...if such a solution exists.
It seems that cv2.videocode is not a valid OpenCV API either in OpenCV 2.x or OpenCV 3.x.
Below is a sample code it works in OpenCV 3 which uses cv2.VideoCapture class.
import numpy as np
import cv2
# Open a sample video available in sample-videos
vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4')
#if not vcap.isOpened():
# print "File Cannot be Opened"
while(True):
# Capture frame-by-frame
ret, frame = vcap.read()
#print cap.isOpened(), ret
if frame is not None:
# Display the resulting frame
cv2.imshow('frame',frame)
# Press q to close the video windows before it ends if you want
if cv2.waitKey(22) & 0xFF == ord('q'):
break
else:
print "Frame is None"
break
# When everything done, release the capture
vcap.release()
cv2.destroyAllWindows()
print "Video stop"
You may check this Getting Started with Videos tutorial for more information.
Hope this help.
You will have to read the video using VideoCapture. there is no other way around that for now. unless you define it yourself.
remember a video is a combination of images changing at defined frame rate.
So You can read each frame in a while loop. as you apply the imdecode function.
import numpy as np
import cv2
cap = cv2.VideoCapture('https://www.example.com/myimage.mp4')
while(cap.isOpened()):
ret, image = cap.read()
loadedImage = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('frame',loadedImage)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

python - Output by OpenCV VideoWriter empty

I have recently started to program with opencv-python, but I got stuck when I tried to write a video using cv2. The output by the script is empty. Here's my code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'h263')
out = cv2.VideoWriter('cv2_camera_output.mp4',fourcc, 20.0, (800,600))
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
cv2.imshow('gray', gray)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
I guessed that the issue must have something to do with the fourcc codec. So I googled if there was a fourCC codec for mac (I am using OS X 10.12.3 (Sierra)), but all the suggestions didn't work for my computer, so the issue may not even be in the fourCC codec. These are the links I have visited:
OpenCV Documentation (I didn't follow this one, it was just to make sure, and it didn't work either)
GitHub Tests for FourCC codecs on OS X
Does anybody know the real issue? Any help would be great
Your frame width and height must be the same as the width and height of your VideoWriter. Just add this before out.write(frame) and you might be fine:
frame = cv2.resize(frame,(800,600))
Or change the size of your VideoWriter to the initial size of webcam frame. Mine is (640,480). I think if your OS doesn't support the format, it just won't write anything. Not even an empty file will be created. I'm on Linux and I think 'h263' doesn't work on it but 'h264' does. When I use 'h263' it just doesn't make any file.
I solved the problem. The problem simply was that I could not use the VideoWriter for grayscale, so I had to use it for the coloured frame.
Biggest problem is that h263 specifies the exact frame sizes it can encode (take a look at the possible values at https://en.wikipedia.org/wiki/H.263#Version_1_and_Annex_I) and you don't comply with that.
After resolving this issue it is possible that h263 still won't work with mp4 container on OSX (on Linux and Windows it doesn't because they use FFMPEG as backends but OSX uses another library) so I suggest that you use avi as container.
And lastly you will have to either resize your image (just like #ROAR said) or use the dimensions of the input device like this:
width = int(cap.get(3))
height = int(cap.get(4))
Although if you do the latter with h263 codec than you have to use an input device which produces frames that are compliant with the size restrictions.
My problem was actually that I did not have space left on my disk. It not did give a warning.

Categories

Resources