In order to easily rotate an image in 3D space, I have written a simple method that will do just that. It accepts rotations (in degrees) along each of the three axis (x, y and z), with 90 degrees being the "normal" position.
It also supports translations along each of the axis, and a variable focal distance (you would usually want the focal distance to be the same as your dz).
The parameters are:
input: the image that you want rotated.
output: the Mat object to put the resulting file in.
alpha: the rotation around the x axis
beta: the rotation around the y axis
gamma: the rotation around the z axis (basically a 2D rotation)
dx: translation along the x axis
dy: translation along the y axis
dz: translation along the z axis (distance to the image)
f: focal distance (distance between camera and image, a smaller number exaggerates the effect)
The method is defined as:
A blog about anything a software engineer might encounter during his programming efforts.
28 November 2012
26 October 2012
Overlay transparent image in OpenCV
It seems OpenCV does not provide very much support for transparent images. It has images with 4 channels, which are treated as BGRA images, with the fourth channel being the Alpha channel. It also supports saving these images using the PNG format, yet it does not support properly displaying these images in highgui, nor does it support combining these images.
I have looked a while for a way to combine a (BGR) background image with a (BGRA) foreground image, with semi-transparent images, but was unable to find one. So, I wrote my own and since I couldn't find a solution on the internet, I'll bet I can save some people some time by sharing my implementation, which is as follows:
Labels:
C++
,
OpenCV
,
transparency
11 July 2012
Installation guide: OpenCV 2.4 with Visual Studio C++ 2010
After some trouble installing OpenCV 2.4 in Windows and using it with Visual C++ 2010, I decided to write a post about this, so I can hopefully save you some time figuring this one out. It is based on this wiki, but that describes how to build with CMake etc, which is not necessary (anymore?).
Okay, so first you need to download OpenCV 2.4 here. After downloading, you need to extract it. I have extracted it to "D:\OpenCV2.4.2\" and I will use this folder for the rest of this post, you can change it if you like.
Edit your PATH variable (right click on this computer, properties, then select the tab "advanced" and click on "Environment Variables", which is near the bottom).
Okay, so first you need to download OpenCV 2.4 here. After downloading, you need to extract it. I have extracted it to "D:\OpenCV2.4.2\" and I will use this folder for the rest of this post, you can change it if you like.
Edit your PATH variable (right click on this computer, properties, then select the tab "advanced" and click on "Environment Variables", which is near the bottom).
Labels:
C++
,
Guide
,
Installation
,
OpenCV
9 February 2012
Add a Facebook "like" and Google "+1" button to Magento and integrate them with Google Analytics
Let's start with adding the Facebook like button. On this page: https://developers.facebook.com/docs/reference/plugins/like/, you can create the button as you would like it to appear on your site. When you press "Get Code", you'll get 2 pieces of code.
First we have to add the JavaScript code. To do this, open your head.phtml page, which can be found here:
In this file, add the script, like so:
After that, you can add the other part of the Facebook code in any of your pages, where you would like to have the button. If you want to have it in a CMS page, you can create a Custom Variable, by opening the admin part of your Magento shop and navigating to System -> Custom Variables. In there, create a new variable and insert the code in the Variable HTML Value.
First we have to add the JavaScript code. To do this, open your head.phtml page, which can be found here:
app/design/frontend/<your template>/<theme>/template/page/html/head.phtmlIn this file, add the script, like so:
<script type="text/javascript"> (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/nl_NL/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script>After that, you can add the other part of the Facebook code in any of your pages, where you would like to have the button. If you want to have it in a CMS page, you can create a Custom Variable, by opening the admin part of your Magento shop and navigating to System -> Custom Variables. In there, create a new variable and insert the code in the Variable HTML Value.
Labels:
Analytics
,
Facebook
,
Google+
,
javascript
,
Magento
,
Social Media
29 November 2011
Error during serialization or deserialization using the JSON JavaScriptSerializer
Today one of the internal web applications that we have wouldn't run properly on my development machine (it works fine on the production server). When opened it would produce the following exception:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
It seems that the production server has a higher
maxJsonLength value in its machine.config than my development machine. To solve this problem, add the following in your web.config.
Labels:
asp.net
,
exception
,
iis
,
javascript
,
json
,
web.config
22 November 2011
The Null coalescing operator
It seems that a lot of people do not know of the existence of this handy little operator, so I decided to put it up here, so it may help somebody clean up their code.
Have you ever had a
Chances are, you've written it in one of the following ways:
or
But using the NULL coalescing operator, you can simply write:
Have you ever had a
Nullable<...> type which you needed to read to a regular value type, but needed a "default" value for when it was NULL, as the regular value type cannot handle it?Chances are, you've written it in one of the following ways:
int? i = null; // please note that Nullable<int> is the same as int?int a;if(i.HasValue) // equal to: if(i != null) a = i.Value;else a = -1;or
int a = i.HasValue ? i.Value : -1; // This is already a bit shorter!But using the NULL coalescing operator, you can simply write:
Entity Framework: duplicate rows in resultset from a view
After including a view I have in my database in an Entity Framework data model, I noticed that for some strange reason, the result was showing duplicates. When a set should have for instance 10 different rows, it might contain only 4 different rows, some of which were duplicated so it was still a total of 10 rows.
The view itself showed the correct results, but when called from code using the Entity Framework, it once again showed the wrong results.
After some testing I found out that the rows that were duplicated, were rows that shared certain values with the rows that were replaced by it. After checking this in my Entity Model, I soon found at that the Entity Model has a strange way of handling rows with equal primary key values.
I'll try and explain my findings:
The view itself showed the correct results, but when called from code using the Entity Framework, it once again showed the wrong results.
After some testing I found out that the rows that were duplicated, were rows that shared certain values with the rows that were replaced by it. After checking this in my Entity Model, I soon found at that the Entity Model has a strange way of handling rows with equal primary key values.
I'll try and explain my findings:
Labels:
.net
,
C#
,
Entity Framework
,
SQL
Windows Task Scheduler error 2147942667
If you have created a task within Windows Task Scheduler, you might encounter a task that does not run properly. When you look into the history of the task, you might find the following error message:
Task Scheduler failed to start instance "<guid value>" of "<task name>" task for user "<user name>" . Additional Data: Error Value: 2147942667.
The reason for this error is the fact that you have put quotes (") around the value in Startup Path. Strangely, the executable may have quotes surrounding it (e.g. "C:\Path to\Executable.exe"), but the Startup Path may not, even when there are spaces in the Path (which makes the use of quotes for the executable necessary).
Task Scheduler failed to start instance "<guid value>" of "<task name>" task for user "<user name>" . Additional Data: Error Value: 2147942667.
The reason for this error is the fact that you have put quotes (") around the value in Startup Path. Strangely, the executable may have quotes surrounding it (e.g. "C:\Path to\Executable.exe"), but the Startup Path may not, even when there are spaces in the Path (which makes the use of quotes for the executable necessary).
Remove any quotes you have in the Startup Path value and try again.
See also this Microsoft Support Article:
Windows Vista onwards scheduled tasks fail to run if the path in "Start in (Optional)" field has quotes
See also this Microsoft Support Article:
Windows Vista onwards scheduled tasks fail to run if the path in "Start in (Optional)" field has quotes
Labels:
Task scheduler
,
Windows
25 February 2011
aspnet_regsql.exe doesn't work with SQL Azure
If you want to create the database structure for using Forms Authentication in your Windows Azure hosted ASP.Net application, you'll probably have noticed that running aspnet_regsql.exe on your Azure database doesn't work.
I have tried merging a local database using Red Gate SQL Compare 9 (you can of course also use the SQL Azure Migration Wizard), but that also gave me some errors regarding some elements in the resulting update statement that were not supported in SQL Azure.
I have looked into these errors and found that it was relatively easy to fix these. If you take a look at the Stored Procedure called
I have tried merging a local database using Red Gate SQL Compare 9 (you can of course also use the SQL Azure Migration Wizard), but that also gave me some errors regarding some elements in the resulting update statement that were not supported in SQL Azure.
I have looked into these errors and found that it was relatively easy to fix these. If you take a look at the Stored Procedure called
aspnet_Membership_GetNumberOfUsersOnline in a "regular" SQL server, you'll see that it contains a couple of (NOLOCK) statements in it's SELECT statement.
Labels:
asp.net
,
Authentication
,
SQL
,
SQL Azure
,
Windows Azure
9 January 2011
Thread.Sleep(1) waits approx. 15 ms in stead of 1
Ever noticed how the time
After some research I discovered that the .Net runtime and Windows map this to a lower resolution in time, due to the way they handle threads. According to some sites it is 15.6 ms.
This means that any x between 1 and 15 will have your thread wait 15.6 ms (give or take, as it might be that your thread has to wait a bit more because of other calculations your CPU is processing). Any value between 16 and 31 will have your thread wait 2 x 15.6 ms (i.e. 31.2 ms) etc. The documentation also states that
For me, this is not a problem, I have just set the thread that was supposed to go slower to a different value, to make sure it actually runs slower. But just out of curiosity I have done some more research into how to solve it if you really want to have your thread sleep for a more precise period of time.
It seems the MultiMedia API's can help with that. I have tested the following code and it allowed me to set the sleep to a millisecond precisely.
Thread.Sleep(int x) waits is not equal to x? I just noticed it happening with 2 threads with different values for the sleep, yet they were running just as quick.After some research I discovered that the .Net runtime and Windows map this to a lower resolution in time, due to the way they handle threads. According to some sites it is 15.6 ms.
This means that any x between 1 and 15 will have your thread wait 15.6 ms (give or take, as it might be that your thread has to wait a bit more because of other calculations your CPU is processing). Any value between 16 and 31 will have your thread wait 2 x 15.6 ms (i.e. 31.2 ms) etc. The documentation also states that
Thread.Sleep(int x) does not wait exactly x milliseconds, but rather "at least" x milliseconds.For me, this is not a problem, I have just set the thread that was supposed to go slower to a different value, to make sure it actually runs slower. But just out of curiosity I have done some more research into how to solve it if you really want to have your thread sleep for a more precise period of time.
It seems the MultiMedia API's can help with that. I have tested the following code and it allowed me to set the sleep to a millisecond precisely.
Labels:
.net
,
multi-threading
5 January 2011
ThreadAbortException on Response.Redirect(), Response.End() and Response.Transfer()
If you have ever used a call to
This is normal behaviour, but can mess up your program if the corresponding catch is executed unexpectedly.
To avoid this, catch the
For instance, if you have:
You can rewrite it like so:
Response.Redirect("url"), Response.End() or Server.Transfer() within a try block, you will probably have noticed that these calls always throw a ThreadAbortException.This is normal behaviour, but can mess up your program if the corresponding catch is executed unexpectedly.
To avoid this, catch the
ThreadAbortException in a separate catch, or write a try/catch around the call. For instance, if you have:
try{ Do something here; Response.Redirect("some url");
Do some more work;}catch(Exception ex){ Do something useful with the excepion here;}You can rewrite it like so:
30 December 2010
Crystal Reports: The maximum report processing jobs limit configured by your system administrator has been reached.
This exception is produced by Crystal Reports when the maximum number of concurrent report processes have been initiated. I have had troubles with this exception in my asp.net application, but at first it seemed almost to occur at random. Recycling the app pool solved the problem when it occurred. After a while (when the application was used more intensively) this became a real problem, as it began to occur more and more often.
My application does not use a ReportViewer, but rather generates a pdf file and sends it to the client as a download, using the following code:
At first, I fixed this problem quite easily, by altering one value in the registry:
My application does not use a ReportViewer, but rather generates a pdf file and sends it to the client as a download, using the following code:
ReportDocument repDoc = new ReportDocument();
repDoc.Load(filename);
// update the crystal report database connection
repDoc.SetCrystalReportDatabase("ConnectionString");
// send the resulting document to the user (as PDF).
Response.ClearContent();
Response.ClearHeaders();
repDoc.ExportToHttpResponse(formatType, Response, true, "Report");repDoc.Dispose();At first, I fixed this problem quite easily, by altering one value in the registry:
Labels:
.net
,
asp.net
,
crystal reports
,
exception
An error occurred while validating. HRESULT = '80004005'
I was having trouble with this error today, when I was trying to build a Deployment package. I also noticed that my deployment package showed no Detected References anymore.
The weird thing was, that my solution build properly and I could even run the software. It was just the deployment package that was producing errors.
As I found, the first thing to check is missing references. If they are not in use in the code, debugging the project will not produce any errors, building the deployment will. This also includes references to other projects, which are not included in the solution. If not pointing directly to the pre-built dll, these will produce problems.
For me though, this did not solve my problem, but I did find something else that caught my eye;
The weird thing was, that my solution build properly and I could even run the software. It was just the deployment package that was producing errors.
As I found, the first thing to check is missing references. If they are not in use in the code, debugging the project will not produce any errors, building the deployment will. This also includes references to other projects, which are not included in the solution. If not pointing directly to the pre-built dll, these will produce problems.
For me though, this did not solve my problem, but I did find something else that caught my eye;
Labels:
.net
,
exception
,
visual studio
22 December 2010
ASP Menu leaving empty space above menu items
Today I was having trouble with an ASP.Net Menu control that kept a bit of empty space above, which made it render too low in the div element it was supposed to stay inside of:
This problem just came out of nowhere, one day my menu is showing as it should, the next day, it is not. I even tried rolling back to the older version of the files, but somehow this didn't change a thing. It might have been an update to Visual Studio 2010, which got automatically installed or something.
After looking into the rendered html with IE8 and its developer tools (press F12 to get these, then CTRL-B to click an element in the page and have its tag selected in the developer tool), I discoverd an
This problem just came out of nowhere, one day my menu is showing as it should, the next day, it is not. I even tried rolling back to the older version of the files, but somehow this didn't change a thing. It might have been an update to Visual Studio 2010, which got automatically installed or something.
After looking into the rendered html with IE8 and its developer tools (press F12 to get these, then CTRL-B to click an element in the page and have its tag selected in the developer tool), I discoverd an
a-element above my Menu:(The
div with class Menu is my own div, in it you see the table with class ct100_Menu1_2 which is the actual menu, with 2 a elements around it)21 December 2010
Reseed a table in SQL Server
In Microsoft SQL Server, it is possible to reseed an identity column of a table. If you want to start an identity column at a different value (for instance, after clearing it), you can use the following syntax:
DBCC CHECKIDENT (myTable, reseed, 0)The next row that is added to the table will have 1 in its identity column. If we would use
DBCC CHECKIDENT (myTable, reseed, 41)the next row would get 42 in its identity column.
Be careful when using this on tables with rows in them, if the new seed is lower than the highest currently in the table, you will encounter problems before long. When the new seed is already in use, you will get a unique key restriction violation on insert!
Labels:
SQL
,
SQL Server
20 December 2010
Convert objects to string and back without culture problems
After storing various values as strings in a database, I had some troubles with parsing these values back to their original types (
As it seems, the most commonly used ways (such as
The best way I have found to convert values to strings and back, independent of the current culture, is with the use of the
It can be used as follows:
It can be used for other types, by using its following method:
doubles, datetimes, etc.) on various clients.As it seems, the most commonly used ways (such as
ToString(), Convert.ToString(), Convert.ToDecimal() and DateTime.Parse()) perform these conversions based on the current culture. This means that the whole format of a datetime can differ on different clients, but also the thousands separator in numbers and also their decimal mark as all of these are culture dependent.The best way I have found to convert values to strings and back, independent of the current culture, is with the use of the
FormatterConverter class. This class converts objects to other objects, independent of any culture (probably using the InvariantCulture).It can be used as follows:
FormatterConverter fConverter = new FormatterConverter();double d = fConverter.ToDouble(stringValue);string s = fConverter.ToString(datetimeValue);It can be used for other types, by using its following method:
object Convert(object obj, Type t)
For instance, to convert a string to a Car object, you can use the following:
Car myCar = fConverter.Convert(stringValue, typeof(Car)) as Car;you have to cast the result to
Car, as the Convert method returns an object.17 December 2010
Could not load file or assembly 'System.Data' or one of its dependencies
The full exception is:
Could not load file or assembly 'System.Data' or one of its dependencies. An attempt was made to load a program with an incorrect format.
This problem seems to occur rather a lot and it seems there are different causes for it to occur. I have had this problem today and the information I found on the internet did not help at all. I have tried setting System.Data to not copy local, but then it just started with other libraries. I have also changed the .net version in my web.config, but that did not solve my problem either.
The only real difference that I could find between the old and new server was the fact that the new server was 64-bits. So looked into that and found an option in the advanced settings of an app pool in IIS7, named "Enable 32-Bit Applications".
After setting it to true, everything worked as before.
Could not load file or assembly 'System.Data' or one of its dependencies. An attempt was made to load a program with an incorrect format.
This problem seems to occur rather a lot and it seems there are different causes for it to occur. I have had this problem today and the information I found on the internet did not help at all. I have tried setting System.Data to not copy local, but then it just started with other libraries. I have also changed the .net version in my web.config, but that did not solve my problem either.
The only real difference that I could find between the old and new server was the fact that the new server was 64-bits. So looked into that and found an option in the advanced settings of an app pool in IIS7, named "Enable 32-Bit Applications".
After setting it to true, everything worked as before.
16 December 2010
Getting the ISO weeknumber in SQL Server 2005 (and earlier)
I just discovered that SQL Server often returns the wrong week number when using DatePart(wk, @date).
For instance, SELECT DatePart(wk, '2010-12-17') returns 47 while it should be 46.
This is because SQL Server starts counting weeks from 1 Jan, so 1 Jan is always in week 1 of the year.
The ISO standard states that week 1 is the first week with 4 days in it.
The following code can be used (with @date being the datetime) to return the ISO week
(From windowsitpro.com)
Since SQL2008, DatePart supports the ISO Week, by calling:
For instance, SELECT DatePart(wk, '2010-12-17') returns 47 while it should be 46.
This is because SQL Server starts counting weeks from 1 Jan, so 1 Jan is always in week 1 of the year.
The ISO standard states that week 1 is the first week with 4 days in it.
The following code can be used (with @date being the datetime) to return the ISO week
CREATE FUNCTION GetISOWeek(@date DateTime)
RETURNS INTEGER
AS
BEGIN
declare @ISOweek INTEGER;
select @ISOweek = datepart(wk ,@date) + 1 - datepart(wk, 'Jan 4,' + CAST(datepart(yy, @date) as CHAR(4)));
if (@ISOweek = 0)
select @ISOweek = datepart(wk, 'Dec ' + CAST(24 + datepart(day, @date) AS CHAR(2)) + ',' + CAST(datepart(yy, @date) - 1 as CHAR(4))) + 1 RETURN @ISOweek
END
GO(From windowsitpro.com)
Since SQL2008, DatePart supports the ISO Week, by calling:
DatePart(isowk, @date) or DatePart(isoww, @date)
Labels:
SQL
,
SQL Server
,
weeknumber
Get the date of the Nth day of a given year and weeknumber
Given a year and a weeknumber, you can calculate the date of the Nth day of that week. The best way to do this as far as I have been able to come up with is this:
(int)culture.DateTimeFormat.FirstDayOfWeek + 1;
if(dayOfWeek <= 0) dayOfWeek += 7;
The
public static DateTime GetNthDayOfWeek(int year, int weeknumber, int n, CultureInfo culture){ // Get 1st jan of given year DateTime date = new DateTime(year, 1, 1);
// Get the weeknumber of this 1st jan int beginWeek = GetWeekNumber(date, culture); if (beginWeek >= 52) beginWeek = 0;
// determine how many weeks to jump ahead for the requested week int weeksToProgress = weeknumber - beginWeek;
// Add this number of weeks date = culture.Calendar.AddWeeks(date, weeksToProgress);
// move to nth day and return int dayOfWeek = (int)culture.Calendar.GetDayOfWeek(date) - (int)culture.DateTimeFormat.FirstDayOfWeek + 1;
if(dayOfWeek <= 0) dayOfWeek += 7;
return date.AddDays(n - dayOfWeek);}
The
GetWeekNumber method is of course the one as described in the post before this one.
Labels:
.net
,
C#
,
datetime
,
weeknumber
Get the culture specific weeknumber in .NET
The easiest way to get a culture specific weeknumber is the following:
Where culture is the culture you wish to use for determining the weeknumber. To use the current culture, you can use the following:
culture.Calendar.GetWeekOfYear(inputDate, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek);Where culture is the culture you wish to use for determining the weeknumber. To use the current culture, you can use the following:
CultureInfo culture = CultureInfo.CurrentCulture;
Labels:
.net
,
C#
,
datetime
,
weeknumber
Subscribe to:
Posts
(
Atom
)



