How can I implement a complex sinusoidal function? - c#

The following is the 2d complex sinusoidal function,
u0 and v0 represent Fundamental Frequencies in X and Y directions respectively.
I need to implement that sinusoidal function in this present form so that, I can plot it and save it in a Bitmap image file.
How can I represent j (imaginary number)?
What values should I assign to u0 and v0 respectively to plot that Sinusoidal Function?
Can anyone give me any hint?
Edit:
here is my use-case: ... ... I need to implement Gabor Filter using both spatial and frequency domain equations. In the link ... http://www.cs.utah.edu/~arul/report/node13.html ..., you can see that there are several equations. (14) is the equation of Gabor Filter in spatial domain. (15) is the equation of Gabor Filter in frequency domain. Hence, my question.

You need to actually compute the complex value with real math
For that you can exploit this commonly used formula (usually used in DFT/DFFT):
e^(j*x) = cos(x) + j*sin(x)
Now as you do not have complex numbers so you need to handle complex value as 2 element vector cplx = re + j*im so:
e^(-j*2*pi*(u0*x+v0*y)) = cos(-2*pi*(u0*x+v0*y)) + j*sin(-2*pi*(u0*x+v0*y))
---------------------------------------------------------------------------
re(x,y) = cos(-2*pi*(u0*x+v0*y))
im(x,y) = sin(-2*pi*(u0*x+v0*y))
Plot the values
Complex domain has 2 parts (re,im) and your function is 2D so that leads you to 4D graph. You need to convert it to something humans can comprehend there are many ways I would go for 3D graph where:
x,y is the position (same as input variables)
z is Real part re
color is Imaginary part im encoded as color scale (similar to IR images) or gray scale
Do not forget to rotate project the graph so it is visible from side a bit tilted not hiding important features. Here see example of 3D graph with color coding:
HSV histogram showed as 3D graph
Of coarse the output style depends on your task what you need to see/emphasize what is important and what not. You can for example plot 2D power graph instead:
x,y is the position (same as input variables)
color is sqrt(re*re+im*im) encoded as color scale or gray scale
Or you can create 2 separate plots one for re and one for im see some examples here:
What should be the input and output for an FFT image transformation?

Related

Indoor path-finding c# wpf

I am currently developing an indoor path-finding. I have multiple floors and different rooms. How will I be able to implement a* algorithm in the images of each floor using c# wpf?
I use spatial A* for the game I'm working on.
Spatial A* uses movement "cost" to work out the best route between two points. The cost mentions is supplied by an array. Usually a 2d array of number - float uint or whatever.
Moving through a square/cell at position x,y thus costs the number in that 2d array. EG costs[2,3] would be the cost of movement through the cell 2 cells across from the left and 3 down from the top of an imaginary grid projected onto your "room".
If the move is diagonal then there's also a multiplier to consider but that will be in whichever implementation you go with.
Hence you need a 2d costed array per floor.
You would need to somehow analyse your pictures and work out an appropriate size for a costed cell. This should match the smallest size of a significant piece of terrain in your floor.
You would then translate your picture into a costed array. You've not told us anywhere near enough to tell you specifically how to do that. Maybe that would have to be a manual process though.
Blocked cells get the max number, empty cells get 1. Depending on your requirements that might be that. Or alternatively you might have actors leaping tables and chairs etc.
You give the pathing algorithm start and target location (x,y), the appropriate costed array and it works out the cheapest route.

Generate Voronoi diagram without using Fortune's algorithm

