OpenCV -- Function to grab frame - opencv

I'm trying to create a function that gives the frame at the moment the function is called. So when i call the function, it should give the picture of the object that is in front of the camera at the moment the function is called.
I have been trying for hours, but i can't succeed. Anyone?
main file:
#include "camera.h"
#include <iostream>
#include <unistd.h>
int main(int argc, const char *argv[])
{
Camera cam;
cam.setVideoSource(0);
cv::Mat image;
cv::Mat image2;
cam.openCamera();
cam.grabFrame(image); // grap first frame
sleep(5); // wait 5 seconds
cam.grabFrame(image2); // capture seconds frame
cv::namedWindow("1",CV_WINDOW_KEEPRATIO);
cv::imshow("1",image);
cv::namedWindow("2",CV_WINDOW_KEEPRATIO);
cv::imshow("2",image2);
cv::waitKey();
return 0;
}
camera.h file
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
class Camera{
private:
int videoSource; //video source
cv::VideoCapture cap; //capture of camera
public:
//constructor default videoSourceNumber
Camera() : videoSource(0) {};
//Setter: videoSourceNumber
void setVideoSource(int sourceNumber){
videoSource = sourceNumber;
}
//function OPEN CAMERA
//opens the video capture
//returns true if successfull
bool openCamera() {
cap.open(videoSource);
if (!cap.isOpened()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
//function GRAB FRAME
//grabs the frame of the video capture
//returns true if successfull
bool grabFrame(cv::Mat& cameraFrame){
cap >> cameraFrame;
if (cameraFrame.empty()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
};

A somewhat unsatisfying solution:
//function GRAB FRAME
//grabs the frame of the video capture
//returns true if successfull
bool grabFrame(cv::Mat& cameraFrame){
int attempts = 0;
do {
cap >> cameraFrame;
attempts++;
} while (cameraFrame.empty() && attempts < 10);
if (cameraFrame.empty()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
I also played with this for a while and could not find a solution. My instinct was to give the camera more "warm-up" time before asking for the first frame. A sleep of 10 seconds seems to do so reliably, but that is not acceptable. If I don't give it any sleep before the first grabFrame() call, the while loop I added only seems to run twice.
Credit to: https://stackoverflow.com/a/9285151/2518451

Related

opencv imread exit code 0xC0000409

The code is:
#include <iostream>
#include <opencv2/opencv.hpp>
int main (int argc, char** argv) {
auto path = "C:/Users/huhua/Pictures/11.jpg";
auto img = cv::imread(path);
if (img.empty()) {
std::cout << "is empty" << std::endl;
return 1;
}
cv::imshow("demo", img);
cv::waitKey(0);
return 0;
}
The 11.jpg exist. And if I use another 11.bmp. It works well.
After debug. The error is throw at libjpeg-trubo/src/jdatasr.c
fill_input_buffer(j_decompress_ptr cinfo)
{
my_src_ptr src = (my_src_ptr)cinfo->src;
size_t nbytes;
// error is throw at here
nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
// ...
}
Is my libjpeg issue??
How to fix this?
The 11.jpg image:
Update:
The OpenCV info
Update on 2021/10/19:
The reason is I set the cmake_toolchain_path after project(xxx). I should set the cmake_toolchain_path before project.
https://github.com/microsoft/vcpkg/discussions/20802

Alternative to waitKey() for updating window in OpenCV

All examples and books I've seen so far recommends using waitKey(1) to force repaint OpenCV window. That looks weird and too hacky. Why wait for even 1ms when you don't have to?
Are there any alternatives? I tried cv::updateWindow but it seems to require OpenGL and therefore crashes. I'm using VC++ on Windows.
I looked in to source and as #Dan Masek said, there doesn't seem to be any other functions to process windows message. So I ended up writing my own little DoEvents() function for VC++. Below is the full source code that uses OpenCV to display video frame by frame while skipping desired number of frames.
#include <windows.h>
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
bool DoEvents();
int main(int argc, char *argv[])
{
VideoCapture cap(argv[1]);
if (!cap.isOpened())
return -1;
namedWindow("tree", CV_GUI_EXPANDED | CV_WINDOW_AUTOSIZE);
double frnb(cap.get(CV_CAP_PROP_FRAME_COUNT));
std::cout << "frame count = " << frnb << endl;
for (double fIdx = 0; fIdx < frnb; fIdx += 50) {
Mat frame;
cap.set(CV_CAP_PROP_POS_FRAMES, fIdx);
bool success = cap.read(frame);
if (!success) {
cout << "Cannot read frame " << endl;
break;
}
imshow("tree", frame);
if (!DoEvents())
return 0;
}
return 0;
}
bool DoEvents()
{
MSG msg;
BOOL result;
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
result = ::GetMessage(&msg, NULL, 0, 0);
if (result == 0) // WM_QUIT
{
::PostQuitMessage(msg.wParam);
return false;
}
else if (result == -1)
return true; //error occured
else
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
return true;
}

Error while capturing video for a pre-defined time period

This program captures video until I press Esc. But I need to modify this program and capture video for 30s.
After recording the video it plays very fast and the video length reduces. I tried to add waitKey at the end, but it still doesn't work. After recording the video length should be the same. How can I do that? Any suggestions?
int main( int argc, const char** argv )
{
using namespace std;
using namespace cv;
VideoCapture cap(0);
while(!(cap.isOpened() && cap.grab()))
{
cout << "Camera not ready" << endl;
}
VideoWriter Writer("D:/MyVideo.avi", CV_FOURCC('P','I','M','1'),20,Size(640,480), true);
while (waitKey(30)!= 27)
{
Mat frame;
cap >> frame;
Writer.write(frame);
imshow("D:/MyVideo", frame);
}
}
int64 t0 = cv::getTickCount();
while (waitKey(30)!= 27)
{
Mat frame;
cap >> frame; // read a new frame from video
Writer.write(frame); //writer the frame into the file
double t = (cv::getTickCount() - t0) / cv::getTickFrequency();
if (t > 30)
break;
...
// now, we need to adjust to the desired framerate of 20fps,
// so we need to sleep for 1000/20 = 50 milliseconds
// either have a window, and use waitKey():
// imshow("lalala", frame);
// waitKey(50);
// or just sleep(), unfortunately system dependant ;(
// win:
// Sleep(50);
// linux, etc.:
// usleep(50);
}

saving an image sequence from video using opencv2

Newbie question and yes I have spent a lot of time sifting through similar questions and Answers with no luck.
What I am trying to do is save frames from a video file in a sequential order. I have managed to save one image using c and I cannot seem to save images after that. I have started using c++ in opencv instead of c and all I can do is view the video and not save any jpg's from it.
I am using opencv2.4.4a on mac if that helps.
below is my c example
#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
int main (int argc, char** argv)
{
//initializing capture from file
CvCapture * capture = cvCaptureFromAVI ("/example/example.mov");
//Capturing a frame
IplImage* img = 0;
if(!cvGrabFrame(capture)) //capture a frame
{
printf)Could not grab a fram\n\7");
exit(0);
}
img=cvRerieveFrame(capture); //retrieve the captured frame
//writing an image to a file
if (!cvSaveImage("/frames/test.jpg", img))
printf("Could not save: %s\n","test.jpg");
//free resources
cvReleaseCapture(&capture);
}
Thank you in advance
edit to the above.
I have added to the above code which results in an image to be saved with the test.jpg and then gets rewritten with the next frame. How do I tell opencv to not copy over the last image and rename the next frame to test_2.jpg eg, test_1.jpg, test_2.jpg and so on?
double num_frames = cvGetCaptureProperty (capture, CV_CAP_PROP_FRAME_COUNT);
for (int i = 0; i < (int)num_frames; i++)
{
img = cvQueryFrame(capture);
cvSaveImage("frames/test.jpg", img);
}
cvReleaseCapture(&capture);
}
This is my code... I tryed a lot and finally made it
this is c++ using opencv 3... hope it works
#include "opencv2/opencv.hpp"
#include <sstream>
#include <iostream>
using namespace cv;
using namespace std;
Mat frame,img;
int counter;
int main(int,char**)
{
VideoCapture vid("video3.avi");
while (!vid.isOpened())
{
VideoCapture vid("video2.MOV");
cout << "charging" << endl;
waitKey(1000);
}
cout << "Video opened!" << endl;
while(1)
{
stringstream file;
vid.read(frame);
if(frame.empty()) break;
file << "/home/pedro/workspace/videoFrame/Debug/frames/image" << counter << ".jpg";
counter++;
imwrite(file.str(),frame);
char key = waitKey(10);
if ( key == 27)
{break;}
}
}
Use an index that will keep track of the number part in the filename. In the image capturing loop, add the index with the filename and build the final filename.
here is an example :
while(1)
{
cap.read ( frame);
if( frame.empty()) break;
imshow("video", frame);
char filename[80];
sprintf(filename,"C:/Users/cssc/Desktop/testFolder/test_%d.png",i);
imwrite(filename, frame);
i++;
char key = waitKey(10);
if ( key == 27) break;
}
This is my way to do in Python3.0. Have to have CV2 3+ version for it to work.
This function saves images with frequency given.
import cv2
import os
print(cv2.__version__)
# Function to extract frames
def FrameCapture(path,frame_freq):
# Path to video file
video = cv2.VideoCapture(path)
success, image = video.read()
# Number of frames in video
fps = int(video.get(cv2.CAP_PROP_FPS))
length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
print('FPS:', fps)
print('Extracting every {} frames'.format(frame_freq))
print('Total Frames:', length)
print('Number of Frames Saved:', (length // frame_freq) + 1)
# Directory for saved frames
try:
frame_dir = path.split('.')[0]
os.mkdir(frame_dir)
except FileExistsError:
print('Directory ({}) already exists'.format(frame_dir))
# Used as counter variable
count = 0
# checks whether frames were extracted
success = 1
# vidObj object calls read
# function extract frames
while count < length :
video.set(cv2.CAP_PROP_POS_FRAMES , count)
success, image = video.read()
# Saves the frames with frame-count
cv2.imwrite(frame_dir + "/frame%d.jpg" % count, image)
count = count + frame_freq

After reading multiple frames from a camera, OpenCV suddenly always fails to read frames. How do I diagnose this?

I run a program similar to the one in this question: https://stackoverflow.com/a/8719192/26070
#include <opencv/highgui.h>
#include <iostream>
/** #function main */
int main( int argc, char** argv )
{
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://192.0.0.1:8081/live.sdp";
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey(500);
} else {
cv::imshow("Output Window", image);
}
if(cv::waitKey(1) >= 0) break;
}
}
The program runs fine for a certain amount of time (about one minute or so) and then the call to read() (method from cv::VideoCapture) always returns false.
The output is as follows:
[mpeg4 # 00da27a0] ac-tex damaged at 22 7
[mpeg4 # 00da27a0] Error at MB: 309
No frame
No frame
No frame
Note: the first two lines are not always present.
So, how can I determine what the root of the problem is?

Resources