Saving video as series of images opencv - visual-studio-2010

This question is in continuation of error-in-opencv-code-for-motion-detection. The editted code works without any errors but the output video is not created,it is of zero bytes!What is wrong in this?Also,the bounding box created for motion detection never really captures the motion that is, it does not do what it originally claimed to do.Am I misunderstanding something about the objective of thie code?So, here are my questions:
How to rectify the creation and save the video?
What needs to be modified to detect motion and track it?
How to convert the video to a series of numbered jpg images from each frame and vice-versa.

Here is the code which you can work with to frame a video as a set of images.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cv.h"
#include <highgui.h>
#include "cxcore.h"
int main( int argc, char** argv )
{
CvCapture *capture = cvCaptureFromAVI("E:\\Myvideo.avi");
if(!capture)
{
printf("!!! cvCaptureFromAVI failed (file not found?)\n");
return -1;
}
int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
printf("* FPS: %d\n", fps);
IplImage* frame = NULL;
int frame_number = 0;
char key = 0;
while (key != 'q')
{
// get frame
frame = cvQueryFrame(capture);
if (!frame)
{
printf("!!! cvQueryFrame failed: no frame\n");
break;
}
// quit when user press 'q'
key = cvWaitKey(1000 / fps);
}
// free resources
cvReleaseCapture(&capture);
return 0;
}

Related

XShmGetImage fails without any error displayed

