Search Results

Search found 221 results on 9 pages for 'hmm'.

Page 1/9 | 1 2 3 4 5 6 7 8 9  | Next Page >

  • HMM for perspective estimation in document image, can't understand the algorithm

    - by maximus
    Hello! Here is a paper, it is about estimating the perspective of binary image containing text and some noise or non text objects. PDF document The algorithm uses the Hidden Markov Model: actually two conditions T - text B - backgrouond (i.e. noise) It is hard to understand the algorithm itself. The question is that I've read about Hidden Markov Models and I know that it uses probabilities that must be known. But in this algorithm I can't understand, if they use HMM, how do they get those probabilities (probability of changing the state from S1 to another state for example S2)? I didn't find anything about training there also in that paper. So, if somebody understands it, please tell me. Also is it possible to use HMM without knowing the state change probabilities?

    Read the article

  • Stored Procedures with SSRS? Hmm… not so much

    - by Rob Farley
    Little Bobby Tables’ mother says you should always sanitise your data input. Except that I think she’s wrong. The SQL Injection aspect is for another post, where I’ll show you why I think SQL Injection is the same kind of attack as many other attacks, such as the old buffer overflow, but here I want to have a bit of a whinge about the way that some people sanitise data input, and even have a whinge about people who insist on using stored procedures for SSRS reports. Let me say that again, in case you missed it the first time: I want to have a whinge about people who insist on using stored procedures for SSRS reports. Let’s look at the data input sanitisation aspect – except that I’m going to call it ‘parameter validation’. I’m talking about code that looks like this: create procedure dbo.GetMonthSummaryPerSalesPerson(@eomdate datetime) as begin     /* First check that @eomdate is a valid date */     if isdate(@eomdate) != 1     begin         select 'Please enter a valid date' as ErrorMessage;         return;     end     /* Then check that time has passed since @eomdate */     if datediff(day,@eomdate,sysdatetime()) < 5     begin         select 'Sorry - EOM is not complete yet' as ErrorMessage;         return;     end         /* If those checks have succeeded, return the data */     select SalesPersonID, count(*) as NumSales, sum(TotalDue) as TotalSales     from Sales.SalesOrderHeader     where OrderDate >= dateadd(month,-1,@eomdate)         and OrderDate < @eomdate     group by SalesPersonID     order by SalesPersonID; end Notice that the code checks that a date has been entered. Seriously??!! This must only be to check for NULL values being passed in, because anything else would have to be a valid datetime to avoid an error. The other check is maybe fair enough, but I still don’t like it. The two problems I have with this stored procedure are the result sets and the small fact that the stored procedure even exists in the first place. But let’s consider the first one of these problems for starters. I’ll get to the second one in a moment. If you read Jes Borland (@grrl_geek)’s recent post about returning multiple result sets in Reporting Services, you’ll be aware that Reporting Services doesn’t support multiple results sets from a single query. And when it says ‘single query’, it includes ‘stored procedure call’. It’ll only handle the first result set that comes back. But that’s okay – we have RETURN statements, so our stored procedure will only ever return a single result set.  Sometimes that result set might contain a single field called ErrorMessage, but it’s still only one result set. Except that it’s not okay, because Reporting Services needs to know what fields to expect. Your report needs to hook into your fields, so SSRS needs to have a way to get that information. For stored procs, it uses an option called FMTONLY. When Reporting Services tries to figure out what fields are going to be returned by a query (or stored procedure call), it doesn’t want to have to run the whole thing. That could take ages. (Maybe it’s seen some of the stored procedures I’ve had to deal with over the years!) So it turns on FMTONLY before it makes the call (and turns it off again afterwards). FMTONLY is designed to be able to figure out the shape of the output, without actually running the contents. It’s very useful, you might think. set fmtonly on exec dbo.GetMonthSummaryPerSalesPerson '20030401'; set fmtonly off Without the FMTONLY lines, this stored procedure returns a result set that has three columns and fourteen rows. But with FMTONLY turned on, those rows don’t come back. But what I do get back hurts Reporting Services. It doesn’t run the stored procedure at all. It just looks for anything that could be returned and pushes out a result set in that shape. Despite the fact that I’ve made sure that the logic will only ever return a single result set, the FMTONLY option kills me by returning three of them. It would have been much better to push these checks down into the query itself. alter procedure dbo.GetMonthSummaryPerSalesPerson(@eomdate datetime) as begin     select SalesPersonID, count(*) as NumSales, sum(TotalDue) as TotalSales     from Sales.SalesOrderHeader     where     /* Make sure that @eomdate is valid */         isdate(@eomdate) = 1     /* And that it's sufficiently past */     and datediff(day,@eomdate,sysdatetime()) >= 5     /* And now use it in the filter as appropriate */     and OrderDate >= dateadd(month,-1,@eomdate)     and OrderDate < @eomdate     group by SalesPersonID     order by SalesPersonID; end Now if we run it with FMTONLY turned on, we get the single result set back. But let’s consider the execution plan when we pass in an invalid date. First let’s look at one that returns data. I’ve got a semi-useful index in place on OrderDate, which includes the SalesPersonID and TotalDue fields. It does the job, despite a hefty Sort operation. …compared to one that uses a future date: You might notice that the estimated costs are similar – the Index Seek is still 28%, the Sort is still 71%. But the size of that arrow coming out of the Index Seek is a whole bunch smaller. The coolest thing here is what’s going on with that Index Seek. Let’s look at some of the properties of it. Glance down it with me… Estimated CPU cost of 0.0005728, 387 estimated rows, estimated subtree cost of 0.0044385, ForceSeek false, Number of Executions 0. That’s right – it doesn’t run. So much for reading plans right-to-left... The key is the Filter on the left of it. It has a Startup Expression Predicate in it, which means that it doesn’t call anything further down the plan (to the right) if the predicate evaluates to false. Using this method, we can make sure that our stored procedure contains a single query, and therefore avoid any problems with multiple result sets. If we wanted, we could always use UNION ALL to make sure that we can return an appropriate error message. alter procedure dbo.GetMonthSummaryPerSalesPerson(@eomdate datetime) as begin     select SalesPersonID, count(*) as NumSales, sum(TotalDue) as TotalSales, /*Placeholder: */ '' as ErrorMessage     from Sales.SalesOrderHeader     where     /* Make sure that @eomdate is valid */         isdate(@eomdate) = 1     /* And that it's sufficiently past */     and datediff(day,@eomdate,sysdatetime()) >= 5     /* And now use it in the filter as appropriate */     and OrderDate >= dateadd(month,-1,@eomdate)     and OrderDate < @eomdate     group by SalesPersonID     /* Now include the error messages */     union all     select 0, 0, 0, 'Please enter a valid date' as ErrorMessage     where isdate(@eomdate) != 1     union all     select 0, 0, 0, 'Sorry - EOM is not complete yet' as ErrorMessage     where datediff(day,@eomdate,sysdatetime()) < 5     order by SalesPersonID; end But still I don’t like it, because it’s now a stored procedure with a single query. And I don’t like stored procedures that should be functions. That’s right – I think this should be a function, and SSRS should call the function. And I apologise to those of you who are now planning a bonfire for me. Guy Fawkes’ night has already passed this year, so I think you miss out. (And I’m not going to remind you about when the PASS Summit is in 2012.) create function dbo.GetMonthSummaryPerSalesPerson(@eomdate datetime) returns table as return (     select SalesPersonID, count(*) as NumSales, sum(TotalDue) as TotalSales, '' as ErrorMessage     from Sales.SalesOrderHeader     where     /* Make sure that @eomdate is valid */         isdate(@eomdate) = 1     /* And that it's sufficiently past */     and datediff(day,@eomdate,sysdatetime()) >= 5     /* And now use it in the filter as appropriate */     and OrderDate >= dateadd(month,-1,@eomdate)     and OrderDate < @eomdate     group by SalesPersonID     union all     select 0, 0, 0, 'Please enter a valid date' as ErrorMessage     where isdate(@eomdate) != 1     union all     select 0, 0, 0, 'Sorry - EOM is not complete yet' as ErrorMessage     where datediff(day,@eomdate,sysdatetime()) < 5 ); We’ve had to lose the ORDER BY – but that’s fine, as that’s a client thing anyway. We can have our reports leverage this stored query still, but we’re recognising that it’s a query, not a procedure. A procedure is designed to DO stuff, not just return data. We even get entries in sys.columns that confirm what the shape of the result set actually is, which makes sense, because a table-valued function is the right mechanism to return data. And we get so much more flexibility with this. If you haven’t seen the simplification stuff that I’ve preached on before, jump over to http://bit.ly/SimpleRob and watch the video of when I broke a microphone and nearly fell off the stage in Wales. You’ll see the impact of being able to have a simplifiable query. You can also read the procedural functions post I wrote recently, if you didn’t follow the link from a few paragraphs ago. So if we want the list of SalesPeople that made any kind of sales in a given month, we can do something like: select SalesPersonID from dbo.GetMonthSummaryPerSalesPerson(@eomonth) order by SalesPersonID; This doesn’t need to look up the TotalDue field, which makes a simpler plan. select * from dbo.GetMonthSummaryPerSalesPerson(@eomonth) where SalesPersonID is not null order by SalesPersonID; This one can avoid having to do the work on the rows that don’t have a SalesPersonID value, pushing the predicate into the Index Seek rather than filtering the results that come back to the report. If we had joins involved, we might see some of those being simplified out. We also get the ability to include query hints in individual reports. We shift from having a single-use stored procedure to having a reusable stored query – and isn’t that one of the main points of modularisation? Stored procedures in Reporting Services are just a bit limited for my liking. They’re useful in plenty of ways, but if you insist on using stored procedures all the time rather that queries that use functions – that’s rubbish. @rob_farley

    Read the article

  • 10 tape technology features that make you go hmm.

    - by Karoly Vegh
    A week ago an Oracle/StorageTek Tape Specialist, Christian Vanden Balck, visited Vienna, and agreed to visit customers to do techtalks and update them about the technology boom going around tape. I had the privilege to attend some of his sessions and noted the information and features that took the customers by surprise and made them think. Allow me to share the top 10: I. StorageTek as a brand: StorageTek is one of he strongest names in the Tape field. The brand itself was valued so much by customers that even after Sun Microsystems acquiring StorageTek and the Oracle acquiring Sun the brand lives on with all the Oracle tapelibraries are officially branded StorageTek.See http://www.oracle.com/us/products/servers-storage/storage/tape-storage/overview/index.html II. Disk information density limitations: Disk technology struggles with information density. You haven't seen the disk sizes exploding lately, have you? That's partly because there are physical limits on a disk platter. The size is given, the number of platters is limited, they just can't grow, and are running out of physical area to write to. Now, in a T10000C tape cartridge we have over 1000m long tape. There you go, you have got your physical space and don't need to stuff all that data crammed together. You can write in a reliable pattern, and have space to grow too. III. Oracle has a market share of 62% worldwide in recording head manufacturing. That's right. If you are running LTO drives, with a good chance you rely on StorageTek production. That's two out of three LTO recording heads produced worldwide.  IV. You can store 1 Exabyte data in a single tape library. Yes, an Exabyte. That is 1000 Petabytes. Or, a million Terabytes. A thousand million GigaBytes. You can store that in a stacked StorageTek SL8500 tapelibrary. In one SL8500 you can put 10.000 T10000C cartridges, that store 10TB data (compressed). You can stack 10 of these SL8500s together. Boom. 1000.000 TB.(n.b.: stacking means interconnecting the libraries. Yes, cartridges are moved between the stacked libraries automatically.)  V. EMC: 'Tape doesn't suck after all. We moved on.': Do you remember the infamous 'Tape sucks, move on' Datadomain slogan? Of course they had to put it that way, having only had disk products. But here's a fun fact: on the EMCWorld 2012 there was a major presence of a Tape-tech company - EMC, in a sudden burst of sanity is embracing tape again. VI. The miraculous T10000C: Oracle StorageTek has developed an enterprise-grade tapedrive and cartridge, the T10000C. With awesome numbers: The Cartridge: Native 5TB capacity, 10TB with compression Over a kilometer long tape within the cartridge. And it's locked when unmounted, no rattling of your data.  Replaced the metalparticles datalayer with BaFe (bariumferrite) - metalparticles lose around 7% of magnetism within 30 days. BaFe does not. Yes we employ solid-state physicists doing R&D on demagnetisation in our labs. Can be partitioned, storage tiering within the cartridge!  The Drive: 2GB Cache Encryption implemented in HW - no performance hit 252 MB/s native sustained data rate, beats disk technology by far. Not to mention peak throughput.  Leading the tape while never touching the data side of it, protecting your data physically too Data integritiy checking (CRC recalculation) on tape within the drive without having to read it back to the server reordering data from tape-order, delivering it back in application-order  writing 32 tracks at once, reading them back for CRC check at once VII. You only use 20% of your data on a regular basis. The rest 80% is just lying around for years. On continuously spinning disks. Doubly consuming energy (power+cooling), blocking diskstorage capacity. There is a solution called SAM (Storage Archive Manager) that provides you a filesystem unifying disk and tape, moving data on-demand and for clients transparently between the different storage tiers. You can share these filesystems with NFS or CIFS for clients, and enjoy the low TCO of tape. Tapes don't spin. They sit quietly in their slots, storing 10TB data, using no energy, producing no heat, automounted when a client accesses their data.See: http://www.oracle.com/us/products/servers-storage/storage/storage-software/storage-archive-manager/overview/index.html VIII. HW supported for three decades: Did you know that the original PowderHorn library was released in '87 and has been only discontinued in 2010? That is over two decades of supported operation. Tape libraries are - just like the data carrying on tapecartridges - built for longevity. Oh, and the T10000C cartridge has 30-year archival life for long-term retention.  IX. Tape is easy to manage: Have you heard of Tape Storage Analytics? It is a central graphical tool to summarize, monitor, analyze dataflow, health and performance of drives and libraries, see: http://www.oracle.com/us/products/servers-storage/storage/tape-storage/tape-analytics/overview/index.html X. The next generation: The T10000B drives were able to reuse the T10000A cartridges and write on them even more data. On the same cartridges. We call this investment protection, and this is very important for Oracle for the future too. We usually support two generations of cartridges together. The current drive is a T10000C. (...I know I promised to enlist 10, but I got still two more I really want to mention. Allow me to work around the problem: ) X++. The TallBots, the robots moving around the cartridges in the StorageTek library from tapeslots to the drives are cableless. Cables, belts, chains running to moving parts in a library cause maintenance downtimes. So StorageTek eliminated them. The TallBots get power, commands, even firmwareupgrades through the rails they are running on. Also, the TallBots don't just hook'n'pull the tapes out of their slots, they actually grip'n'lift them out. No friction, no scratches, no zillion little plastic particles floating around in the library, in the drives, on your data. (X++)++: Tape beats SSDs and Disks. In terms of throughput (252 MB/s), in terms of TCO: disks cause around 290x more power and cooling, in terms of capacity: 10TB on a single media and soon more.  So... do you need to store large amounts of data? Are you legally bound to archive it for dozens of years? Would you benefit from automatic storage tiering? Have you got large mediachunks to be streamed at times? Have you got power and cooling issues in the growing datacenters? Do you find EMC's 180° turn of tape attitude interesting, but appreciate it at the same time? With all that, you aren't alone. The most data on this planet is stored on tape. Tape is coming. Big time.

    Read the article

  • How to sift idioms and set phrases apart from other common phrases using NLP techniques?

    - by hippietrail
    What techniques exist that can tell the difference betwen plain common phrases such as "to the", "and the" and set phrases and idioms which have their own lexical meanings such as "pick up", "fall in love", "red herring", "dead end"? Are there techniques which are successful even without a dictionary, statistical methods HMMs train on large corpora for instance? Or are there heuristics such as ignoring or weighting down "promiscuous" words which can co-occur with just about any word versus words which occur either alone or in a specific limited set of idiomatic phrases? If there are such heuristics, how do we take into account set phrases and verbal phrases which do incorporate promiscuous words such as "up" in "beat up", "eat up", "sit up", "think up"? UPDATE I've found an interesting paper online: Unsupervised Type and Token Identi?cation of Idiomatic Expressions

    Read the article

  • Hmm, why finding by '2' or '2' return the same record?

    - by SXLee
    Hi everyone, forget my newbie question, but why finding by '2' or '2' in Mysql returns the same record? For example: Say I have a record with string field named 'slug', and the value is '2'. And the following SQLs returns same record. SELECT * From articles WHERE slug='2' SELECT * From articles WHERE slug='2'

    Read the article

  • Choosing a VS project type (C++)

    - by typoknig
    Hi all, I do not use C++ much (I try to stick to the easier stuff like Java and VB.NET), but the lately I have not had a choice. When I am picking a project type in VS for some C++ source I download, what project type should I pick? I had just been sticking with Win32 Console Applications, but I just downloaded some code (below) that will not work right even when it compiles with out errors. I have tried to use a CLR Console Application and an empty project too, and have changed many variables along the way, but I cannot get this code to work. I noticed that this code does not have "int main()" at its beginning, does that have something to do with it? Anyways, here is the code, got it from here: /* Demo of modified Lucas-Kanade optical flow algorithm. See the printf below */ #ifdef _CH_ #pragma package <opencv> #endif #ifndef _EiC #include "cv.h" #include "highgui.h" #include <stdio.h> #include <ctype.h> #endif #include <windows.h> #define FULL_IMAGE_AS_OUTPUT_FILE #define cvMirror cvFlip //IplImage *image = 0, *grey = 0, *prev_grey = 0, *pyramid = 0, *prev_pyramid = 0, *swap_temp; IplImage **buf = 0; IplImage *image1 = 0; IplImage *imageCopy=0; IplImage *image = 0; int win_size = 10; const int MAX_COUNT = 500; CvPoint2D32f* points[2] = {0,0}, *swap_points; char* status = 0; //int count = 0; //int need_to_init = 0; //int night_mode = 0; int flags = 0; //int add_remove_pt = 0; bool bLButtonDown = false; //bool bstopLoop = false; CvPoint pt, pt1,pt2; //IplImage* img1; FILE* FileDest; char* strImageDir = "E:\\Projects\\TSCreator\\Images"; char* strItemName = "b"; int imageCount=0; int bFirstFace = 1; // flag for first face int mode = 1; // Mode 1 - Haar Traing Sample Creation, 2 - HMM sample creation, Mode = 3 - Both Harr and HMM. //int startImgeNo = 1; bool isEqualRation = false; //Weidth to height ratio is equal //Selected Image data IplImage *selectedImage = 0; int selectedX = 0, selectedY = 0, currentImageNo = 0, selectedWidth = 0, selectedHeight= 0; CvRect selectedROI; void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount); void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount); // Code for draw ROI Cropping Image void on_mouse( int event, int x, int y, int flags, void* param ) { char f[200]; CvRect reg; if( !image ) return; if( event == CV_EVENT_LBUTTONDOWN ) { bLButtonDown = true; pt1.x = x; pt1.y = y; } else if ( event == CV_EVENT_MOUSEMOVE ) //Draw the selected area rectangle { pt2.x = x; pt2.y = y; if(bLButtonDown) { if( !image1 ) { /* allocate all the buffers */ image1 = cvCreateImage( cvGetSize(image), 8, 3 ); image1->origin = image->origin; points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); status = (char*)cvAlloc(MAX_COUNT); flags = 0; } cvCopy( image, image1, 0 ); //Equal Weight-Height Ratio if(isEqualRation) { pt2.y = pt1.y + (pt2.x-pt1.x); } //Max Height and Width is the image width and height if(pt2.x>image->width) { pt2.x = image->width; } if(pt2.y>image->height) { pt2.y = image->height; } CvPoint InnerPt1 = pt1; CvPoint InnerPt2 = pt2; if ( InnerPt1.x > InnerPt2.x) { int tempX = InnerPt1.x; InnerPt1.x = InnerPt2.x; InnerPt2.x = tempX; } if ( pt2.y < InnerPt1.y ) { int tempY = InnerPt1.y; InnerPt1.y = InnerPt2.y; InnerPt2.y = tempY; } InnerPt1.y = image->height - InnerPt1.y; InnerPt2.y = image->height - InnerPt2.y; CvFont font; double hScale=1.0; double vScale=1.0; int lineWidth=1; cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth); char size [200]; reg.x = pt1.x; reg.y = image->height - pt2.y; reg.height = abs (pt2.y - pt1.y); reg.width = InnerPt2.x -InnerPt1.x; //print width and heght of the selected reagion sprintf(size, "(%dx%d)",reg.width, reg.height); cvPutText (image1,size,cvPoint(10,10), &font, cvScalar(255,255,0)); cvRectangle(image1, InnerPt1, InnerPt2, CV_RGB(255,0,0), 1); //Mark Selected Reagion selectedImage = image; selectedX = pt1.x; selectedY = pt1.y; selectedWidth = reg.width; selectedHeight = reg.height; selectedROI = reg; //Show the modified image cvShowImage("HMM-Harr Positive Image Creator",image1); } } else if ( event == CV_EVENT_LBUTTONUP ) { bLButtonDown = false; // pt2.x = x; // pt2.y = y; // // if ( pt1.x > pt2.x) // { // int tempX = pt1.x; // pt1.x = pt2.x; // pt2.x = tempX; // } // // if ( pt2.y < pt1.y ) // { // int tempY = pt1.y; // pt1.y = pt2.y; // pt2.y = tempY; // // } // //reg.x = pt1.x; //reg.y = image->height - pt2.y; // //reg.height = abs (pt2.y - pt1.y); ////reg.width = reg.height/3; //reg.width = pt2.x -pt1.x; ////reg.height = (2 * reg.width)/3; #ifdef FULL_IMAGE_AS_OUTPUT_FILE CvRect FullImageRect; FullImageRect.x = 0; FullImageRect.y = 0; FullImageRect.width = image->width; FullImageRect.height = image->height; IplImage *regionFullImage =0; regionFullImage = cvCreateImage(cvSize (FullImageRect.width, FullImageRect.height), image->depth, image->nChannels); image->roi = NULL; //cvSetImageROI (image, FullImageRect); //cvCopy (image, regionFullImage, 0); #else IplImage *region =0; region = cvCreateImage(cvSize (reg.width, reg.height), image1->depth, image1->nChannels); image->roi = NULL; cvSetImageROI (image1, reg); cvCopy (image1, region, 0); #endif //cvNamedWindow("Result", CV_WINDOW_AUTOSIZE); //selectedImage = image; //selectedX = pt1.x; //selectedY = pt1.y; //selectedWidth = reg.width; //selectedHeight = reg.height; ////currentImageNo = startImgeNo; //selectedROI = reg; /*if(mode == 1) { saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo); } else if(mode == 2) { saveForHMMTraining(image,reg,startImgeNo); } else if(mode ==3) { saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo); saveForHMMTraining(image,reg,startImgeNo); } else { printf("Invalid mode."); } startImgeNo++;*/ } } /* Save popsitive samples for Harr Training. Also add an entry to the PositiveSample.txt with the location of the item of interest. */ void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount) { char f[255] ; sprintf(f,"%s\\%s\\harr_%s%d%d.jpg",strImageDir,strItemName,strItemName,imageCount/10, imageCount%10); cvNamedWindow("Harr", CV_WINDOW_AUTOSIZE); cvShowImage("Harr", src); cvSaveImage(f, src); printf("output%d%d \t ", imageCount/10, imageCount%10); printf("width %d \t", width); printf("height %d \t", height); printf("x1 %d \t", x); printf("y1 %d \t\n", y); char f1[255]; sprintf(f1,"%s\\PositiveSample.txt",strImageDir); FileDest = fopen(f1, "a"); fprintf(FileDest, "%s\\harr_%s%d.jpg 1 %d %d %d %d \n",strItemName,strItemName, imageCount, x, y, width, height); fclose(FileDest); } /* Create Sample Images for HMM recognition algorythm trai ning. */ void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount) { char f[255] ; printf("x=%d, y=%d, w= %d, h= %d\n",roi.x,roi.y,roi.width,roi.height); //Create the file name sprintf(f,"%s\\%s\\hmm_%s%d.pgm",strImageDir,strItemName,strItemName, imageCount); //Create storage for grayscale image IplImage* gray = cvCreateImage(cvSize(roi.width,roi.height), 8, 1); //Create storage for croped reagon IplImage* regionFullImage = cvCreateImage(cvSize(roi.width,roi.height),8,3); //Croped marked region cvSetImageROI(src,roi); cvCopy(src,regionFullImage); cvResetImageROI(src); //Flip croped image - otherwise it will saved upside down cvConvertImage(regionFullImage, regionFullImage, CV_CVTIMG_FLIP); //Convert croped image to gray scale cvCvtColor(regionFullImage,gray, CV_BGR2GRAY); //Show final grayscale image cvNamedWindow("HMM", CV_WINDOW_AUTOSIZE); cvShowImage("HMM", gray); //Save final grayscale image cvSaveImage(f, gray); } int maina( int argc, char** argv ) { CvCapture* capture = 0; //if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) // capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 ); //else if( argc == 2 ) // capture = cvCaptureFromAVI( argv[1] ); char* video; if(argc ==7) { mode = atoi(argv[1]); strImageDir = argv[2]; strItemName = argv[3]; video = argv[4]; currentImageNo = atoi(argv[5]); int a = atoi(argv[6]); if(a==1) { isEqualRation = true; } else { isEqualRation = false; } } else { printf("\nUsage: TSCreator.exe <Mode> <Sample Image Save Path> <Sample Image Save Directory> <Video File Location> <Start Image No> <Is Equal Ratio>\n"); printf("Mode = 1 - Haar Traing Sample Creation. \nMode = 2 - HMM sample creation.\nMode = 3 - Both Harr and HMM\n"); printf("Is Equal Ratio = 0 or 1. 1 - Equal weidth and height, 0 - custom."); printf("Note: You have to create the image save directory in correct path first.\n"); printf("Eg: TSCreator.exe 1 E:\Projects\TSCreator\Images A 11.avi 1 1\n\n"); return 0; } capture = cvCaptureFromAVI(video); if( !capture ) { fprintf(stderr,"Could not initialize capturing...\n"); return -1; } cvNamedWindow("HMM-Harr Positive Image Creator", CV_WINDOW_AUTOSIZE); cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0); //cvShowImage("Test", image1); for(;;) { IplImage* frame = 0; int i, k, c; frame = cvQueryFrame( capture ); if( !frame ) break; if( !image ) { /* allocate all the buffers */ image = cvCreateImage( cvGetSize(frame), 8, 3 ); image->origin = frame->origin; //grey = cvCreateImage( cvGetSize(frame), 8, 1 ); //prev_grey = cvCreateImage( cvGetSize(frame), 8, 1 ); //pyramid = cvCreateImage( cvGetSize(frame), 8, 1 ); // prev_pyramid = cvCreateImage( cvGetSize(frame), 8, 1 ); points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); status = (char*)cvAlloc(MAX_COUNT); flags = 0; } cvCopy( frame, image, 0 ); // cvCvtColor( image, grey, CV_BGR2GRAY ); cvShowImage("HMM-Harr Positive Image Creator", image); cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0); c = cvWaitKey(0); if((char)c == 's') { //Save selected reagion as training data if(selectedImage) { printf("Selected Reagion Saved\n"); if(mode == 1) { saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo); } else if(mode == 2) { saveForHMMTraining(selectedImage,selectedROI,currentImageNo); } else if(mode ==3) { saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo); saveForHMMTraining(selectedImage,selectedROI,currentImageNo); } else { printf("Invalid mode."); } currentImageNo++; } } } cvReleaseCapture( &capture ); //cvDestroyWindow("HMM-Harr Positive Image Creator"); cvDestroyAllWindows(); return 0; } #ifdef _EiC main(1,"lkdemo.c"); #endif If I put... #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } ... before the previous code (and link it to the correct OpenCV .lib files) it compiles without errors, but does nothing at the command line. How do I make it work?

    Read the article

  • Array::include? on ActiveRecord collection not calling op== ?

    - by tribalvibes
    Given a collection of named Foos from ActiveRecord, why does Array.include? not seem to call Foo.== but yet index does? class Foo < ActiveRecord::Base def ==(s) self.name == s end end class Bar < ActiveRecord::Base has_many :foos end bar.foos << Foo.new( :name = 'hmm' ) bar.foos.all.include?('hmm') # does select all from db every time = true bar.foos.include?('hmm') # does not go to db, but does not find the Foo! = false bar.foos.index('hmm') # does not go to db, but does find the Foo[0] ! = 0 bar.foos.index('eh') # no such object = nil I understand shallow about the proxies, but (without a detour into the AR source) why is index seemingly behaving correctly but include? is not !? Is this a bug in the proxy behavior, and/or is this behavior documented somewhere ? Thanks.

    Read the article

  • Common Pitfalls in Python

    - by Anurag Uniyal
    Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :) My question is what other things should I add to my list of things to MUST avoid? Mutable default arguments Import modules always same way e.g. from y import x and import x are different things, they are treated as different modules. Do not use range in place of lists because range() will become an iterator anyway, the following will fail: myIndexList = [0,1,3] isListSorted = myIndexList == range(3) # will fail in 3.0 isListSorted = myIndexList == list(range(3)) # will not same thing can be mistakenly done with xrange: `myIndexList == xrange(3)`. Catching multiple exceptions try: raise KeyError("hmm bug") except KeyError,TypeError: print TypeError It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, use this instead: try: raise KeyError("hmm bug") except (KeyError,TypeError): print TypeError

    Read the article

  • Communication with a single-threaded apartment

    - by hmm
    How do I communicate with a method in a single threaded apartment process in .NET? I have something like a coordinator worker pattern need with the single threaded apartment process acting like the worker. I cannot use named pipes read/writes for my scenario due to certain reasons. Is there any other way to delegate work to the single threaded apartment process?

    Read the article

  • Debug checklists/Helpers with Visual Studio/.NET

    - by hmm
    I have STAThread process which when called from my process simply bombs with no exceptions and almost nothing in the call stack. If I click Cntrl+Alt+E, I get an exceptions window, how can I use it in this situation, seems like some exception is not being caught here. Also what other debugging aids can I use here in Visual Studio 2010?

    Read the article

  • Convert a Unit Vector to a Quaternion

    - by Hmm
    So I'm very new to quaternions, but I understand the basics of how to manipulate stuff with them. What I'm currently trying to do is compare a known quaternion to two absolute points in space. I'm hoping what I can do is simply convert the points into a second quaternion, giving me an easy way to compare the two. What I've done so far is to turn the two points into a unit vector. From there I was hoping I could directly plug in the i j k into the imaginary portion of the quaternion with a scalar of zero. From there I could multiply one quaternion by the other's conjugate, resulting in a third quaternion. This third quaternion could be converted into an axis angle, giving me the degree by which the original two quaternions differ by. Is this thought process correct? So it should just be [ 0 i j k ]. I may need to normalize the quaternion afterwards, but I'm not sure about that. I have a bad feeling that it's not a direct mapping from a vector to a quaternion. I tried looking at converting the unit vector to an axis angle, but I'm not sure this would work, since I don't know what angle to give as an input.

    Read the article

  • .NET Code Evolution

    - by Alois Kraus
    Originally posted on: http://geekswithblogs.net/akraus1/archive/2013/07/24/153504.aspxAt my day job I do look at a lot of code written by other people. Most of the code is quite good and some is even a masterpiece. And there is also code which makes you think WTF… oh it was written by me. Hm not so bad after all. There are many excuses reasons for bad code. Most often it is time pressure followed by not enough ambition (who cares) or insufficient training. Normally I do care about code quality quite a lot which makes me a (perceived) slow worker who does write many tests and refines the code quite a lot because of the design deficiencies. Most of the deficiencies I do find by putting my design under stress while checking for invariants. It does also help a lot to step into the code with a debugger (sometimes also Windbg). I do this much more often when my tests are red. That way I do get a much better understanding what my code really does and not what I think it should be doing. This time I do want to show you how code can evolve over the years with different .NET Framework versions. Once there was  time where .NET 1.1 was new and many C++ programmers did switch over to get rid of not initialized pointers and memory leaks. There were also nice new data structures available such as the Hashtable which is fast lookup table with O(1) time complexity. All was good and much code was written since then. At 2005 a new version of the .NET Framework did arrive which did bring many new things like generics and new data structures. The “old” fashioned way of Hashtable were coming to an end and everyone used the new Dictionary<xx,xx> type instead which was type safe and faster because the object to type conversion (aka boxing) was no longer necessary. I think 95% of all Hashtables and dictionaries use string as key. Often it is convenient to ignore casing to make it easy to look up values which the user did enter. An often followed route is to convert the string to upper case before putting it into the Hashtable. Hashtable Table = new Hashtable(); void Add(string key, string value) { Table.Add(key.ToUpper(), value); } This is valid and working code but it has problems. First we can pass to the Hashtable a custom IEqualityComparer to do the string matching case insensitive. Second we can switch over to the now also old Dictionary type to become a little faster and we can keep the the original keys (not upper cased) in the dictionary. Dictionary<string, string> DictTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); void AddDict(string key, string value) { DictTable.Add(key, value); } Many people do not user the other ctors of Dictionary because they do shy away from the overhead of writing their own comparer. They do not know that .NET has for strings already predefined comparers at hand which you can directly use. Today in the many core area we do use threads all over the place. Sometimes things break in subtle ways but most of the time it is sufficient to place a lock around the offender. Threading has become so mainstream that it may sound weird that in the year 2000 some guy got a huge incentive for the idea to reduce the time to process calibration data from 12 hours to 6 hours by using two threads on a dual core machine. Threading does make it easy to become faster at the expense of correctness. Correct and scalable multithreading can be arbitrarily hard to achieve depending on the problem you are trying to solve. Lets suppose we want to process millions of items with two threads and count the processed items processed by all threads. A typical beginners code might look like this: int Counter; void IJustLearnedToUseThreads() { var t1 = new Thread(ThreadWorkMethod); t1.Start(); var t2 = new Thread(ThreadWorkMethod); t2.Start(); t1.Join(); t2.Join(); if (Counter != 2 * Increments) throw new Exception("Hmm " + Counter + " != " + 2 * Increments); } const int Increments = 10 * 1000 * 1000; void ThreadWorkMethod() { for (int i = 0; i < Increments; i++) { Counter++; } } It does throw an exception with the message e.g. “Hmm 10.222.287 != 20.000.000” and does never finish. The code does fail because the assumption that Counter++ is an atomic operation is wrong. The ++ operator is just a shortcut for Counter = Counter + 1 This does involve reading the counter from a memory location into the CPU, incrementing value on the CPU and writing the new value back to the memory location. When we do look at the generated assembly code we will see only inc dword ptr [ecx+10h] which is only one instruction. Yes it is one instruction but it is not atomic. All modern CPUs have several layers of caches (L1,L2,L3) which try to hide the fact how slow actual main memory accesses are. Since cache is just another word for redundant copy it can happen that one CPU does read a value from main memory into the cache, modifies it and write it back to the main memory. The problem is that at least the L1 cache is not shared between CPUs so it can happen that one CPU does make changes to values which did change in meantime in the main memory. From the exception you can see we did increment the value 20 million times but half of the changes were lost because we did overwrite the already changed value from the other thread. This is a very common case and people do learn to protect their  data with proper locking.   void Intermediate() { var time = Stopwatch.StartNew(); Action acc = ThreadWorkMethod_Intermediate; var ar1 = acc.BeginInvoke(null, null); var ar2 = acc.BeginInvoke(null, null); ar1.AsyncWaitHandle.WaitOne(); ar2.AsyncWaitHandle.WaitOne(); if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Intermediate did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Intermediate() { for (int i = 0; i < Increments; i++) { lock (this) { Counter++; } } } This is better and does use the .NET Threadpool to get rid of manual thread management. It does give the expected result but it can result in deadlocks because you do lock on this. This is in general a bad idea since it can lead to deadlocks when other threads use your class instance as lock object. It is therefore recommended to create a private object as lock object to ensure that nobody else can lock your lock object. When you read more about threading you will read about lock free algorithms. They are nice and can improve performance quite a lot but you need to pay close attention to the CLR memory model. It does make quite weak guarantees in general but it can still work because your CPU architecture does give you more invariants than the CLR memory model. For a simple counter there is an easy lock free alternative present with the Interlocked class in .NET. As a general rule you should not try to write lock free algos since most likely you will fail to get it right on all CPU architectures. void Experienced() { var time = Stopwatch.StartNew(); Task t1 = Task.Factory.StartNew(ThreadWorkMethod_Experienced); Task t2 = Task.Factory.StartNew(ThreadWorkMethod_Experienced); t1.Wait(); t2.Wait(); if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Experienced did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Experienced() { for (int i = 0; i < Increments; i++) { Interlocked.Increment(ref Counter); } } Since time does move forward we do not use threads explicitly anymore but the much nicer Task abstraction which was introduced with .NET 4 at 2010. It is educational to look at the generated assembly code. The Interlocked.Increment method must be called which does wondrous things right? Lets see: lock inc dword ptr [eax] The first thing to note that there is no method call at all. Why? Because the JIT compiler does know very well about CPU intrinsic functions. Atomic operations which do lock the memory bus to prevent other processors to read stale values are such things. Second: This is the same increment call prefixed with a lock instruction. The only reason for the existence of the Interlocked class is that the JIT compiler can compile it to the matching CPU intrinsic functions which can not only increment by one but can also do an add, exchange and a combined compare and exchange operation. But be warned that the correct usage of its methods can be tricky. If you try to be clever and look a the generated IL code and try to reason about its efficiency you will fail. Only the generated machine code counts. Is this the best code we can write? Perhaps. It is nice and clean. But can we make it any faster? Lets see how good we are doing currently. Level Time in s IJustLearnedToUseThreads Flawed Code Intermediate 1,5 (lock) Experienced 0,3 (Interlocked.Increment) Master 0,1 (1,0 for int[2]) That lock free thing is really a nice thing. But if you read more about CPU cache, cache coherency, false sharing you can do even better. int[] Counters = new int[12]; // Cache line size is 64 bytes on my machine with an 8 way associative cache try for yourself e.g. 64 on more modern CPUs void Master() { var time = Stopwatch.StartNew(); Task t1 = Task.Factory.StartNew(ThreadWorkMethod_Master, 0); Task t2 = Task.Factory.StartNew(ThreadWorkMethod_Master, Counters.Length - 1); t1.Wait(); t2.Wait(); Counter = Counters[0] + Counters[Counters.Length - 1]; if (Counter != 2 * Increments) throw new Exception(String.Format("Hmm {0:N0} != {1:N0}", Counter, 2 * Increments)); Console.WriteLine("Master did take: {0:F1}s", time.Elapsed.TotalSeconds); } void ThreadWorkMethod_Master(object number) { int index = (int) number; for (int i = 0; i < Increments; i++) { Counters[index]++; } } The key insight here is to use for each core its own value. But if you simply use simply an integer array of two items, one for each core and add the items at the end you will be much slower than the lock free version (factor 3). Each CPU core has its own cache line size which is something in the range of 16-256 bytes. When you do access a value from one location the CPU does not only fetch one value from main memory but a complete cache line (e.g. 16 bytes). This means that you do not pay for the next 15 bytes when you access them. This can lead to dramatic performance improvements and non obvious code which is faster although it does have many more memory reads than another algorithm. So what have we done here? We have started with correct code but it was lacking knowledge how to use the .NET Base Class Libraries optimally. Then we did try to get fancy and used threads for the first time and failed. Our next try was better but it still had non obvious issues (lock object exposed to the outside). Knowledge has increased further and we have found a lock free version of our counter which is a nice and clean way which is a perfectly valid solution. The last example is only here to show you how you can get most out of threading by paying close attention to your used data structures and CPU cache coherency. Although we are working in a virtual execution environment in a high level language with automatic memory management it does pay off to know the details down to the assembly level. Only if you continue to learn and to dig deeper you can come up with solutions no one else was even considering. I have studied particle physics which does help at the digging deeper part. Have you ever tried to solve Quantum Chromodynamics equations? Compared to that the rest must be easy ;-). Although I am no longer working in the Science field I take pride in discovering non obvious things. This can be a very hard to find bug or a new way to restructure data to make something 10 times faster. Now I need to get some sleep ….

    Read the article

  • Can someone explain me this code ?

    - by VaioIsBorn
    #include <stdio.h> #include <unistd.h> #include <string.h> int good(int addr) { printf("Address of hmm: %p\n", addr); } int hmm() { printf("Win.\n"); execl("/bin/sh", "sh", NULL); } extern char **environ; int main(int argc, char **argv) { int i, limit; for(i = 0; environ[i] != NULL; i++) memset(environ[i], 0x00, strlen(environ[i])); int (*fptr)(int) = good; char buf[32]; if(strlen(argv[1]) <= 40) limit = strlen(argv[1]); for(i = 0; i <= limit; i++) { buf[i] = argv[1][i]; if(i < 36) buf[i] = 0x41; } int (*hmmptr)(int) = hmm; (*fptr)((int)hmmptr); return 0; } I don't really understand the code above, i have it from an online game - i should supply something in the arguments so it would give me shell, but i don't get it how it works so i don't know what to do. So i need someone that would explain it what it does, how it's working and the stuff. Thanks.

    Read the article

  • Python - Things one MUST avoid

    - by Anurag Uniyal
    Today I was bitten again by "Mutable default arguments" after many years. I usually don't use mutable default arguments unless needed but I think with time I forgot about that, and today in the application I added tocElements=[] in a pdf generation function's argument list and now 'Table of Content' gets longer and longer after each invocation of "generate pdf" :) My question is what other things should I add to my list of things to MUST avoid? 1 Mutable default arguments 2 import modules always same way e.g. 'from y import x' and 'import x' are totally different things actually they are treated as different modules see http://stackoverflow.com/questions/1459236/module-reimported-if-imported-from-different-path 3 Do not use range in place of lists because range() will become an iterator anyway, so things like this will fail, so wrap it by list myIndexList = [0,1,3] isListSorted = myIndexList == range(3) # will fail in 3.0 isListSorted = myIndexList == list(range(3)) # will not same thing can be mistakenly done with xrange e.g myIndexList == xrange(3). 4 Catching multiple exceptions try: raise KeyError("hmm bug") except KeyError,TypeError: print TypeError It prints "hmm bug", though it is not a bug, it looks like we are catching exceptions of type KeyError,TypeError but instead we are catching KeyError only as variable TypeError, instead use try: raise KeyError("hmm bug") except (KeyError,TypeError): print TypeError

    Read the article

  • Amazon Kindle for Linux

    <b>Jim Lynch:</b> "Hmm. It seems that one VERY prominent platform is missing. Yep, that's right. Amazon still has not released a Kindle application for Linux."

    Read the article

  • Going Beyond the Relational Model with Data

    SQL is a powerful tool for querying data, and for aggregating it. However, you can't easily use it to draw inferences, to make predictions, or to tease out subtle correlations. To provide ever more sophisticated inferences to businesses, the race is on to combine the power of the relational model with advanced statistical packages. Both IBM and PostGres are ready with solutions. And SQL Server? Hmm...

    Read the article

  • using Quick Sequence Diagram Editor for sequence diagrams

    - by Jason S
    Anyone have experience with Quick Sequence Diagram Editor? The combination of instant display + text source code + Java implementation is very attractive to me, but I can't quite figure out how to make the syntax do what I want, and the documentation's not very clear. Here's a contrived example: al:Actor bill:Actor atm:ATM[a] bank:Bank[a] al:atm.give me $10 atm:al has $3=bank.check al's account balance al:atm.what time is it atm:al.it's now atm:al.stop bugging me atm:al.you only have $3 atm:bill.and don't you open your mouth bill:atm.who asked you? bill:atm.give me $20 al:atm.hey, I'm not finished! atm:bill has $765=bank.check bill's account balance atm:yes I'm sure, bill has $765=bank.hmm are you sure? atm:bill.here's $20, now go away atm:great, he's a cool dude=bank.I just gave Bill $20 al:atm.what about my $10? atm:al.read my lips: you only have $3 Here's the result from QSDE in single-threaded mode: and in multi-threaded mode: I guess I'm not clear what starts/ends those vertical bars. I have a situation which is single-threaded, but there's state involved, and all the messages are asynchronous. I guess that means I should use an external object to represent that state and its lifetime. What I want is for one timeline to represent the message sequence al:atm.give me $10 atm:bank.check al's account balance bank:atm.al has $3 atm:al.you only have $3 and another timeline to represent the message sequence bill:atm.give me $20 atm:bank.check bill's account balance bank:atm.bill has $765 atm:bank.hmm are you sure? bank:atm.yes I'm sure, bill has $765 atm:bill.here's $20, now go away atm:bank.I just gave Bill $20 bank:atm.great, he's a cool dude with the other "wisecracks" representing other miscellaneous messages that I don't care about right now. Is there a way to do this with QSDE?

    Read the article

1 2 3 4 5 6 7 8 9  | Next Page >