<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Visual Core &#187; VB.NET</title>
	<atom:link href="http://visualcore.com/index.php/tag/vb-net/feed/" rel="self" type="application/rss+xml" />
	<link>http://visualcore.com</link>
	<description>An amazing repository of useless junk</description>
	<lastBuildDate>Sat, 18 Jun 2011 05:12:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>.NET 4.0: Parallel Programming</title>
		<link>http://visualcore.com/index.php/2009/06/net-4-0-parallel-programming/</link>
		<comments>http://visualcore.com/index.php/2009/06/net-4-0-parallel-programming/#comments</comments>
		<pubDate>Sat, 06 Jun 2009 06:35:34 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallel]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=32</guid>
		<description><![CDATA[.NET 4.0 Beta 1 contains some interesting parallel programming constructs. Sounds like a great idea, I&#8217;m really interested to see where this is going.
]]></description>
			<content:encoded><![CDATA[<p>.NET 4.0 Beta 1 contains some interesting <a href="http://code.msdn.microsoft.com/ParExtSamples" target="_BLANK">parallel programming</a> constructs. Sounds like a great idea, I&#8217;m really interested to see where this is going.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2009/06/net-4-0-parallel-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Smarter Data Caches</title>
		<link>http://visualcore.com/index.php/2008/08/smarter-data-caches/</link>
		<comments>http://visualcore.com/index.php/2008/08/smarter-data-caches/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 08:39:50 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Data/DB]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=81</guid>
		<description><![CDATA[ASP.NET provides a way of storing data so when the application needs it again, it can be loaded from the current process&#8217; memory rather than making another round trip to the database server. This concept is founded on the idea of temporal locality, that is, if it&#8217;s requested once, there is a high likelihood it [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.NET provides a way of storing data so when the application needs it again, it can be loaded from the current process&#8217; memory rather than making another round trip to the database server. This concept is founded on the idea of temporal locality, that is, if it&#8217;s requested once, there is a high likelihood it will be needed again in the near future. A time limit is set on the cached item, and when that limit expires, the data is no longer valid.</p>
<p>Variable, file and database cache dependencies extend this capability to allow the user to link the cache to the data source. When the data is modified, and therefore no longer valid, the cache can be automatically cleared. Aside from the fact that it has an affinity for SQL Server 2005, it&#8217;s a decent system. However, in my opinion, the key issue is not *when* to cache, but *what* to cache. The theory of data caching is actually based on two concepts, temporal locality AND spacial locality (when one thing is requested, data near it will also soon be requested). ASP.NET puts the burden of spacial locality solely on the shoulders of the developer.</p>
<h4>A data access scenario</h4>
<p>Here is a typical scenario: a user arrives at a web site, say it&#8217;s an e-commerce system. The user searches for &#8220;widget&#8221;, and gets 500 results for widgets. The user then searches for &#8220;widget x&#8221; and gets 100 results, finding the item they want in the first page.</p>
<p>Next, the user clicks on widget-x and then views the product&#8217;s details, including thumbnails, specifications, and related products. Deciding to look at related products, they click on widget-y, widget-z and widget-v; all of witch show widget-x in their &#8220;related items&#8221;. The user then returns to the details page for widget-x and adds the item to their shopping cart, and then proceeds to check-out. Checkout is three stages, finally showing a receipt of the user&#8217;s order.</p>
<p>Without a data cache, this system could load the product record for widget-x a total of eleven times, depending on how the checkout pages are implemented. Also, product details and related products are loaded twice for the product details page for widget-x and possibly again for the other widgets.</p>
<h4>Performance &amp; cache</h4>
<p>Even a cursory thought about performance should bring to mind the need for a data cache to avoid unnecessary trips to the database server. However, cache has a lot of knobs and it&#8217;s not immediate how and when the data should be cached. The following is a list of variations on how a cache system could be used to minimize the impact of this common user behavior:</p>
<div style="background-color: #eee; padding: 0 6px;">
<h4>1) Cache only the highest level</h4>
<p>Product details by the product id, load everything else as needed. This still does not make use of spacial locality.</p>
<h4>2) Cache everything grouped</h4>
<p>Product and related data are stored under the product id as the key. This makes use of spacial locality, but is an inefficient use of memory, since similar related data could be cached multiple times for different products. Also, it logically segments the cache by the page functionality, since the product details page will likely have a distinct data set from a search results page.</p>
<h4>3) Cache everything individually</h4>
<p>Products are stored under the product id, details are stored under their detail id&#8217;s, related products are stored as individual records under their own id&#8217;s. This approach is highly granular, fixing this issue of segmentation in the last method, but is much more of a burden to the developer to manage. For a team working on a single project, this type of system would require a class to manage access to the cache to ensure cache coherency.</p>
<h4>4) Cache the page output</h4>
<p>The page is rendered once, and the output is stored. Future requests simply return the pre-rendered HTML. This is like 2) above, causing each page to have their own cache, never sharing data. One could argue that this method is perhaps safer, since no individual objects are being cached, and therefor no mixing of old and new data can occur.</p>
<h4>5) Cache the page output in blocks</h4>
<p>Each part of the page must be composed of user controls, and then the user controls are rendered once. Future requests for the controls simply return the pre-renedered HTML. This is similar to 3) above, where the controls used across multiple pages can all benefit from a more granular cache.</p></div>
<p>And the list goes on. Furthermore, within each one of these methods, there are more detailed options of how to invalidate the cache, and exactly how to key the various bits of cached data. It&#8217;s a lot to manage for the developer, and it gets much worse if there is no system-wide plan for a team of developers.</p>
<h4>Relational locality</h4>
<p>Unfortunately, I&#8217;m not proposing a solution, however, I do have some thoughts on a possible approach. I think the cache concept of spacial locality could be extended to relational locality. That is, when a record is accessed, its related records will likely be accessed also. Due to the highly relational nature of relational databases, this type of system should be relatively easy to implement in an automated fashion. The types of cache controls needed would be something like relation-levels to traverse when requesting data.</p>
<p>A radical approach would be to create a pass-through layer where all data requests get sent to a data cache. This cache decides what to pull from the database based on the data requested. In this type of model, the data cache would essentially replace the data access layer. When selecting related data to fetch, two approaches could be taken:</p>
<div style="background-color: #eee; padding: 0 6px;">
<h4>1) A design-time process</h4>
<p>A process could be run which compiles all requests down to stored procedures for the current build. Essentially the cache system would analyze all requests and build a working set of queries based on the requests from the code.</p>
<h4>2) A run-time process</h4>
<p>The cache/data layer could actively monitor real-time requests and change the stored procedures based on usage statistics. So if a major advertising campaign caused a flood of traffic to one page, and spilled over to related pages, the system could actively cache all data for the page, and related pages on the first visit to the root page (the one that was advertised).</p></div>
<p>I realize that this type of system requires a major development investment, and may not be practical at this time. However, it seems a smarter and simpler cache system is needed if ASP.NET aims to enable the average developer to create massive web systems out of the box.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/08/smarter-data-caches/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Twiddling Bits in VB.NET</title>
		<link>http://visualcore.com/index.php/2008/06/twiddling-bits-in-vb-net/</link>
		<comments>http://visualcore.com/index.php/2008/06/twiddling-bits-in-vb-net/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 01:25:36 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=86</guid>
		<description><![CDATA[Setting and reading individual bits (aka bit masking) is a powerful tool and something I&#8217;ve always had a hard time with. Tutorials and documentation explain how to set and read bits, but they seem to fall short in explaining what is actually going on under the covers.
Binary Basics
All data in a computer is represented as [...]]]></description>
			<content:encoded><![CDATA[<p>Setting and reading individual bits (aka bit masking) is a powerful tool and something I&#8217;ve always had a hard time with. Tutorials and documentation explain how to set and read bits, but they seem to fall short in explaining what is actually going on under the covers.</p>
<h4>Binary Basics</h4>
<p>All data in a computer is represented as bits. In VB.NET the Integer type is a 32-bit integer and is represented internally as 32 bits. For example:</p>
<p><code><br />
Dim i As Integer = 4<br />
</code></p>
<p>Internally, the variable i is represented as the following 32 bits:</p>
<p><code><br />
Bits:   0000 0000 0000 0000 0000 0000 0000 0100<br />
Index: 31                                     0<br />
</code></p>
<p>Each bit has an index, starting from 0 at the right and ending with 31 at the left. The value of each bit is 2^x, where x is the bit&#8217;s index in the bit string, so the right-most bit (more commonly known as the Least Significant bit) has a decimal value of 2^0 or 1. The left-most bit (or Most Significant bit) has a decimal value of 2^31 or 2,147,483,648. </p>
<p>The value of the number is the sum of all &#8220;1&#8243; bits in the string. For example:</p>
<p><code><br />
[ 0111 ] = 2^2 + 2^1 + 2^0<br />
         = 4 + 2 + 1<br />
         = 7<br />
</code></p>
<h4>VB&#8217;s Bit Operators</h4>
<p>Visual Basic provides the tools needed to start editing individual bits, namely the &#8220;bitwise&#8221; logical operators. The following is a list of bitwise operators along with a basic idea of their intended purpose. The first three operators below (And, Or, XOr) enable you to use two bit strings to produce a new third string. The last operator (Not), operates on just one bit string alone.</p>
<p><code><br />
And - Lets you check for a specific pattern<br />
Or  - Turns on a specified pattern, leaving other bits alone<br />
XOr - Chooses one flag or the other, but not both<br />
Not - Inverts all bits (1 becomes 0, and vice versa)<br />
</code></p>
<p>Here are a few examples of two given input strings along with the output created. These examples show what happens conceptually, actual VB code would not have literal binary strings.</p>
<p><code><br />
1111 And 1010 = 1010<br />
1010 And 0101 = 0000</p>
<p>1000 Or 0001 = 1001<br />
1010 Or 1011 = 1011</p>
<p>1000 XOr 1010 = 0010<br />
1111 XOr 1111 = 0000</p>
<p>Not 1001 = 0110<br />
Not 1111 = 0000<br />
Not 0000 = 1111<br />
</code></p>
<p>As mentioned earlier, in real VB code the bit string is hidden in the Integer data type. The bitwise operators can be used to see the actual contents of these bit strings. The first thing we need is a function that displays the bit string of a given Integer.</p>
<p><code><br />
Sub PrintBinary(ByVal number As Integer)<br />
    Dim bpi As Integer = CInt(Math.Log(Integer.MaxValue, 2))</p>
<p>    Console.WriteLine("Bits/Integer: " &#038; bpi)</p>
<p>    For i As Integer = bpi To 0 Step -1<br />
        Dim bit As Char</p>
<p>        If (number And CLng(2 ^ i)) > 0 Then<br />
            bit = "1"c<br />
        Else<br />
            bit = "0"c<br />
        End If</p>
<p>        Console.Write("{0} ", bit)</p>
<p>        If i > 0 And i Mod 4 = 0 Then<br />
            Console.Write(" ")<br />
        End If<br />
    Next</p>
<p>    Console.WriteLine()<br />
End Sub<br />
</code></p>
<p>The first line of this code establishes the number of bits in an integer by taking the log base 2 of the maximum integer value, which returns ~30.99 and is rounded up to 31 by CInt. </p>
<p><span style="color: #999; font-size: smaller;">(Side note: the reason 30.99 is returned instead of 31 is because the max value of a signed integer is actually 1 less than the value of the most significant bit when negatives are implemented using <a href="http://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">2&#8217;s complement</a>. Understanding this is not critical to the rest of this post.)</span></p>
<p>Next a loop is created to print out each bit from most significant (left) to least significant (right). Each iteration of the loop, the number is And&#8217;ed with the current value of the bit in position i, which is represented by 2 to the i&#8217;th power. This integer value of 2^i creates a bit string with only 1 bit turned on (all other bits are set to zero) and is used to test the same bit in the given number by applying the And operator. </p>
<p>If this And operation returns zero, the bit in the i&#8217;th position of the given number is off, if it returns non-zero, the bit is on. Below is an trace of the loop showing what is actually happening at the bit level when i=1 and i=2. A call to PrintBinary(4) is assumed.</p>
<p><code><br />
The number passed in by the user:<br />
number = 4<br />
    = 0000 0000 0000 0000 0000 0000 0000 0100</p>
<p>First iteration (the bit is off):<br />
i = 1<br />
2^i = 2<br />
    = 0000 0000 0000 0000 0000 0000 0000 0010</p>
<p>If (number And CLng(2 ^ 1)) > 0 Then<br />
4 And 2 > 0 (?)<br />
    = 0000 0000 0000 0000 0000 0000 0000 0000<br />
    = 0 '<- Result, False</p>
<p>Second iteration (the bit is on):<br />
i = 2<br />
2^i = 4<br />
    = 0000 0000 0000 0000 0000 0000 0000 0100</p>
<p>If (number And CLng(2 ^ 2)) > 0 Then<br />
4 And 4 > 0 (?)<br />
    = 0000 0000 0000 0000 0000 0000 0000 0100<br />
    = 4 '<- Result, True<br />
</code></p>
<p>As shown in the two iterations above, the And operator compares the bits in a string 1-by-1 matched up by index. If the bits are both on, the resulting bit in the i'th position in the new bit string is also on. The final result is returned as an Integer. </p>
<p>This becomes more interesting when using the Or operator to create a number with multiple bits turned on. The key is to use numbers that are an integer power of 2, any other numbers will mangle the bit string. Here is an example of setting 3 bits and passing it to our PrintBinary() function:</p>
<p><code><br />
' Note that<br />
'   128 = 2 ^ 7<br />
'   4   = 2 ^ 2<br />
'   2   = 2 ^ 1</p>
<p>PrintBinary(128 Or 4 Or 2)<br />
    = 0000 0000 0000 0000 0000 0000 1000 0110<br />
</code></p>
<p>Notice how the bit positions match exactly the powers of 2 that were passed to PrintBinary, that is bits 7, 2 and 1 are flipped on. </p>
<h4>Real World Bit Strings</h4>
<p>In a real application, it is desirable to simplify this process as much as possible; enter enumerations. An enumeration can be used to give names to individual bits and can then be used in a function as a set of flags or options.</p>
<p><code><br />
Public Enum FileFlags As Integer<br />
    Read = 1<br />
    Write = 2<br />
    Execute = 4<br />
End Enum<br />
</code></p>
<p>Notice that the enumeration values are integer powers of 2, same as above. This enumeration defines 3 flags, Read, Write and Execute. A function can use these flags to indicate how it should operate. This is only appropriate when the flags are not mutually exclusive (meaning more than one flag can be applied at the same time). </p>
<p>To use this enumeration, I have created a dummy function called "SetPermissions". The function is not complete; it is only intended to demonstrate how to read bit flags by using a bit mask.</p>
<p><code><br />
Sub SetPermissions(ByVal flags As FileFlags)<br />
   If (flags And FileFlags.Execute) = FileFlags.Execute Then<br />
       Console.Write("X")<br />
   Else<br />
       Console.Write("-")<br />
   End If</p>
<p>   If (flags And FileFlags.Read) = FileFlags.Read Then<br />
       Console.Write("R")<br />
   Else<br />
       Console.Write("-")<br />
   End If</p>
<p>   If (flags And FileFlags.Write) = FileFlags.Write Then<br />
       Console.Write("W")<br />
   Else<br />
       Console.Write("-")<br />
   End If<br />
End Sub</p>
<p>SetPermissions(FileFlags.Read Or FileFlags.Write)<br />
  => -RW<br />
</code></p>
<p>What is actually happening is that when SetPermissions is called, the "Or" operator is turning on the Read bit and the Write bit in our bit string. The function then applies a bit mask using the "And" operator to test if each individual flag is set.  </p>
<h4>A Few Words on Style</h4>
<p>Enumerations are preferred when multiple options are available for one specific value. They should not be used when the values are logically disconnected. </p>
<p>Constants can be used instead of enumerations, however, enumerations are preferred when the values logically group together (constants also disable intelisense). The Win32 API is a good example of values that should be grouped when ported to .NET. In the C/C++ headers, all values are represented as individual constants, converting them to an enumeration when porting makes working with the API much nicer. </p>
<p>As always, never under any circumstance should literal numbers be used to create a flag. So-called magic numbers without names will confuse the hell out of anyone working on the code after you have written it - yes, including you <img src='http://visualcore.com/wp/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . All literal numbers should be given names, either as enumerations, constants, or at the very least in a local variable.</p>
<p><a href="/Downloads/VisualCore.Lab.BitStrings.zip">Download</a> the bit string example code for this article.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/06/twiddling-bits-in-vb-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sobel Edge Detector in VB.NET</title>
		<link>http://visualcore.com/index.php/2008/03/sobel-edge-detector-in-vb-net/</link>
		<comments>http://visualcore.com/index.php/2008/03/sobel-edge-detector-in-vb-net/#comments</comments>
		<pubDate>Sun, 23 Mar 2008 01:52:51 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Parallel]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Vision]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=96</guid>
		<description><![CDATA[
I recently stumbled onto a C tutorial on edge detection and decided to implement the algorithm in VB.NET. Edge detection is a machine vision technique that attempts to identify interesting parts of an image, such as where one object ends and another begins. One way of finding these areas is to search for sharp changes [...]]]></description>
			<content:encoded><![CDATA[<p><a href="/images/articles/sobel/ss-1-big.jpg" target="_blank"><img src="/images/articles/sobel/ss-1.jpg" alt="Sample Output" style="border: none" /></a><br />
I recently stumbled onto a C tutorial on edge detection and decided to implement the algorithm in VB.NET. Edge detection is a machine vision technique that attempts to identify interesting parts of an image, such as where one object ends and another begins. One way of finding these areas is to search for sharp changes in intensity between each pixel and its neighbors. A source image is processed and an output image is created that highlights the edges found in the source. The output image is a visualization of what the algorithm detected and ultimately these results can be applied to solve a specific problem.</p>
<p>Although the background and mathematical basis for the algorithm are interesting, I’m only going to discuss them briefly and focus on the implementation and performance issues in .NET. If you are curious about the details behind the algorithm, you should check out the original <a href="http://del.icio.us/moldymagnet/edge" target="_blank">articles</a> I found.</p>
<h4>The Algorithm</h4>
<p>To find relative changes in intensity level, the algorithm processes the image one pixel at a time. It looks at the change in intensity to the left and right of the current pixel, stores it and then checks the change in intensity in the pixels above and below the current pixel and stores it as well. The actual process happens one dimension at a time for each pixel (horizontal and then vertical), and then combines the result into two dimensional pixel data, the output image. </p>
<p>As each pixel is encountered, its neighboring pixel’s intensity levels get calculated and then subtracted from the neighbor pixel on the opposite side. The resulting sum of all the pixels is the relative change in intensity at that location. If opposite neighbor pixels are the same color, when subtracted from each other the result will be zero (black).  If the two neighboring pixels were radically different intensity levels the output would be greater than zero. The mechanism that averages the pixels is a weighted matrix, one for vertical (the xMask) and one for horizontal (the yMask):<br />
<code><br />
Dim xMask(,) As Single _<br />
    = New Single(,) {{-1, 0, 1}, _<br />
                     {-2, 0, 2}, _<br />
                     {-1, 0, 1}}</p>
<p>Dim yMask(,) As Single _<br />
    = New Single(,) {{1, 2, 1}, _<br />
                     {0, 0, 0}, _<br />
                     {-1, -2, -1}}<br />
</code><br />
Each element in the matrices represents a bordering pixel, with the center element being the current pixel. The numbers in each matrix is the weighting of the importance of the pixel at that location, so pixels directly above or beside the current pixel are weighted heavier (denoted above with a 2 instead of a 1) than diagonal pixels. Notice that in both matrices, the current pixel is ignored (set to zero). </p>
<p>For the vertical yMask, the strictly horizontal elements are zero, and the opposite is true for the xMask. The elements of each matrix are multiplied by the border pixels intensity levels, and then the results are summed. Since the opposite sides are also opposite signs, the sum is the change in intensity we were looking for. The final step is to add the absolute value of the horizontal and vertical differences in intensity. This process is actually a rough approximation of the mathematical gradient of the image.</p>
<h4>First Implementation: GDI+</h4>
<p>To get things started, I wanted to keep the details of working with the image data to a minimum, so I created the algorithm to work with the infinitely slow GDI+ Bitmap object using the GetPixel and SetPixel methods. The implementation is straight forward:<br />
<code><br />
 1. Create X and Y loops to scan across<br />
     each pixel in the source image<br />
 2. Create I and J loops to process the<br />
     eight border pixels for the current pixel (X,Y)<br />
 3. Get the current border pixel<br />
     Intensity(X + I, Y + J) : 1/3 * (R + G + B)<br />
     using Bitmap.GetPixel on the source image<br />
 4. Multiply the intensity by the appropriate mask<br />
 5. Clamp the output value to [0, 255]<br />
 6. Write the output pixel value to the output<br />
     image (Bitmap.SetPixel)<br />
</code><br />
Below is sample output of the initial implementation:<br />
<a href="/images/articles/sobel/ss-1-big.jpg" target="_blank"><img src="/images/articles/sobel/ss-1.jpg" alt="Sample Output" style="border: none" /></a><br />
This process typically runs in about 3K pixels /second, which sounds fast… but actually takes about 160 seconds to process an 800 x 600 pixel image (480K pixels). So for real-time processing, this method is absolutely out. Although it’s very slow, this method works as expected and was useful to me as a reference renderer as I tested new approaches.</p>
<h4>Take Two: Direct Pixel Access</h4>
<p>The GDI Bitmap object offers a handy function, Lock/UnlockBits(), that returns the raw bytes of memory composing the Bitmap object. By using this function, it is possible to read all pixels in one call, process them, and then write them back in a single call. This is much, much faster than using Get/SetPixel() methods which operate on a single pixel for each read and write. The intense down side of LockBits is that you no longer have friendly access to the pixel by X and Y coordinates, and documentation is pretty bad.<br />
When calling LockBits(), you specify what format you want the data to be returned in. The pixels get returned as a contiguous array of bit data, and you are charged with picking it apart.  For my purposes, I’ve forced the format to always be 24 bit RGB. The function returns a one dimensional array of bytes. Each pixel is encoded according to the format specified, so in my case, there are 3 bytes for each pixel (R, G and B). To emulate two dimensions, a “stride” value is given, which lets you know how many bytes there are per line, along with a “height” which is the total number of scan lines. So each pixel can still be accessed with X and Y coordinates by using the following formula:<br />
<code><br />
Pixel.Red = Array[stride * Y + X * 3]<br />
Pixel.Blue = Array[stride * Y + X * 3 + 1]<br />
Pixel.Green = Array[stride * Y + X * 3 + 2]<br />
</code><br />
Notice that the Y value is multiplied by the width of the scan line and X is multiplied by the amount of byte data per pixel, the 3 here is for RGB. The first byte at this location is red, the next byte is green and the last byte is blue, which is why 0, 1 and 2 are added to X.<br />
To make this logic less painful, I created a wrapper class for the bitmap object which has its own GetPixel and SetPixel methods. This class locks the bits on the image when it loads and then operates on the array. It implements IDisposable, and when Dispose is called, it calls UnlockBits on the original bitmap image, committing all changes to the image at once.<br />
This implementation runs at around 50Kp/s, a huge improvement of over the original. Processing the pixels in blocks greatly improved performance, but this is still a little too slow for any real-time application. The 800&#215;600 image still takes about 10 seconds to process with this new method.</p>
<h4>Take Three: Divide and Conquer</h4>
<p>The next approach I took was to reduce the input data by splitting the image in two. The actual split is done by creating Rectangle objects and then passing these rectangles to LockBits when retrieving the image data.<br />
Since I wanted to test different numbers of splits, it became very important to *neatly* keep track of work units, that is, what part of the image was actually being processed. Also, I had another idea in mind for the next implementation, so I wanted this idea of work units to be reusable. To facilitate this, I created a class called ImageWorkUnit with the following properties:<br />
<code><br />
Image:    The input Bitmap which is being processed<br />
WorkArea: The Rectangle of the area to process<br />
Result:   The output Bitmap shared by all workers<br />
</code><br />
Using this new work unit class, I then created a method to split the image into multiple work units (the number of units is variable) and then a loop to process each loop sequentially. Right now, stop and make a quick estimate of how fast this new method will run using two units (splitting the image in half). Before I ran this new implementation, I made an approximation of no more than few percent speed increase. I was wrong. This method runs at a blazing 450Kp/s, a vast improvement over the direct pixel access method.<br />
As happy as I was with the result, it was a little disturbing and I decide to do some tests. I varied the number of divisions, and much to my surprise, using only one division it ran at the same speed, 450Kp/s. This implied that the speed increase was not caused by dividing the image, but by something else. Here is the original processing loop:<br />
<code><br />
For y As Integer = 0 To inImg.Height - 1<br />
    For x As Integer = 0 To inImg.Width – 1<br />
    ...<br />
    Next<br />
Next<br />
</code><br />
Now here is the new processing loop for the work unit based implementation:<br />
<code><br />
For y As Integer = 0 To area.Height - 1<br />
    For x As Integer = 0 To area.Width - 1<br />
    ...<br />
    Next<br />
Next<br />
</code><br />
The speed increase was due to the fact that I was no longer accessing the Height and Width properties of the image (it was also accessed in the body of the loop). It turns out, the Height and Width properties of the Bitmap object are not exactly optimized. By simply not accessing these properties inside the loop, I got a speed up of about 900%.</p>
<h4>Take Four: Use the Cores Luke</h4>
<p>In the final implementation, I created a new class to spawn separate threads to process the image in parallel. This function gets the processor count, and then splits the image that many times and spawns threads to process the chunks.<br />
Oddly, this method runs at either 500Kp/s *or* around 700Kp/s. The discrepancy is because of the thread scheduler. In the new class I created, I simply spawn threads, fire them off and leave it up to the thread scheduler to pick a core to execute on. If both threads execute on the same core, the result is 500Kp/s, when they happen to run on different cores, the speed up to 700Kp/s occurs. I’m not exactly sure how to get around this in managed code – if you have any ideas, please post a comment and let me know.<br />
So with the fastest algorithm, and my fingers crossed, it can process that 800&#215;600 image in about 0.6 seconds (down from 2.5 minutes), which is actually a reasonable rate for real time applications.<br />
<a href="/downloads/SobelEdgeDetection.zip">Download</a> the Sobel edge detector code and sample images.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/03/sobel-edge-detector-in-vb-net/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Simple Recursive Blob Detection</title>
		<link>http://visualcore.com/index.php/2008/02/simple-recursive-blob-detection/</link>
		<comments>http://visualcore.com/index.php/2008/02/simple-recursive-blob-detection/#comments</comments>
		<pubDate>Sat, 09 Feb 2008 17:00:34 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Vision]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=102</guid>
		<description><![CDATA[Continuing my quest for useless VB.NET code, I am going to delve into blob detection. When I say blob, I am not referring to Binary Large OBjects (like database BLOBs), but blobs in the visual sense &#8211; a contiguous area of one specific color (in the simplest case). A good example of blob detection is [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing my quest for useless VB.NET code, I am going to delve into blob detection. When I say blob, I am not referring to Binary Large OBjects (like database BLOBs), but blobs in the visual sense &#8211; a contiguous area of one specific color (in the simplest case). A good example of blob detection is the magic wand tool in a paint program. When you click an area all similar and contiguous pixels are included to create a selection area. Another is optical character recognition (OCR), where the blobs that are found are possible characters.<br />
The type of blob recognition I am going to describe is a very simple algorithm that does not use calculus – this is a straight forward recursive algorithm, however it may not be the best candidate for the job.</p>
<h4>The Goal</h4>
<p>The goal of this algorithm is to be able to identify the blobs in the following black and white image.<br />
<img src="/images/articles/blobs/1-original.gif" alt="Source image" /><img src="/images/articles/blobs/3-BlobsSelected.gif" alt="Source with blobs selected"/><br />
The first image above is the source image, and the second is the source with each pixel outlined in black and the blobs outlined in red. I will define a blob as a collection of pixels that share any of the 8 possible common borders. Notice that a blob could be defined using only 4 borders (that is, don’t count diagonal boarders), which would change the top two blobs in the example.</p>
<h4>The Algorithm</h4>
<p>The algorithm is simply going to count the number of pixels in the blob. This could easily be extended to actually collect the pixel locations to create a region. Keep in mind that in this example black pixels are “on” and white pixels are “off”. The basic idea is as follows:<br />
<code><br />
1. To initialize, create a copy of the image, which will<br />
   be altered to mark the progress of the algorithm<br />
2. Base Cases<br />
   a. If a pixel is off, return zero<br />
   b. If a pixel is out of bounds, return zero<br />
3.Recursive Case<br />
   a. If a pixel is on<br />
      i.  Turn off the current pixel<br />
      ii. Return 1 plus the sum of all 8 surrounding<br />
          pixels<br />
</code><br />
And that’s the entire algorithm. </p>
<h4>An Example: BlobSize(6, 1)</h4>
<p>An example might help to clear up any confusion. Let’s get the size of the blob located at pixel (6, 1). The following image is a visual representation of what the algorithm is going to do in the first two recursive calls.<br />
<img src="/images/articles/blobs/4-testing61.gif" alt="BlobSize at 6,1" /><img src="/images/articles/blobs/5-testing72.gif" alt="BlobSize at 7,2"/><br />
Assume our function is BlobSize(x as Integer, y as Integer) and returns an Integer (the number of pixels in the blob), and we are calling BlobSize(6, 1). We go back to the algorithm: step 1, this pixel is on and it is within the boundaries of the image, so we are not at a base case &#8211; skip to step 2. Step 2, the pixel is on, so turn it off and then return 1 + the sum of all surrounding pixels, that is:<br />
<code><br />
Return _<br />
   BlobSize(5, 0) + BlobSize(6, 0) + BlobSize(7, 0) + _<br />
   BlobSize(5, 1) + 1 + BlobSize(7, 1) + _<br />
   BlobSize(5, 2) + BlobSize(6, 2) + BlobSize(7, 2)<br />
</code><br />
Notice how each term in the return statement corresponds to a pixel from the 3&#215;3 box in the image above (the 1 being the current pixel). The results from pixels 1, 2, 3, 4, 5, 6, and 7 will all be base cases and return 0 since they are off. But notice that pixel 8 is another recursive case, where it’s surrounding 8 pixels will be tested and the blob will expand. This function will ultimately return 5.<br />
Here is the code for BlobSize():<br />
<code><br />
Private Function BlobSize(ByVal image As Bitmap, _<br />
                 ByVal x As Integer, ByVal y As Integer) _<br />
                 As Integer<br />
    If x < 0 Or x >= image.Width Or _<br />
       y < 0 Or y >= image.Height Then<br />
        Return 0<br />
    End If<br />
    Dim c As Color = image.GetPixel(x, y)<br />
    If c.R = 255 And c.G = 255 And c.B = 255 Then<br />
        Return 0<br />
    End If<br />
    image.SetPixel(x, y, Color.White)<br />
    Dim size As Integer = 1<br />
    For i As Integer = -1 To 1<br />
        For j As Integer = -1 To 1<br />
            If i = 0 And j = 0 Then Continue For<br />
            size += BlobSize(image, x + i, y + j)<br />
        Next<br />
    Next<br />
    Return size<br />
End Function<br />
</code></p>
<h4>The Problem</h4>
<p>Here is a comparison of the blob size (n) to the number of recursive calls (r):<br />
<code><br />
    n |     r<br />
---------------<br />
    5 |    41<br />
    6 |    49<br />
   13 |   105<br />
 1125 |  9001<br />
 1350 | 10801<br />
 2925 | 23401<br />
</code><br />
The performance of this algorithm is 8n + 1 or O(n) in <a href="http://en.wikipedia.org/wiki/Big_O_notation" target="_blank">Big O</a> notation. This causes a problem because the algorithm is recursive.  The problem occurs for larger values of n. On my machine, the upper limit was 26705 recursions on a 196 x 156 pixel, solid black image. At this point the system ran out of stack space and I got a StackOverflowException.</p>
<h4>Conclusion</h4>
<p>This algorithm will work for images no larger than 3338 pixels on my machine; however the stack space can possibly vary from machine to machine. There are several sneaky tricks that could be done to make it work on larger images, but the bottom line is that this algorithm is not well suited for the task.<br />
Ultimately, you must resort to using calculus to solve this problem with larger image sizes. I will show an implementation using the Gaussian or Laplaceian method some time in the future.</p>
<p>You can download the code and test images for BlobSize() <a href="/downloads/articles/blobs/VisualCore.Blobber.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/02/simple-recursive-blob-detection/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Wave Analyzer</title>
		<link>http://visualcore.com/index.php/2008/02/wave-analyzer/</link>
		<comments>http://visualcore.com/index.php/2008/02/wave-analyzer/#comments</comments>
		<pubDate>Wed, 06 Feb 2008 02:01:05 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Modeling]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Waves]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=105</guid>
		<description><![CDATA[I&#8217;ve posted some new code under the projects section, a wave analyzer. It&#8217;s still pretty early in development, but you can use it to see how waves actually move, rather than just looking at formulas. 
A simple sine wave is composed of 4 basic components: amplitude, frequency, wave length and phase angle. The wave analyzer [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve posted some new code under the projects section, a wave analyzer. It&#8217;s still pretty early in development, but you can use it to see how waves actually move, rather than just looking at formulas. </p>
<p>A simple sine wave is composed of 4 basic components: amplitude, frequency, wave length and phase angle. The wave analyzer allows you to add waves to the graph, and then tweak these components to see how it effects the output.</p>
<p>It gets interesting when you add multiple waves and then combine their output. This shows a similar output to what you would see if you had several wave generators hooked up to a string (in real life) and looked at their combined effect.</p>
<p>To get started, first go download the <a href="/downloads/waveanalyzer1.0.zip">app</a> (or <a href="/downloads/waveanalyzer1.0_src.zip">source code</a>). Run the application and then follow these steps to get something like this:<br />
<br /><img src="/images/proj-9-ss-2.gif" alt="Wave Analyzer Screenshot" /><br />
<code><br />
1. Click "Add Waveform"<br />
2. Click "Add Waveform" again to get a second wave<br />
3. Now in the Function Generators window, increase the wave<br />
   length parameter of the second wave.<br />
4. You should now see the plot of two waves on the green<br />
   screen, to see the sum, click the "Sum All Channels"<br />
   button, on the main window<br />
5. To see *just* the sum, go back toe the Function<br />
   Generators window and click the "visible" button on<br />
   both the waves to hide them<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/02/wave-analyzer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Modeling with Euler&#8217;s Method</title>
		<link>http://visualcore.com/index.php/2008/01/modeling-with-eulers-method/</link>
		<comments>http://visualcore.com/index.php/2008/01/modeling-with-eulers-method/#comments</comments>
		<pubDate>Mon, 21 Jan 2008 06:57:24 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Math]]></category>
		<category><![CDATA[Modeling]]></category>
		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=111</guid>
		<description><![CDATA[Recently, I have been learning how to create mathematical models in code so I figured I would share a little. Models are used to show how some phenomenon in life behaves and are typically based on an equation that represents the thing to be modeled. So the trick is to find a way to solve [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I have been learning how to create mathematical models in code so I figured I would share a little. Models are used to show how some phenomenon in life behaves and are typically based on an equation that represents the thing to be modeled. So the trick is to find a way to solve those equations in code. </p>
<p>Euler&#8217;s method (pronounced Oiler) is one way of doing this, and I will show a very simple example using the following differential equation:<br />
<code><br />
dy/dx = 2x<br />
</code><br />
When solved by integration, the actual solution is:<br />
<code><br />
y = x ^ 2<br />
</code><br />
So that is the value that we want to obtain from the program after it completes. The Euler method requires initial known values for a starting point and then determines the slope of the tangent line at that point in order to find the next *approximate* point on the curve. The initial x, y values can be arbitrary (x=1 and y=1 are used in the example), but it must be a solution to the system &#8211; using x=1, y=8 would be bad since x^2=8 is false.</p>
<p>Since this is an approximation, the the final result will always be off by some margin of error (for example, for xMax=2, y should equal 4, since 2 ^ 2 = 4, but when you run this code, you will see that it is off by a small amount). This error is a function of the step size, dx. Smaller step sizes are generally more accurate. In the example below, a step size of 0.01 is used, which results in an error of 0.25% and a step size of 0.005 results in an error of 0.103%.</p>
<p>In the code below, xMax is the ending x-value that will be approximated, dx is the step size, and x &#038; y are the initial known values. The code was written to be run as a console application in VB.NET 2005.</p>
<p><code><br />
Sub Main()<br />
    Dim x As Double = 1<br />
    Dim y As Double = 1<br />
    Dim xMax As Double = 2<br />
    Dim dx As Double = 0.01</p>
<p>    Console.WriteLine("X , Y -- % Error")<br />
    Do While x < xMax<br />
        Euler(x, y, dx)<br />
        Console.WriteLine( _<br />
            "{0:f2} , {1:f2} -- Error: {2:f3}%", _<br />
            x, y, (1 - (y / x ^ 2)) * 100)<br />
    Loop</p>
<p>    Console.Read()<br />
End Sub</p>
<p>Sub Euler(ByRef x As Double, _<br />
            ByRef y As Double, _<br />
            ByVal dx As Double)<br />
    Dim slope As Double = 2 * x<br />
    Dim change As Double = slope * dx<br />
    y += change<br />
    x += dx<br />
End Sub<br />
</code></p>
<p>Here is a sample run:<br />
<code><br />
X , Y -- % Error<br />
...<br />
1.91 , 3.64 -- Error: 0.249%<br />
1.92 , 3.68 -- Error: 0.250%<br />
1.93 , 3.72 -- Error: 0.250%<br />
1.94 , 3.75 -- Error: 0.250%<br />
1.95 , 3.79 -- Error: 0.250%<br />
1.96 , 3.83 -- Error: 0.250%<br />
1.97 , 3.87 -- Error: 0.250%<br />
1.98 , 3.91 -- Error: 0.250%<br />
1.99 , 3.95 -- Error: 0.250%<br />
2.00 , 3.99 -- Error: 0.250%<br />
</code><br />
As you can see from the sample run, the output claims that:<br />
<code><br />
 x ^ 2 = y<br />
 2 ^ 2 = 3.99<br />
</code><br />
illustrating the approximation error. However, models are not supposed to be exact, they are supposed to be a representation that exhibits behavior similar to the thing your are trying to analyze. Also, there are much better approximation methods (such as Runge-Kutta). You wouldn't want to really use this method to solve the equation in this example, this was just to establish how the concept works. As the complexity of the model grows, this method becomes much more attractive.</p>
<p>This basic framework can be used to model all sorts of neat stuff. Coming up, I will post an example model for a cooling liquid using this method in conjunction with Newton's law of cooling, and then gravity and falling objects.</p>
<p>You can read more about Euler's method <a href="http://en.wikipedia.org/wiki/Euler_integration">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/01/modeling-with-eulers-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding the Nearest Known Color</title>
		<link>http://visualcore.com/index.php/2008/01/finding-the-nearest-known-color/</link>
		<comments>http://visualcore.com/index.php/2008/01/finding-the-nearest-known-color/#comments</comments>
		<pubDate>Mon, 21 Jan 2008 05:49:38 +0000</pubDate>
		<dc:creator>Jeremy Cowles</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[VB.NET]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://visualcore.com/wp/?p=113</guid>
		<description><![CDATA[I recently ran across an interesting question in a usenet post; How do you convert an arbitrary color to a known / system color?
After some thought, I reasoned: in order to find the nearest known color, you must get the difference for each known color based on your sampled color. You could do this by [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ran across an interesting question in a usenet post; How do you convert an arbitrary color to a known / system color?</p>
<p>After some thought, I reasoned: in order to find the nearest known color, you must get the difference for each known color based on your sampled color. You could do this by looping through each known color in the enumeration Drawing.KnownColor. </p>
<p>Next, you could compare the R, G, and B values (or H, S, V values if that is more appropriate) for the known to the sample. To get the distance, you could either do a simple sum of the absolute differences, or if you are a Man or Woman of science, you would use the <A href="http://en.wikipedia.org/wiki/Root_mean_square">RMS</A> (Root Mean Square) value. Finally, you keep the value with the smallest difference and return it.</p>
<p>In my sample code below, I also created a structure for returning the Name, Color and the Distance &#8211; this is just a little sugar to help the medicine go down, not really necessary.<br />
<code><br />
Private R As New Random</p>
<p>Private Sub Button1_Click(ByVal sender As System.Object, _<br />
              ByVal e As System.EventArgs) _<br />
                      Handles Button1.Click</p>
<p>    Dim randColor As Color = _<br />
                      Color.FromArgb(R.Next(0, 255), _<br />
                                     R.Next(0, 255), _<br />
                                     R.Next(0, 255))</p>
<p>    Me.RandomColorBox.BackColor = randColor<br />
    Me.RandomColorLabel.Text = randColor.ToString</p>
<p>    '// now match to nearest known color<br />
    Dim nearest As ColorName = FindNearestKnown(randColor)<br />
    Me.KnownColorLabel.Text = nearest.Name<br />
    Me.NearestColorBox.BackColor = nearest.Color</p>
<p>End Sub</p>
<p>Structure ColorName<br />
    Public Color As Color<br />
    Public Name As String<br />
    Public Distance As Integer<br />
End Structure</p>
<p>Public Function FindNearestKnown(ByVal c As Color) _<br />
                                        As ColorName<br />
    Dim best As ColorName</p>
<p>    best.Name = Nothing</p>
<p>    For Each colorName As String In _<br />
                    [Enum].GetNames(GetType(KnownColor))<br />
        Dim known As Color = Color.FromName(colorName)<br />
        Dim dist As Integer</p>
<p>        dist = Math.Abs(CInt(c.R) - known.R) _<br />
                + Math.Abs(CInt(c.G) - known.G) _<br />
                + Math.Abs(CInt(c.B) - known.B)</p>
<p>        If best.Name Is Nothing _<br />
                 OrElse dist < best.Distance Then<br />
            best.Color = known<br />
            best.Name = colorName<br />
            best.Distance = dist<br />
        End If<br />
    Next</p>
<p>    Return best<br />
End Function<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://visualcore.com/index.php/2008/01/finding-the-nearest-known-color/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