I have tried below simple program to use XShmGetImage to get the desktop image.
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <X11/extensions/XShm.h>
#include <X11/extensions/Xfixes.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(int argc, const char *argv[])
{
int screen;
Window root;
Display* display;
XImage* img,
int shm=0;
XShmSegmentInfo shminfo;
/* My Desktop Screen Resolution */
int width=1360;
int height=768;
display = XOpenDisplay(getenv("DISPLAY"));
shm = XShmQueryExtension(display);
if ( shm) {
printf ("Ha... QueryExtension Successful..\n");
int scr = XDefaultScreen (display);
printf ("\n Screen Number is %d ", scr);
img = XShmCreateImage (display, DefaultVisual(display, scr),
DefaultDepth ( display, scr),
ZPixmap,
NULL,
&shminfo,
width,
height);
printf ("\n Bytes Per Line %d ", img->bytes_per_line);
shminfo.shmid = shmget (IPC_PRIVATE, img->bytes_per_line * img->height, IPC_CREAT | 0777);
if ( shminfo.shmid == -1 ) {
printf ("\n Can not get the shared Memory ...");
} else {
printf ("\n Greate I am able to get shared memory..");
}
shminfo.shmaddr = img->data =shmat (shminfo.shmid, 0,0);
shminfo.readOnly = False;
if (!XShmAttach (display, &shminfo)) {
printf ("\n i am unable to attach now..");
} else {
printf ("\n Super.. i am able to attach Shared memory to extension ");
}
if ( !XShmGetImage (display, RootWindow(display, DefaultScreen(display)), img, 0,0, AllPlanes)){
printf ("\n Now you should have your image in XImage");
} else {
printf ("\n Ooops.. Something wrong.");
}
}
Output:
Ha... QueryExtension Successful..
Screen Number is 0
Bytes Per Line 5440
Greate I am able to get shared memory..
Super.. i am able to attach Shared memory to extension
Ooops.. Something wrong.
Unfortunately, XShmGetImage fails, and no information is displayed. Please help.
There was a blunder from my side. Actually, it works properly, and I misinterpreted the return value of XShmGetImage API().
The correct one is
if ( !XShmGetImage (display, RootWindow(display, DefaultScreen(display)), img, 0,0, AllPlanes)){
printf ("\n Ooops.. Something wrong.");
} else {
printf ("\n Now you should have your image in XImage");
}

PIC to PIC UART communication to Blink the LED

I want to send a command by PIC12F1572 to another PIC12F1572 through UART
and in that I want to send a function which will blink the LED on the slave PIC.
I have done some code but I am somewhat confusing
can anyone help me here?
P.S- I am Using MPLAB X IDE v3.50
Master/Transmitter PIC12F1572:
#include <xc.h>
#include "main.h"
#include "config.h"
#include "TYPEDEF_Definitions.h"
#include "PIC_12_Timer0.h"
#include "PIC_12_UART.h"
#include "System_init.h"
#include "Pin_manager.h"
#include "LED.h"
#define _XTAL_FREQ 16000000
void main()
{
SYSTEM_Initialize();
//pin_config();
LATA = 0x00;
UART_Init(); //Initialize UART
// StartLedBlinkingWithColor(color);
TRISAbits.TRISA2 = 1; //make RA2 as input
while (1)
{
//LATAbits.LATA2 = 1;
uint8_t Var = 0x61;
//uint8_t Var = LATAbits.LATA2;
if(TXSTAbits.TRMT == 1)
{
UART_write(LED_Blink()); // is it possible?? or how it will be possible
// __delay_ms(1000);
}
LATAbits.LATA2 = 1;
}
}
void LED_Blink()
{
LATAbits.LATA2 = 1;
LATAbits.LATA5 = 1;
__delay_ms(1000);
LATAbits.LATA2 = 0;
LATAbits.LATA5 = 0;
}
RECEIVER/SLAVE PIC12F1572:
#include <xc.h>
#include "config.h"
#include "PIC_12F_GPIO.h"
#include "Led.h"
#include "Interruptmanage.h"
#include "PIC_12F_UART.h"
#include "PIC_12F_TIMER0.h"
#include "main.h"
void main( void)
{
uint8 data;
InterruptInit();
TIMER0_Init();
UART_Init();
InitLeds(); // here I init GPIO pin..no prb here
// SetLedOff();
/*-------------R E C E I V E R*------------*/
while (1)
{ // Endless loop
if (UART_DataReady() ) // I get prob here ..
{
PORTA = UART_ReadOneByte(); // read the received data, [how can I receive my Led_Blink() function??
LATAbits.LATA2 = 1;
//LATAbits.LATA2 = data;
//SendByteSerially(data);
}
}
}
There are a couple of things to consider:
You cannot "send a function" through the UART. Therefore, the LED_Blink() function needs to be on the receiver side. Before doing anything else, verify that the function works on the receiver side, without any UART interaction.
Next, you can define a protocol, which is basically deciding which byte values you send through the UART should trigger the LED_Blink() call on the receiver side. For example, if you decide to use the byte value of 42 to trigger a LED blink, your sender would call UART_write(42) and on the receiver side, you would have something like the following:
data = UART_ReadOneByte();
if (data == 42) {
LED_Blink();
}
So for Receiving data from UART and saving it in array and use the data to vlink nthe LED I Have done this code: Anyone interested can have a look
while (1)
{
if (EUSART_DataReady)
{
for (i = 0; i<FRAMESIZE; i++) //#define FRAMESIZE 19
{
RX_Buffer[i] = EUSART_Read();
if (RX_Buffer[i] == '\n') //check'\n' in the end of frame
break;
}
RX_Buffer[i] = '\n'; //append '\n' at the end of stoaring array for detection of frame
RX_Buffer[i+1] = '\0'; // End of an array
EUSART_WriteAnArrayOfBytes(RX_Buffer);
if(RX_Buffer[0]=='R' && RX_Buffer[FRAMESIZE-2] == '\n') //check for correct frame
{
LATAbits.LATA2 = 1;
__delay_ms(2000);
LATAbits.LATA2 = 0;
__delay_ms(1000);
}
}
}

Get Pixmap out of Xlib

I've been trying to find a way of grabbing video directly from an X window and got pointed to Xlib and the compositing extension.
So far, I've been able to listen to change events and grab a Pixmap with this code:
#include <X11/Intrinsic.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xdamage.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char ** argv) {
int br, base;
Window win = 0x3400003;
Display *dsp = XOpenDisplay(0);
XCompositeQueryExtension(dsp, &base, &br);
XDamageQueryExtension(dsp,&base, &br);
cout << base << endl;
Damage damage = XDamageCreate(dsp, win, XDamageReportRawRectangles);
XCompositeRedirectWindow(dsp, win, CompositeRedirectAutomatic);
XEvent ev;
while(true) {
XNextEvent(dsp, &ev);
if(ev.type == base + XDamageNotify) {
Pixmap pm = XCompositeNameWindowPixmap(dsp, win);
XWindowAttributes attr;
XGetWindowAttributes(dsp, win, &attr);
XWriteBitmapFile(dsp, "test.bmp", pm, attr.width, attr.height, -1, -1);
return 0;
}
}
XCompositeUnredirectWindow(dsp, win, CompositeRedirectAutomatic);
XDamageDestroy(dsp, damage);
return 0;
}
The problem here is that the resulting bmp (created by XWriteBitmapFile) is black&white horribleness. Disregarding the fact that I don't want to write the data to file anyway, I am apparently doing something wrong in reading it.
I would love to convert the Pixmap to either a framebuffer in opengl or a binary blob in ram.
Thanks in advance for any help you can give me on this.
Best regards.
"Bitmaps" in X world refer to two-colored images. I guess XWriteBitmapFile does internally GetImage request and transforms server pixmap to a bitmap. Note that file format is it's own 'X11 bitmap', not windows bitmap.
Use XGetImage function If you actually need image's binary blob.

