I have a dataset containing several videos in .mp4 format stored in a source directory. I want to resize the frames of every video and store in destination directory. I am running a for loop to get every video from source and extract each frame, resize and write in a video and store in destination. But I'm stuck at the VideoCapture part. As far as my knowledge the path is correctly given. Here is the code and the error
`import cv2
import numpy as np
import os
source="C:\\Users\\Desktop\\sourcedir"
dest=r"C:\Users\Desktop\dest"
def frame_capture(file):
path=dest+'\\'+file
so=source+'\\'+file
result = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'mp4v'), 25, (227,227))
cap = cv2.VideoCapture(so)
if(cap.isOpened()==False):
print("Unable to open file")
currentFrame = 0
while(True):
# Capture frame by frame
ret, frame = cap.read()
# resize frame
frame=cv2.resize(frame,(227,227))
result.write(frame)
# To stop duplicate images
currentFrame += 1
cap.release()
cv2.destroyAllWindows()
for file in os.listdir(source):
frame_capture(file)
`
OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\resize.cpp:4052: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize
Need help
Related
I'd like to save video camera output in motion JPEG (MJPG) format. The below code,
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
frame_per_sec = int('10')
out = cv2.VideoWriter('output.mjpeg',cv2.VideoWriter_fourcc('M','J','P','G'), (frame_per_sec), (frame_width,frame_height))
while(True):
ret, frame = cap.read()
if ret == True:
# Write the frame into the file 'output.mjpeg'
out.write(frame)
# Display the resulting frame
cv2.imshow('frame',frame)
# Press Q on keyboard to stop recording
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
While it will run, I am getting the following error(s),
[ WARN:0] OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1
OpenCV: FFMPEG: tag 0x67706a6d/'mjpg' is not supported with codec id 7 and format 'mjpeg / raw MJPEG video'
What can I do to resolve these? I've tried changing the case, ('M','J','P','G' to 'm','j','p','g') with no success.
Appreciate any suggestions regarding resolving the above issue, as well as the GStreamer issue. Thanks in advance.
.mjpeg is not a valid suffix for any known container format.
I'm sure you didn't intend to write a raw MJPG stream without a container. That is very very rarely useful at all and requires expert knowledge.
You have two options:
use MJPG in a .avi container, because that's built into OpenCV and doesn't even require ffmpeg
use whatever ffmpeg understands, which would be a .mpg container, or .mov or .mkv or whatever else
When Try For One video file . this is working but I need to display the unknown or non-fixed number of video files
I tried os.listdir for loop But I couldnt make it run in a function
I need to send different video paths when First video ends everytime with in order and in infinite loop
cap=VideoCapture(path)
while (cap.IsOpened()):
ret, frame = cap.read()
if ret:
cv2.imshow('frame',frame)
else:
print('Not found')
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
if(cv2.waitKey(1) & 0xFF == ord('q')):
break
cap.release()
cv2.destroyAllWindows()
Use glob.glob() to get the list of files you want to open.
Each time one video ends, you should close the VideoCapture and open a new one.
from glob import glob
videolist = sorted(glob(r"videoexamplefolder\*.mp4")) # modify as needed
for video in videolist:
cap=VideoCapture(video)
# ...
I am trying to make this videocapture opencv2 python script allow me to do multiple video streams from my laptop cam and USB cams and I succeeded (with help of youtube) to do so only every time I add a camera I have to edit the line of code and add another videocapture line and another frame and another cv2.imshow. But I want to edit the video capture code in a way that allows me to stream as many cameras as detected without the need to add a line every time there is a camera using a loop. I'm obviously new here so accept my apologies if the solution is too simple.
This is the code that allows me to stream multiple cameras but with adding a line for each camera.
import urllib.request
import time
import numpy as np
import cv2
# Defining URL for camera
video_capture_0 = cv2.VideoCapture(0)
video_capture_1 = cv2.VideoCapture(1)
while True:
# Capture frame-by-frame
ret0, frame0 = video_capture_0.read()
ret1, frame1 = video_capture_1.read()
if (ret0):
# Display the resulting frame
cv2.imshow('Cam 0', frame0)
if (ret1):
# Display the resulting frame
cv2.imshow('Cam 1', frame1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture_0.release()
video_capture_1.release()
cv2.destroyAllWindows()
I tried making a list camlist = [i for i in range(100)] and then adding that to a for loop that keeps adding it to videocapture. But I believe that's a mess so I deleted the code plus that doesn't seem so effective.
If you want to work with many cameras then first you should keep them on list - and then you can use for-loop to get all frame. And frames you should also keep on list so later you can use for-loop to display them. And finally you can use for-loop to release cameras
import cv2
#video_captures = [cv2.VideoCapture(x) for x in range(2)]
video_captures = [
cv2.VideoCapture(0),
#cv2.VideoCapture(1),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/krupowki-srodek/latest.mp4'),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/krakow4/latest.mp4'),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/warszawa/latest.mp4'),
]
while True:
results = []
for cap in video_captures:
ret, frame = cap.read()
results.append( [ret, frame] )
for number, (ret, frame) in enumerate(results):
if ret:
cv2.imshow(f'Cam {number}', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
for cap in video_captures:
cap.release()
cv2.destroyAllWindows()
And now if you even add new camera to list then you don't have to change rest of code.
But for many cameras it is good to run every camera in separated thread - but still keep all on lists.
Few days ago was question: How display multi videos with threading using tkinter in python?
We're doing a project in school where we need to do basic image processing. Our goal is to use every video frame for the Raspberry Pi and do real time image processing.
We've tried to include raspistill in our python-program but so far nothing has worked. The goal of our project is to design a RC-car which follows a blue/red/whatever coloured line with help from image processing.
We thought it would be a good idea to make a python-program which does all image processing necessary, but we currently struggle with the idea of bringing recorded images into the python program. Is there a way to do this with picamera or should we try a different way?
For anyone curious, this is how our program currently looks
while True:
#camera = picamera.PiCamera()
#camera.capture('image1.jpg')
img = cv2.imread('image1.jpg')
width = img.shape[1]
height = img.shape[0]
height=height-1
for x in range (0,width):
if x>=0 and x<(width//2):
blue = img.item(height,x,0)
green = img.item(height,x,1)
red = img.item(height,x,2)
if red>green and red>blue:
OpenCV already contains functions to process live camera data.
This OpenCV documentation provides a simple example:
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()
Of course, you do not want to show the image but all your processing can be done there.
Remember to sleep a few hundred milliseconds so the pi does not overheat that much.
Edit:
"how exactly would I go about it though. I used "img = cv2.imread('image1.jpg')" all the time. What do I need to use instead to get the "img" variable right here? What do I use? And what is ret, for? :)"
ret indicates whether the read was successful. Exit program if not.
The read frame is nothing other than your img = cv2.imread('image1.jpg') so your detection code should work exactly the same.
The only difference is that your image does not need to be saved and reopened. Also for debugging purposes you can save the recorded image, like:
import cv2, time
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
if ret:
cv2.imwrite(time.strftime("%Y%m%d-%H%M%S"), frame)
cap.release()
You can use picamera to acquire images.
To make it "real time", you can acquire data each X milliseconds. You need to set X depending on the power of your hardware (and the complexity of the openCV algorithm).
Here's an example (from http://picamera.readthedocs.io/en/release-1.10/api_camera.html#picamera.camera.PiCamera.capture_continuous) how to acquire 60 images per second using picamera:
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
try:
for i, filename in enumerate(camera.capture_continuous('image{counter:02d}.jpg')):
print(filename)
time.sleep(1)
if i == 59:
break
finally:
camera.stop_preview()
I have the following code:
# Import packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
X_RESOLUTION = 640
Y_RESOLUTION = 480
# Initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (X_RESOLUTION, Y_RESOLUTION)
camera.framerate = 10
rawCapture = PiRGBArray(camera, size = (X_RESOLUTION, Y_RESOLUTION))
# Allow camera to warmup
time.sleep(0.1)
#Capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# Grab the raw NumPy array representing the image
image = frame.array
# Show the frame
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
# Clear the stream so it is ready to receive the next frame
rawCapture.truncate(0)
# If the 'q' key was pressed, break from the loop
if(key == ord('q')):
break
It is all fine and dandy. It captures video and displays it on my screen and it exits when I press 'q'. However, if I wanted to manipulate the frames somehow, say for example I wanted to set every pixels R value in each frame to 255 to make the image red. How would I do that?
My end goal is to write software that detects movement on a static background. I understand the theory and the actual data manipulation that needs to be done to make this happen, I just cant figure out how to access each frame's pixel data and operate on it. I attempted to change some values in 'image', but it says the array is immutable and cannot be written to, only read from.
Thanks for your time.
I have accessed each pixel{R,G,B values accessed separately } value randomly and have changed the value of it in the image. You can do it on an video by extracting each frame of it. It is implemented in c++ with opencv. Go through this link https://stackoverflow.com/a/32664968/3853072 you will get an idea.