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()
Related
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.
First my Setup:
Windows 10, Asus Notebook, Logitech C920 HD Pro Webcam, Opencv-Python 3.4.4.19
When I manually take a photo with the webcam using the Windows 10 Camera App, it is sharp.
But if I program a code in Python and use OpenCV the taken photo is blurred (unsharp).
When I press the space bar, a photo is taken.
I already tried to play with the contrast, brightness and FPS. Unfortunately this didn't lead to any result.
import cv2
import os
cam = cv2.VideoCapture(1)
cv2.namedWindow("test")
cam.set(3, 1920)
cam.set(4, 1080)
img_counter = 0
myfile="XXX"
if os.path.isfile(myfile):
os.remove(myfile)
else:
print("Error: %s file not found" % myfile)
while True:
ret, frame = cam.read()
cv2.imshow("test", frame)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
print("Escape hit, closing...")
break
elif k%256 == 32:
img_name = "Bild{}.png".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
img_counter += 1
cam.release()
cv2.destroyAllWindows()
Are there settings for OpenCv to get the image sharper?
In the final stage I have 3 cameras which automatically take a photo one after the other.
Unsharp Image (OpenCV)
Sharp Image (Windows 10 Kamera App)
Image cv2.imshow
Typical camera pipelines have a sharpening filter applied to remove the effect of blurring caused by the scene being out of focus, or poor optics.
My guess is that OpenCV is capturing the image closer to "raw" without adding the sharpening filter. You should be able to add a sharpening filter yourself. You can tell when a sharpening filter is applied as there will be a "ringing" artifact around high contrast edges.
I am currently using OpenCV in python to read from a video .mp4 file which is ~300kb in size, 1min and 20sec long. I have noticed that if I read each frame from the file, and write said frame to a new file using OpenCV's functionalities, my new video copy is ~50Mb... can someone explain how this is possible and how to fix it?
The codec for both files is the same: H.264
Below is the code:
import numpy as np
import cv2
cap = cv2.VideoCapture('/Users/video.mp4')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv2.VideoWriter('output.mp4',fourcc, 50.0, (160, 210))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
I am a beginner to python.
I want to read frame from avi files and I write following code.When I run this code I get the message like Segmentation fault (core dumped).
Could anyone tell me the reason.
I am sure I have used the right root of the avi file.
I try to find the problem by ipython. I found the error occured when reach the line of ret, frame = cap.read().
import numpy as np
import cv2
cap = cv2.VideoCapture('/home/sunjia/code/night_goto.avi')
while(cap.isOpened()):
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()
Change While condition
while(ret):
Try this !!
**** Correction ****
before while loop add this statement: ret, frame = cap.read()
.read() will return two parameters: the frame and boolean: 'True' if there is any frame in the read file or 'False' if there is no frame. This way 'ret' will be initialized and can be used for 'while()'.
Now, the while() loop will run till the statement "ret, frame = cap.read()" in the loop returns parameters.
I have two pieces of codes. Here is the first one. It was mainly copied from save a video section on OpenCV-Python tutorial website, but I modified a little bit.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
cap.set(7,200)
out = cv2.VideoWriter('output.avi',cv2.cv.CV_FOURCC('X','V','I','D'), 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
Second one is here:
import cv
cv.NamedWindow('camera',1)
cap = cv.CaptureFromCAM(0)
fps = 20
fourcc = cv.CV_FOURCC('X','V','I','D')
cv.SetCaptureProperty(cap,cv.CV_CAP_PROP_FRAME_COUNT,200)
out = cv.CreateVideoWriter('output.avi',fourcc,fps,(640,480))
while True
img = cv.QueryFrame(out,img)
cv.WriteFrame(out,img)
cv.ShowImage('camera',img)
if cv.WaitKey(1) & 0xFF == ord('q'):
break
cv.DestroyAllWindows()
Neither of them can make a video file saved or destroy the window in the end. No errors occurred in shell after running the code. I used Python 2.7.6 and OpenCV 2.3.1. Can somebody help me? Thanks a lot.
PS: I am not sure whether my method to set frame numbers correct or not.
It may have several reasons. Check the following:
Check that you can encode with XVID, maybe try with MJPEG first.
Set width and height of your input video by cap.set(3,640) and cap.set(4,480)