Getting process base address in Mac OSX

I'm trying to read the memory of a process using task_for_pid / vm_read.
uint32_t sz;
pointer_t buf;
task_t task;
pid_t pid = 9484;
kern_return_t error = task_for_pid(current_task(), pid, &task);
vm_read(task, 0x10e448000, 2048, &buf, &sz);
In this case I read the first 2048 bytes.
This works when I know the base address of the process (which I can find out using gdb "info shared" - in this case 0x10e448000), but how do I find out the base address at runtime (without looking at it with gdb)?
Answering my own question. I was able to get the base address using mach_vm_region_recurse like below. The offset lands in vmoffset. If there is another way that is more "right" - don't hesitate to comment!
#include <stdio.h>
#include <mach/mach_init.h>
#include <sys/sysctl.h>
#include <mach/mach_vm.h>
...
mach_port_name_t task;
vm_map_offset_t vmoffset;
vm_map_size_t vmsize;
uint32_t nesting_depth = 0;
struct vm_region_submap_info_64 vbr;
mach_msg_type_number_t vbrcount = 16;
kern_return_t kr;
if ((kr = mach_vm_region_recurse(task, &vmoffset, &vmsize,
&nesting_depth,
(vm_region_recurse_info_t)&vbr,
&vbrcount)) != KERN_SUCCESS)
{
printf("FAIL");
}
Since you're calling current_task(), I assume you're aiming at your own process at runtime. So the base address you mentioned should be the dynamic base address, i.e. static base address + image slide caused by ASLR, right? Based on this assumption, you can use "Section and Segment Accessors" to get the static base address of your process, and then use the dyld functions to get the image slide. Here's a snippet:
#import <Foundation/Foundation.h>
#include </usr/include/mach-o/getsect.h>
#include <stdio.h>
#include </usr/include/mach-o/dyld.h>
#include <string.h>
uint64_t StaticBaseAddress(void)
{
const struct segment_command_64* command = getsegbyname("__TEXT");
uint64_t addr = command->vmaddr;
return addr;
}
intptr_t ImageSlide(void)
{
char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) != 0) return -1;
for (uint32_t i = 0; i < _dyld_image_count(); i++)
{
if (strcmp(_dyld_get_image_name(i), path) == 0)
return _dyld_get_image_vmaddr_slide(i);
}
return 0;
}
uint64_t DynamicBaseAddress(void)
{
return StaticBaseAddress() + ImageSlide();
}
int main (int argc, const char *argv[])
{
printf("dynamic base address (%0llx) = static base address (%0llx) + image slide (%0lx)\n", DynamicBaseAddress(), StaticBaseAddress(), ImageSlide());
while (1) {}; // you can attach to this process via gdb/lldb to view the base address now :)
return 0;
}
Hope it helps!

