C++ Index
Delphi Index
Translating C++ code
for a grey scale histogram into Delphi
The source code for this project can be downloaded as a text file here -> histogram.txt...Included at the bottom of the unit is the C++ source code for the histogram routine...

To generate an intensity histogram of a bitmap (this project uses an 8 bit grey scale bitmap) it is neccesary to loop through each byte of the bitmap and count the number of pixels at each intensity level. For example, an 8 bit grey scale bitmap has 256 different possible intensity levels (from 0, which is black, to 255 which is white, with shades of grey in between). To count the pixels of each intensity an array of bytes (0..255] is used. Let's suppose that the 1st pixel byte value is 126. We increment the array position number 126 by one, and we continue to do this every time we find a byte with the value 126 in the bitmap. In one example I tried, the highest value in the array was 7246, which means that in the bitmap there were 7246 pixels which had that intensity level.
When the button is pushed on the form, the project uses an OpenPictureDialog to select the grey scale bitmap. No error checking is incorporated in the code to make sure that the bitmap is in fact 8 bits and grey scale, and while the code will output results if the bitmap is incorrect, the results will be meaningless. Next both the bitmap and the HistCount array are passed to the histogram summing function which simply loops through the bitmap and counts the number of bytes at each intensity level by incrementing the array position corresponding to that intensity level as described above. Next, in order to display the Histogram as a bitmap the array is passed to a procedure named Histogram100. This routine expresses each total in the area as a percentage of the maximum value found so that when the Histogram graph is drawn each point lies between 0 and 100 on the bitmap. For example if 5000 was the maximum count for a certain intensity value, and another point had the count 2500, since 2500 is 50 percent of 5000 the histogram would plot the point 50 on the bitmap for the value 2500 in the histogram array. Note that the array is passed by reference (using the var keyword) so the actual values in the array are overwritten by the percentage value calculated before being passed to the graphing routine. The graphing routine uses standard pen plotting and line drawing functions of the Canvas to plot lines between each point on the Histogram based on the values in the array.
The C++ code from which the Delphi Histogram function was translated is below...For Delphi programmers unfamiliar with C++ this will look very enigmatic (everything is discussed on the C++ pages linked to on the index page below).
void Histogram(struct Image *IMAGE, int HISTCOUNT[])
{
int x, y, i, j;
for (i=0;i<=255;i++) HISTCOUNT[i] = 0;
for (y=0; y<IMAGE->Rows; y++)
{
for (x=0; x<IMAGE->Cols; x++)
{
j = *(IMAGE->Data+x+(long)y*IMAGE->Cols);
HISTCOUNT[j] = HISTCOUNT[j]+1;
}
}
}
The first line of code (the function header) refers to a structure (struct) which is an image and then declares a pointer to such an image structure, followed by the actual Histogram array being passed as a parameter to the function. This image declaration might be replaced in a Windows enviroment by HBITMAP, another kind of structure pointing to an image, in this case a standard bitmap. In Delphi a bitmap is simply declared as Bitmap : TBitmap which replaces the struct declaration in the C++ header.
Next the variables are declared as type 'integer' ('int' in C++) and you will notice that the declaration is backwards compared to what you are used to in Delphi. Next follows a for loop couting from 0 to 255 which simply zeros out each element in the Histogram array to prepare the array to do the count of the bytes in the bitmap. (See the page on C++ loops on the C++ index page).
This is followed by another loop where we actually being to loop through the bytes in the bitmap. Now in memory a bitmap is actually like a long string of bytes, but it is displayed as a two dimensional matrix. The height lies along the y axis and the width along the x axis. To loop through each byte in the bitmap we begin with a y loop from 0 to the height of the bitmap, and then on each hozizontal row, we do an x loop to extract each individual byte on that line. The actual address of the byte can be calculated as a linear value (the way it actually is in memory, by multiplying y (the height, which is indexed from zero) by the width of each row and then adding the value of x (also indexed by zero).
For example suppose that below we have the bytes in the bitmap. The base address of the bitmap is 1000. The offset is added onto this base address to get the address of each byte, and in the two dimensional matrix below these linear addresses are displayed as a matrix...
0 1 2 3
4 5 6 7
8 9
We want to find the actual address of byte 9. The base address is 1000. The length of the rows is 4. In the above example the first row is y = 0. For the byte numbered zero x (the horizontal position) has the value zero. (Remember that the indexes are zero based. To find the actual address of the byte numbered 9 we take 1000, the base address, and add on (y * 4) + x, which in this example gives us (2 * 4) + 1 which is equal to 9, so then the actual linear address of byte 9 is 1000 + 9 or 1009. (Byte 0 is equivalent to the base address 1000).
The Image structure in this C++ code has a field called 'rows' and so to loop through the rows in the bitmap from top to bottom the y loop begins at zero and counts up to Rows, incrementing y by 1 each time through the loop. At each line the x loop will then go one by one horizontally accross the line (and both x and y will be combined as described above to extract the actual linear address of each byte). The for loop appears as ' for (y=0; y<IMAGE->Rows; y++) '. IMAGE is a pointer to the bitmap data and the operator ' -> ' is the dereference operator and extracts the value for rows from within the image structure. (See the page on C++ pointers).
What follows is probably the most enigmatic line of code for Delphi programmers unfamiliar with C++. ' j = *(IMAGE->Data+x+(long)y*IMAGE->Cols); '. What we want to find out is what the value of the byte is at such and such an address (using y and x to determine the actual linear address). When we find out the byte contained at that address then, in the next line of code, we want to increment the value at that array position by one. J will hold the value of this byte and is used in the next line of code to index the array. Image->Data refers to the zero element of the bitmap (the first byte). We add x to this value and then we add y * Column width and we have the actual address of the byte. The keyword (long) is found wrapped in parentheses before the variable y and this means cast 'y' to a long. (Whenever you see a variable type in brackets before an instance of a variable it is a cast declaration. Assume b is a byte and we see (int)b - this means cast the byte b as an integer for the purposes of whatever calculation is taking place.) However what we have is an address, not the actual byte, a pointer to the byte in effect. So you see the whole equation is wrapped in parentheses and is preceded by an asterik which means 'dereference this pointer'. (See the page on pointers...) Therefore once the address is found the byte value it contains (points to) is stored in the variable j which is then used to index and increment the value contained in the array. To use the example matrix above, assume that byte 9 contained the value 126. The actual address of the byte would be calculated as 1009 and then this pointer would be dereferenced and the value it contains (126) would be assigned to j. Then position 126 in the array would be incremented by one, and the loops would continue.
This highlights one difference between C++ and Pascal. In the code example above an integer (type 'long' ) was the result of a mathematical calculation and then this integer was treated as a pointer and dereferenced to place a value in j. This is possible because C is loosely typed, not strongly like typed as Delphi is. You cannot dereference and integer directly in Delphi, nor can you assign an integer to a pointer (using a cast as in the C++ example above). However you can mimic this by using the function PTR which accepts an integer as an argument and returns a pointer. So assuming you have a pointer to a byte (we will call it 'pb') you could pass the results of the calculation above to the PTR function and it would pass the integer which resulted to the pointer without generating one of those 'type mismatch' compiler errors. You could continue to do manipulations of the integer, passing the result back to the pointer (as a substitute, for example, for using a 'pbytearray' to access a bitmap, as in the code sample below). So then what we would have would be pb := ptr(integer); where pb is a pointer and integer is either an integer or the result of some function returning an integer, which produces results similar to what you see happening in the C++ code above. Delphi would then require an additional step, that of dereferencing the pointer ( j := pb^; ) which would be dereferencing whatever address the integer represented and passing its contents to j. Using 'PTR' instead of pbytearray would allow a more direct translation of the C++ code segment, with the disadvantage in Delphi being that you would need two variables, one the integer which will be manipulated and one the pointer which will be dereferenced, since Delphi is strongly typed. The PTR function seems to be a way of doing an end run around the strict type checking of the compiler since all the function is going to do is go behind the compiler's back and place the integer value into the pointer location. You can also mimic C++ variable casting (casting a byte as an integer, for example) by using the 'Variant' variable, which does the same thing. Variants are not native to Pascal, but were introduced to mimic the loose type casting of languages like C++. A real Pascal purist would hate variants, since they violate the principle of strong type casting and checking done by the compiler, but even a purist couldn't find fault with the PTR function, since something like this is required, since the type casting in Delphi makes pointer use less flexible than in C++. However the disadvantage of a loose language like C++ is that you will really need to keep up on all those security patches, in particular due to those buffer over runs, not to mention all those bug patches. A strongly typed language is inherently more secure, and while fans of C++ constantly point out as its principle benefit that it is so loosely typed, and thus more flexible, this also makes the language less secure, and while one could argue that code can be as secure as a programmer wants to make it, people just aren't that good at considering every single possibility, as all those patches on C++ code testify, and making it secure makes great demands on programmers. You can also add onto this the fact that C++ is based on obsolete forty year old technology (although Pascal is just about as old) and consider the fact that Pascal was written as a response to the often unintelligible syntax of C, and there are other advantages to Delphi as well (a C++ programmer could probably read and decipher a program written in Delphi while a Delphi programmer would find a first encounter with C++ to be enigmatic and obscure, because C++ is enigmatic and obscure. Modern languages are not like this.) But I digress...
Now that we know what this C++ code does, we can translate it into Delphi, and the result is shown below...
procedure TForm1.Histogram(var Bitmap : TBitmap;
var Histcount : array of integer);
var
x, y, i, j : integer;
pb : pbytearray;
begin
For i := 0 to 255 do begin
HistCount[i] := 0;
end;
for y := 0 to Bitmap.height - 1 do begin
pb := Bitmap.scanline[y]; {get the base address for this row}
for x := 0 to Bitmap.width - 1 do begin {scan byte by byte horizontally}
j := pb[x];
{next Increment the pixel count in the histogram for this
pixel intensity, using j, the byte value as the index into
the array}
inc(HistCount[j]);
end;
end;
end;
In the above example an extra variable is declared in the Delphi version, a pointer to a byte array (pb : pbytearray}. On each turn through the y loop (the beginning of each new line in the virtual matrix) pb is set equal to the base address for that line. X is then indexed from zero and used to access the bytes accross that line one at a time (by adding x to the base address represented by 'pb' the pointer to the byte array). It is possible to access the bitmap using a pointer as well, as in the C++ code, and then dereferencing the pointer to get the byte value, but in this example I have stuck with the typical 'pbytearray' since it is what most people are familiar with...
C++ to Delphi Index
Delphi Index
A Unified Field Theory
The Unified Field Theory
is also available as a zip file -> unified.zip
Introduction :The Pioneer Effect and the New Physics. A brief description of the new physics required to explain the 'Pioneer Effect', which is the constant deceleration of space craft as they fly through space.

Principles of Evolution: A Study in the Evolution of Bedbugs
A couple of years ago my bedroom was invaded by bedbugs. There were two variant genetic lines. One type of bedbug was an enlongated, thin, tubular insect, and the second genetic line was a flat, perfectly circular insect. The result of the cross breeding of these two genetically distinct variants was the production of a bedbug with charcteristics of both, an enlongated, flat bedbug with a central bulge (such that the shape of the bedbug was somewhere between 'long' and 'circular'). The long skinny bedbugs were such strange and unfamiliar looking insects that at first I did not recognize them as being bedbugs, and considered them to be a seperate species of insect. However, as the photographs of bedbugs above indicate, enlongated and skinny bedbugs are not uncommon, and the photographs also show the variants that are produced by genetic combinations that result in an insect somewhere in between 'circular' and 'enlongated'.
Therefore it is my hypothesis that evolution occurs by means of the transfer of dominate genes, with the production of such dominant genes being the product of 'biological algorithms', a genetic software program that brings physical characteristics into harmony with behavior, such that when behavior changes, and a conflict then exists, this acts as a trigger and causes the release of dominant genes. The result is rapid evolution of species. The bedbug is a relatively new insect, not the product of millions of years of evolution but rather an insect that is evolving in real time. The newly emerging dominant form of the insect is the flat, round ciruclar insect, well adapted to living in human bedrooms (it is flat, rather than tubular, thus allowing it to hide in the smallest cracks, living a stealthy lifestyle, and it is round, which gives the insect a maximum storage capacity such that it must endanger itself only a few times a month by emerging to feed.
Other examples of rapid evolution include the development of long legs in an invasive species of toad in Australia. As the toads move into the mountainous regions of Australia, and their behvaior changes, making them 'climbing toads', over the course of just a couple of decades the toads in the highlands have grown long legs specially adapted to climbing. It is worth noting here that the toads are poisonous, and are a successful invasive species because they have no natural predators in Australia, and so it would not be the case that the toads with long legs were 'the fittest survivors', because all the toads are survivors, and therefore predation does not explain the rapid emergence and spread of such well adapted, long legged toads. Once again we see evidence for the existence of biological algorithms and the rapid spread of dominant genes through a population, which once introduced proceed to overwhelm the older genes which are being replaced (making toad long legged and a bed bug round and flat).
A Theological Experiment
My interest in pursuing the Unified Field Theory is spurred on by my
need to discover the theoretical explanation of a new form of
propulsion (as explained on this page: Why the
Unified Field Theory?). The experiment involving the bedbugs came
out of nowhere.
I also believe that it is possible to justify theological propositions
using experimental methods. If a thing is an objective truth then it
can be verified and proven true by means of experimentation. Such a
theological proposition is of more value than a ‘divine revelation’,
since such revelations depend upon nothing more than establishing
authority figures which requires the creation of artificial
hierarchies, for the only reason why I might be encouraged to believe
an authority figure who orders me to believe unsubstantiated opinions
is if I could somehow be convinced that this authority possessed a mind
that was somehow superior to mine, and thus was fit to express opinions
as though opinions were unquestionable facts and thus worthy of being
elevated to the status of absolute dogma.
There is a self evident human inequality which is visibly apparent.
Some people are ‘beautiful’ and thus are the true elite on this planet,
and some people are not. It is this sexual inequality and the
degeneration that follows upon beauty that is the true driving force
behind all the evil that happens on earth. The need for ruthless
oppression and the pursuit of wealth and the consequent creation of
suffering and poverty which must follow upon this practice is for the
purpose of creating an artificial alpha elite.
The true elites are the young and the beautiful. The artificial elite
are the rich and the wealthy. The elite aging rich artificial alpha
male has no good looks, for he is physically degenerate, but he will be
found escorting beauty because he has a beautiful wallet. If he loses
his wallet he will be found at home with all the other unattractive
aged beta males sitting in a rocking chair watching reruns of Bonanza.
No money, no sex. It is for this reason that the alpha males are found
to be so ruthless and so violent in pursuit of their goal. The alpha
male has fallen. The beta male has arisen and now the whole planet is
full of ruinous destruction for it.
We see in religion a confused and contradictory reaction to this
reality. On the one hand religion preaches a sexless heaven where
castration and the clitorectomy create ‘pure spirits’. Muslims throw
women under sacks. On the other hand religion supports hierarchy and
is the prop of the elite alpha male. It is for this reason that
religion is incoherent when it comes to speaking about sex.
Now we see this same principle at work in all of nature. Guppies dance
and show off their colorful tails and the guppy who dances with the
most colorful tail is the sexually successful guppy. Therefore it is
the doctrine of the ruthless oppressor which teaches that the solution
to human sexual violence is to be found in castration and the creation
of pure ghosts. This would be equivalent to damning an aardvark for
having the ‘sinful aardvark nature’ or prosecuting an anteater for the
high crime of ‘ant genocide’.
Therefore it was my theological hypothesis that the correct solution to
this problem is to give every guppy a beautiful colorful tail. I
compare this solution to the classic religious solution which is to cut
off every tail since having a tail is ‘sinful’. If having a tail is
sinful then God must be sinful for no human being has any choice in
deciding whether or not they would be born with a colorful tail, or
whether they would not.
When I was young I was a beautiful guppy with a lovely tail. So
everyone seemed to think. I am older now. My nose became very badly
sunburned and destroyed. It seemed good to me to test my hypothesis by
using these ‘biological algorithms’ to correct this problem. I healed
half my nose as you can see by the line separating the still very dark
patch on the side in the photograph below.

I documented my experiment on these pages. one
two
t
hree
four
fi
ve
six
I have confirmed to my own satisfaction that my theological proposition
is correct and that religious dogma is erroneous, being based as it was
upon nothing more than ‘divine revelation’ which is just a form of
opinionated speculation. For the time being I am not continuing this
experiment, for I must wait until the weather on this planet improves,
and the dark clouds of ruthless oppression break letting a little sun
shine come through so that I can show the world the truth about God, by
showing people how God goes about giving an old guppy back his
beautiful colorful tail.
Until then I will have to sit on the sidelines, while all my scientific
breakthroughs are deliberately ignored, while I wonder to myself what
ever in the world could be wrong with the human race, because what this
all will prove at the end of it all is that there definitely was
something wrong with the people on this planet.