I'm hoping to create a Voronoi landscape in Unity in C#. I looked at a number of Unity Project files, but they all implement Fortune's algorithm, which is completely over my head. Are there any other methods of generating Voronoi diagram (that is easier to understand)?
Slow performance is completely fine with me.
Much appreciated!
Sidenote: Since I'm working in Unity and need to generate 2D/3D mesh from Voronoi diagram, per-pixel distance check won't work :,(
On second thought, maybe I could use a 2D array of Vector2s instead of pixels, that are 1.0 unit spaced apart in x and z axis.
There is a very simple way to create an approximated Voronoi diagram VD. For every Site s that should define a cell in the VD (2D-plane) you center a cone at s with constant slope and a certain height. Then you look from above onto that landscape of cones (where all the spikes are visible). The boundary where the different cones meet (projected to the 2D-plane) is the (approximated) Voronoi diagram.
(Image Source)
As you requested in the comments, to get the actual edge data seems not so easy. But there could be some graphical routines to generate them by intersecting the cones.
An alternative is to compute a Delaunay triangulation of the given point set. There are some implementation referenced in this related post (also simple approximations are mentioned). Then you compute the dual graph of your triangulation and you have the Voronoi diagram. (Dual graph means that for every for every edge AB in the triangulation there exists an edge in the VD bisecting the space between the two vertices A and B, and for every triangle there exists a vertex in the VD where the dual edges meet.) Othwerwise there are also many C# Voronoi implementations around: Unity-delaunay, but as you mentioned using the Fortune approach.
If you want to code everything yourself you may compute a triangulation of the points with brute force for n points in O(n^2) time. Then apply in-circle tests and edge flips. That is, for every triangle t(abc) create a circle C defined by the three vertices of t. Then check if there lies another point d of your point set inside C. If so, then flip the edge that is in t as well as forms an edge in the triangle with d. This flipping is done until all triangles fulfil the empty circle property (Delaunay condition). Again with brute force will take O(n^2) time. Then you can compute the dual graph as mentioned above.
(Image Source)
"Easiest? That's the brute-force approach: For each pixel in your output, iterate through all points, compute distance, use the closest. Slow as can be, but very simple. If performance isn't important, it does the job."
[1] Easiest algorithm of Voronoi diagram to implement?

Machine learning to recognize different dollar bills [duplicate]

I'm having some images, of euro money bills. The bills are completely within the image
and are mostly flat (e.g. little deformation) and perspective skew is small (e.g. image quite taken from above the bill).
Now I'm no expert in image recognition. I'd like to achieve the following:
Find the boundingbox for the money bill (so I can "cut out" the bill from the noise in the rest of the image
Figure out the orientation.
I think of these two steps as pre-processing, but maybe one can do the following steps without the above two. So with that I want to read:
The bills serial-number.
The bills face value.
I assume this should be quite possible to do with OpenCV. I'm just not sure how to approach it right. Would I pick a FaceDetector like approach or houghs or a contour detector on an edge detector?
I'd be thankful for any further hints for reading material as well.
Hough is great but it can be a little expensive
This may work:
-Use Threshold or Canny to find the edges of the image.
-Then cvFindContours to identify the contours, then try to detect rectangles.
Check the squares.c example in opencv distribution. It basically checks that the polygon approximation of a contour has 4 points and the average angle betweeen those points is close to 90 degrees.
Here is a code snippet from the squares.py example
(is the same but in python :P ).
..some pre-processing
cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
# find contours and store them all as a list
count, contours = cvFindContours(gray, storage)
if not contours:
continue
# test each contour
for contour in contours.hrange():
# approximate contour with accuracy proportional
# to the contour perimeter
result = cvApproxPoly( contour, sizeof(CvContour), storage,
CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0 );
res_arr = result.asarray(CvPoint)
# square contours should have 4 vertices after approximation
# relatively large area (to filter out noisy contours)
# and be convex.
# Note: absolute value of an area is used because
# area may be positive or negative - in accordance with the
# contour orientation
if( result.total == 4 and
abs(cvContourArea(result)) > 1000 and
cvCheckContourConvexity(result) ):
s = 0;
for i in range(4):
# find minimum angle between joint
# edges (maximum of cosine)
t = abs(angle( res_arr[i], res_arr[i-2], res_arr[i-1]))
if s<t:
s=t
# if cosines of all angles are small
# (all angles are ~90 degree) then write quandrange
# vertices to resultant sequence
if( s < 0.3 ):
for i in range(4):
squares.append( res_arr[i] )
-Using MinAreaRect2 (Finds circumscribed rectangle of minimal area for given 2D point set), get the bounding box of the rectangles. Using the bounding box points you can easily calculate the angle.
you can also find the C version squares.c under samples/c/ in your opencv dir.
There is a good book on openCV
Using a Hough transform to find the rectangular bill shape (and angle) and then find rectangles/circles within it should be quick and easy
For more complex searching, something like a Haar classifier - if you needed to find odd corners of bills in an image?
You can also take a look at the Template Matching methods in OpenCV; another option would be to use SURF features. They let you search for symbols & numbers in size, angle etc. invariantly.

Calculate the volume of a GeometryModel3D

I'm using HelixToolkit's ModelImporter class(Helix 3D Toolkit is a collection of custom controls and helper classes for WPF.) for loading 3D objects from STL files (STereoLithography is a file format native to the stereolithography CAD software created by 3D Systems). The 3D models contain ModelGroup3D object with one or several GeometryModel3D objects inside depending on how many parts the model is comprised from. I would like to calculate the volume of the whole 3D model. I searched for similar questions and the only one answered was this one Calculate volume of 3D mesh which I'm not sure how to reform for my solution. Since I'm a newbie any help is greatly appreciated.
Additionally the models I'm loading are all closed meshes.
Thanks
First convert the surface mesh into a volume mesh. For example, you can convert the triangulated surface mesh into a tetrahedral mesh. One way to do this by constructing the constrained Delaunay triangulation of the surface triangles.
Next, you can get a good estimate of the volume enclosed by the surface mesh, by summing the volumes of all the elements in the volume mesh. For example, by summing the volumes of all the tetrahedrons in the mesh.
The easyest way is computing the Gaussian flux of all triangles.
for the "theory" if your surface is closed then imagine that a vector filed is running through it, then what comes in is equal to what comes out and is also equal to the volume inclosed. for the calculus details check "Gauss theorem" and Green-ostrogradsky integrals.
to compute it:
Vertex v1 ;
Vertex v2 ;
Vertex v3 ;
for (int i = 0;i< triangles.Count; i++)
{
v1 = triangles[i].P0;
v2 = triangles[i].P1;
v3 = triangles[i].P2;
Mesh.volume += (((v2.Y - v1.Y) * (v3.Z - v1.Z) - (v2.Z - v1.Z) * (v3.Y - v1.Y)) * (v1.X + v2.X + v3.X)) / 6;
}
If you have any question don't hesitate, i can develop how you get to that function.
Have fun.

How can you stitch multiple heightmaps together to remove seams?

I am trying to write an algorithm (in c#) that will stitch two or more unrelated heightmaps together so there is no visible seam between the maps. Basically I want to mimic the functionality found on this page :
http://www.bundysoft.com/wiki/doku.php?id=tutorials:l3dt:stitching_heightmaps
(You can just look at the pictures to get the gist of what I'm talking about)
I also want to be able to take a single heightmap and alter it so it can be tiled, in order to create an endless world (All of this is for use in Unity3d). However, if I can stitch multiple heightmaps together, I should be able to easily modify the algorithm to act on a single heightmap, so I am not worried about this part.
Any kind of guidance would be appreciated, as I have searched and searched for a solution without success. Just a simple nudge in the right direction would be greatly appreciated! I understand that many image manipulation techniques can be applied to heightmaps, but have been unable to find a image processing algorithm that produces the results I'm looking for. For instance, image stitching appears to only work for images that have overlapping fields of view, which is not the case with unrelated heightmaps.
Would utilizing a FFT low pass filter in some way work, or would that only be useful in generating a single tileable heightmap?
Because the algorithm is to be used in Unit3d, any c# code will have to be confined to .Net 3.5, as I believe that's the latest version Unity uses.
Thanks for any help!
Okay, seems I was on the right track with my previous attempts at solving this problem. My initial attemp at stitching the heightmaps together involved the following steps for each point on the heightmap:
1) Find the average between a point on the heightmap and its opposite point. The opposite point is simply the first point reflected across either the x axis (if stitching horizontal edges) or the z axis (for the vertical edges).
2) Find the new height for the point using the following formula:
newHeight = oldHeight + (average - oldHeight)*((maxDistance-distance)/maxDistance);
Where distance is the distance from the point on the heightmap to the nearest horizontal or vertical edge (depending on which edge you want to stitch). Any point with a distance less than maxDistance (which is an adjustable value that effects how much of the terrain is altered) is adjusted based on this formula.
That was the old formula, and while it produced really nice results for most of the terrain, it was creating noticeable lines in the areas between the region of altered heightmap points and the region of unaltered heightmap points. I realized almost immediately that this was occurring because the slope of the altered regions was too steep in comparison to the unaltered regions, thus creating a noticeable contrast between the two. Unfortunately, I went about solving this issue the wrong way, looking for solutions on how to blur or smooth the contrasting regions together to remove the line.
After very little success with smoothing techniques, I decided to try and reduce the slope of the altered region, in the hope that it would better blend with the slope of the unaltered region. I am happy to report that this has improved my stitching algorithm greatly, removing 99% of the lines reported above.
The main culprit from the old formula was this part:
(maxDistance-distance)/maxDistance
which was producing a value between 0 and 1 linearly based on the distance of the point to the nearest edge. As the distance between the heightmap points and the edge increased, the heightmap points would utilize less and less of the average (as defined above), and shift more and more towards their original values. This linear interpolation was the cause of the too step slope, but luckily I found a built in method in the Mathf class of Unity's API that allows for quadratic (I believe cubic) interpolation. This is the SmoothStep Method.
Using this method (I believe a similar method can be found in the Xna framework found here), the change in how much of the average is used in determining a heightmap value becomes very severe in middle distances, but that severity lessens exponentially the closer the distance gets to maxDistance, creating a less severe slope that better blends with the slope of the unaltered region. The new forumla looks something like this:
//Using Mathf - Unity only?
float weight = Mathf.SmoothStep(1f, 0f, distance/maxDistance);
//Using XNA
float weight = MathHelper.SmoothStep(1f, 0f, distance/maxDistance);
//If you can't use either of the two methods above
float input = distance/maxDistance;
float weight = 1f + (-1f)*(3f*(float)Math.Pow(input, 2f) - 2f*(float)Math.Pow(input, 3f));
//Then calculate the new height using this weight
newHeight = oldHeight + (average - oldHeight)*weight;
There may be even better interpolation methods that produce better stitching. I will certainly update this question if I find such a method, so anyone else looking to do heightmap stitching can find the information they need. Kudos to rincewound for being on the right track with linear interpolation!
What is done in the images you posted looks a lot like simple linear interpolation to me.
So basically: You take two images (Left, Right) and define a stitching region. For linear interpolation you could take the leftmost pixel of the left image (in the stitching region) and the rightmost pixel of the right image (also in the stitching region). Then you fill the space in between with interpolated values.
Take this example - I'm using a single line here to show the idea:
Left = [11,11,11,10,10,10,10]
Right= [01,01,01,01,02,02,02]
Lets say our overlap is 4 pixels wide:
Left = [11,11,11,10,10,10,10]
Right= [01,01,01,01,02,02,02]
^ ^ ^ ^ overlap/stitiching region.
The leftmost value of the left image would be 10
The rightmost value of the right image would be 1.
Now we interpolate linearly between 10 and 1 in 2 steps, our new stitching region looks as follows
stitch = [10, 07, 04, 01]
We end up with the following stitched line:
line = [11,11,11,10,07,04,01,02,02,02]
If you apply this to two complete images you should get a result similar to what you posted before.

Categories

Resources