boost.log auto_flush files are not stored when app is crashed

Recently I started to play with boost.log, and bumped into an issue that if an unhanded exception is thrown no log messages are written to the log file. I am using rolling text files and auto-flash option is set on.
Here is the modified source from the samples:
#include <stdexcept>
#include <string>
#include <iostream>
#include <fstream>
#include <functional>
#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/log/common.hpp>
#include <boost/log/filters.hpp>
#include <boost/log/formatters.hpp>
#include <boost/log/attributes.hpp>
#include <boost/log/sinks.hpp>
#include <boost/log/utility/empty_deleter.hpp>
#include <boost/log/utility/record_ordering.hpp>
namespace logging = boost::log;
namespace attrs = boost::log::attributes;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace fmt = boost::log::formatters;
namespace keywords = boost::log::keywords;
using boost::shared_ptr;
using namespace boost::gregorian;
enum
{
LOG_RECORDS_TO_WRITE = 100,
LOG_RECORDS_TO_WRITE_BEFORE_EXCEPTION = 10,
THREAD_COUNT = 10
};
BOOST_LOG_DECLARE_GLOBAL_LOGGER(test_lg, src::logger_mt)
//! This function is executed in multiple threads
void thread_fun(boost::barrier& bar)
{
// Wait until all threads are created
bar.wait();
// Here we go. First, identify the thread.
BOOST_LOG_SCOPED_THREAD_TAG("ThreadID", boost::thread::id, boost::this_thread::get_id());
// Now, do some logging
for (unsigned int i = 0; i < LOG_RECORDS_TO_WRITE; ++i)
{
BOOST_LOG(get_test_lg()) << "Log record " << i;
if(i > LOG_RECORDS_TO_WRITE_BEFORE_EXCEPTION)
{
BOOST_THROW_EXCEPTION(std::exception("unhandled exception"));
}
}
}
int main(int argc, char* argv[])
{
try
{
typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink;
shared_ptr< file_sink > sink(new file_sink(
keywords::file_name = L"%Y%m%d_%H%M%S_%5N.log", // file name pattern
keywords::rotation_size = 10 * 1024 * 1024, // rotation size, in characters
keywords::auto_flush = true // make each log record flushed to the file
));
// Set up where the rotated files will be stored
sink->locked_backend()->set_file_collector(sinks::file::make_collector(
keywords::target = "log" // where to store rotated files
));
// Upon restart, scan the target directory for files matching the file_name pattern
sink->locked_backend()->scan_for_files();
sink->locked_backend()->set_formatter(
fmt::format("%1%: [%2%] [%3%] - %4%")
% fmt::attr< unsigned int >("Line #")
% fmt::date_time< boost::posix_time::ptime >("TimeStamp")
% fmt::attr< boost::thread::id >("ThreadID")
% fmt::message()
);
// Add it to the core
logging::core::get()->add_sink(sink);
// Add some attributes too
shared_ptr< logging::attribute > attr(new attrs::local_clock);
logging::core::get()->add_global_attribute("TimeStamp", attr);
attr.reset(new attrs::counter< unsigned int >);
logging::core::get()->add_global_attribute("Line #", attr);
// Create logging threads
boost::barrier bar(THREAD_COUNT);
boost::thread_group threads;
for (unsigned int i = 0; i < THREAD_COUNT; ++i)
threads.create_thread(boost::bind(&thread_fun, boost::ref(bar)));
// Wait until all action ends
threads.join_all();
return 0;
}
catch (std::exception& e)
{
std::cout << "FAILURE: " << e.what() << std::endl;
return 1;
}
}
Source is compiled under Visual Studio 2008. boost.log compiled for boost 1.40.
Any help is highly appreciated.
Check to see if the log file is in the current working directory of the process, rather than the specified file collector target directory ("log" in your sample code). Additionally, you will probably want to specify a directory for the sink "file_name" pattern.
As "JQ" notes, don't expect to see any logging post-exception.

Resources