Posts

IEEE has C as top Programming Language in 2016

The IEEE reports here that C is the number 1 programming language in 2016. As usual, I am slightly dubious about a lot of these rankings, each one seems to yield a different order. Still you would hope that the IEEE would employ a little more rigour than most! Funny thing is I just don’t see many of these C programmers about… Mind you I know one C programmer who personally outputs about 10 times the amount of code as most…

Friday – Programming in pure unadulterated C Today

Today I have the pleasure in programming in pure & unadulterated C, there is something really refreshing about the clean and minimal elegance of the language and its associated design principles, especially considering the weight of baggage the software engineering discipline has gathered of late – not bad for a rainy Friday!

2*c || !(2*c)

A Machine Vision Engineer’s take on Fifty Shades of Grey by James Mahon

A Machine Vision Engineer’s take on Fifty Shades of Grey by James Mahon (generated by pure C source code):

50_shades_of_grey_machine_vision

And the source code:

//
//
// 50Shades.cpp : Something for the weekend - JM
//  I am sure that you could to this in abaout 6 lines of Python, but here it is in olde C
//

#include 
#include 
#include 

#define IMAGE unsigned char

void draw_grey_box ( IMAGE *vram, int x_size, int ix, int iy, int dx, int dy, IMAGE grey )
{
	unsigned char *ptr;
	int   y;
	for ( y = iy; y < iy+dy; ++y ) {
		ptr = vram + ix + y * x_size;
		memset ( ptr, grey, dx );
	}
}


int save_any_pgm_image2 ( IMAGE *ram, char *file, char *com, int x1, int y_1, int x2, int y2, int X_SIZE )
{
	int    dx, y;
	IMAGE  *ptr;
	FILE   *fd;
	dx = x2-x1;

	if ( (fd = fopen ( file, "wb" )) == NULL ) {  /*  1.29  */
		printf   ( "save_any_image File <%s> open failed to write\n", file );
		perror   ( "pgm write" );
		return -1;
	}
	fprintf ( fd, "P5 #%s\n%d\n%d\n255\n", com, dx, y2-y_1 );

	for ( y = y_1; y < y2; y++ ) {             /*  Write it all out from gram */
		ptr = ram + x1 + y * X_SIZE;
		if ( fwrite ( ptr, dx, sizeof( IMAGE ), fd ) != sizeof( IMAGE ) ) {
			fclose  ( fd );
			return -2;
		}
	}
	fclose ( fd );

	return y;
}


int main(int argc, char* argv[])
{
	int x_size = 1024, y_size = 768, i, x, y, dx, dy, nx = 10, ny = 5, ix, iy, grey = 1;

	printf ( "Image fILE in c:\\temp\n" );
	IMAGE *vram;
	dx = x_size / ( nx+1 );
	dy = y_size / ( ny+1 );

	vram = (unsigned char *)malloc ( x_size * y_size );
	memset ( vram, 0, x_size * y_size );

	for ( y = 0; y < ny; ++y ) {
		for ( x = 0; x < nx; ++x ) {

			ix = x * dx + dx / 2;
			iy = y * dy + dy / 2;
			draw_grey_box ( vram, x_size, ix, iy, dx*9/10, dy*9/10, grey*5+3 );
			++grey;
		}
	}
	save_any_pgm_image2 ( vram, "c:\\Temp\\50_shades.pgm", "for Valentines day", 0, 0, x_size, y_size, x_size );

	return 0;
}

Save 8 bit uncompressed windows bitmap file (.BMP) in c# / .Net

It took me about 3 years to figure this out. In .Net when you save an 8 bit bitmap from software (PixelFormat.Format8bppIndexed) via Save() it is saved by default in a compressed format (as is allowed by the .bmp pseudo-standard).

Now some Machine Vision libraries can’t load compressed 8 bit bitmaps (poor old Cognex, bless) so I had to figure out how to get .Net to save the .bmp file in an uncompressed format.

The following code save the bitmap as 8bit compressed (if the bitmap’s format is PixelFormat.Format8bppIndexed)

 bitmap.Save("it.bmp");

Now Microsoft has not documented this whole area very well, but it is quite easy, you have to manually specify an image encoder and set its ‘Compression’ parameters as in the following code:

  // Make sure that the blighter will be saved
  // uncompressed.
  var enc = GetEncoderInfo("image/bmp");
            
  var parms = new EncoderParameters(1);
         
  var parm = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone);
  parms.Param[0] = parm;

  // Save the bitmap.
  bitmap.Save("it.bmp", enc, parms);

Where GetEncoderInfo() is defined as:

private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
    int j;
    ImageCodecInfo[] encoders;
    encoders = ImageCodecInfo.GetImageEncoders();
    for (j = 0; j < encoders.Length; ++j)
    {
        if (encoders[j].MimeType == mimeType)
            return encoders[j];
    }
    return null;
}

Here we set the Encoder.Compression parameter to EncoderValue.CompressionNone and this should ensure that the bitmap is saved uncompressed.

See this post for details of how to save an 8 bit greyscale image to disk from a byte array.

Reference:

http://msdn.microsoft.com/en-us/library/ytz20d80(v=vs.110).aspx

C++ thread safe blocking queue using boost

In Software Engineering some patterns reoccur only every few years. The blocking queue pattern is on such for me. Here is a great article on an implementation of a thread-safe blocking queue that uses boost for synchronisation:

http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

I implemented something like this some years ago (without the benefit of boost etc.) and now I need one again and I want to make it bang-up-to-date wrt. C++11 and boost etc., so this article is a real bonus, much thanks to Anthony Williams!

Strange behaviour of std::thread in Visual Studio 2012

Today I came across some strange behaviour with the VS2012 implementation of std::thread. The created thread’s job was to access the XIMEA camera API, one method of thread creation worked ok, and another only half worked.

With the first mode the API could grab from multiple cameras as expected, while with the other it could only grab from one camera – grabbing from the second camera would always fail. To make things stranger the mode that worked required the passing of an un-used argument to the thread function!

Here is the mode that didn’t work:

int t_func() {
	return do_stuff();
}

void start_thread() {
	std::thread t(t_func);
	t.detach();
}

And here is the mode that does work OK, notice the dummy argument that is passed but otherwise unused!

int t_func(void*) {
	return do_stuff();
}

void start_thread() {
	std::thread t(t_func, (void*)NULL);
	t.detach();
}

All very strange!

Boost link error – undefined reference to boost filesystem detail copy_file( )

I had some difficulty today getting my code to link to boost::filesystem::copy_file() (linking to boost version 1.53.0, gcc v4.7.2), I suffered from link errors like this:

undefined reference to `boost::filesystem::detail::copy_file(boost::filesystem::path const&, boost::filesystem::path const&, boost::filesystem::copy_option, boost::system::error_code*)’

From reading this post, it seemed that my problem may have stemmed from my use of c++0x.

 

None of the suggested solutions in this thread worked for me & I double checked that had built boost with -std=c++0x.

 

In the end after looking through the code in filesystem/operations.hpp the only thing that fixed my linking problem was to #define BOOST_NO_CXX11_SCOPED_ENUMS before including , like this:

#define BOOST_NO_CXX11_SCOPED_ENUMS

#include 

This may well not be the best/proper way to fix the problem but it was the only thing that worked for me..

 

Other relevant links that I found are here, here and here.

 

Enterprise Architect UML – Add C++ #include code statements for dependency relationship

By default #include statements are not inserted into files for dependency relationships when generating C++ code from UML models in Sparx Enterprise Architect – this is a bit annoying but we are well used to UML editors doing annoying things so at least it’s not a terrible surprise!

 

In Enterprise Architect’s defence it is quite easy to add this missing functionality. In order to get it to generate #include statements we have to edit two of the code generation templates: “Import” and “Import Section”.

 

To edit the templates go to the “Settings / Code Generation Templates…”, menu and you should see a list of the templates on the left-hand side of the screen.

 

Change the “Import” template so that it looks like this:

$file = %importFileName%
%if $file == "" or importInFile=="T" or $file == fileName%
%endTemplate%

#include "$file"

And then change the “Import Section” template so that it looks like this:

$COMMENT="WARNING: THIS IS AN ADVANCED TEMPLATE"
$COMMENT="DO NOT MODIFY UNLESS YOU ARE AN"
$COMMENT="ADVANCED USER!"

$imports += %list="Import" @separator="\n" importFromDependency=="T"%
%REMOVE_DUPLICATES($imports, "\n")%


%fileImports%

Now when you generate C++ code from your modle #include statements should be inserted to satisify dependency relationships.

 

Thanks to this article for the instructions (in German!).

 

Light Weight Logger in C++

I came across this interesting article in Dr. Dobbs that details the implementation of a light weight logging framework in C++ that uses policy classes:

http://www.drdobbs.com/cpp/a-lightweight-logger-for-c/240147505?pgno=1

I reckon that it could be of special of interest for use with embedded systems.

C# Create a Cognex 8bit image (CogImage8Grey) from an 8bit Grayscale image array (byte[])

Here is some code that shows how to create an 8bit grayscale cognex image (CogImage8Grey) from an 8bit raw image stored as a byte array (byte[]). This type of memory messing is difficult in .NET at the best of times and it’s just a pity the the cognex library doesn’t help much more than it does.

 

I also have a feeling that the cognex library is doing more copying than it strictly needs to, but in true style its software documentation does not detail if, or when, it copies image data (or much else for that matter!) So I copy the image data from the byte array into a malloc’ed buffer before creating the cognex image.

 

First we have to define a SafeBuffer through which cognex can free up the allocated memory when it is finished with it, to do this we can derive a class from SafeBuffer like this:
[crayon lang=”csharp”]
///

/// A wrapper around malloc so that FreeHGlobal() is called
/// when the object is disposed.
///

class SafeMalloc : SafeBuffer
{
///

/// Allocates memory and initialises the SaveBuffer
///

///The number of bytes to allocate public SafeMalloc(int size) : base(true)
{
this.SetHandle(Marshal.AllocHGlobal(size));
this.Initialize((ulong)size);
}

///

/// Called when the object is disposed, ferr the
/// memory via FreeHGlobal().
///

///
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(this.handle);
return true;
}

///

/// Cast to IntPtr
///

public static implicit operator IntPtr(SafeMalloc h)
{
return h.handle;
}
}
[/crayon]

 

Its constructor mallocs the memory and when it is disposed ReleaseHandle() is called, and this frees the memory. I also added a cast to IntPtr so that we can pass it into functions that expect an IntPtr.

 

Now that we have SafeMalloc we can write function to create the cognex image like this:
[crayon lang=”csharp”]
class CognexStuff
{
public ICogImage Convert8BitRawImageToCognexImage(
byte[] imageData, int width, int height)
{
// no padding etc. so size calculation
// is simple.
var rawSize = width * height;

var buf = new SafeMalloc(rawSize);

// Copy from the byte array into the
// previously allocated. memory
Marshal.Copy(imageData, 0, buf, rawSize);

// Create Cognex Root thing.
var cogRoot = new CogImage8Root();

// Initialise the image root, the stride is the
// same as the widthas the input image is byte alligned and
// has no padding etc.
cogRoot.Initialize(width, height, buf, width, buf);

// Create cognex 8 bit image.
var cogImage = new CogImage8Grey();

// And set the image roor
cogImage.SetRoot(cogRoot);

return cogImage;
}
}
[/crayon]

 

This function allocates memory via SafeMalloc, it then copies the raw image data from the input array into this memory. Then CogImage8Root.Initialize() is called passing in a pointer to this memory. not that in this case the image’s stride is the same as its width. Once the CogImage8Root has been initialised we can create a CogImage8Grey image and set the root via a call to SetRoot()!

 

They certainly make you work for it!!

 

If you know that nobody else will be using your image array and are willing to go ‘unsafe'(!) then you could avoid this extra memory copy by pinning the array and getting a pointer to it, you could then pass this pointer directly to the root Initialize() function. In this case you won’t need the SafeMalloc class etc.

 

Thanks to all on this thread for hints on SafeBuffer!