Xojo: Sketching with Real-time Contrast Preserving Decolorization and Potrace


Always looking for some ways to learn the computer to ‘see’, I came accross two very interesting algorithms: ‘Real-time Contrast Preserving Decolorization’ by Cewu Lu, Li Xu and Jiaya Jia. And Potrace by Peter Selinger

Decolorization – the process to transform a color image to a grayscale one – is a basic tool in digital printing, stylized black-and-white photography, and in many single channel image processing applications. RTCPD is aiming at maximally preserving the original color contrast alleviate a strict order constraint for color mapping based on human vision system.

An example can be seen here:

The second algorithm Potrace(TM) is a tool for tracing a bitmap, which means, transforming a bitmap into a smooth, scalable image.


Playing around with both algorithms, I came up with the idea to use them for a project I had in mind for some time: Sketching pictures on my wall using a Pico projector.

First I had to implement both algorithms in Xojo. The result of RTCPR can be found in the attached source code in the RTCPRGB2Gray() method:

Private Sub RTCPRGB2Gray(pic as Picture)
  dim imcols as Integer = pic.Width
  dim imrows as Integer = pic.Height
  dim sRGB as RGBSurface = pic.RGBSurface
  dim Mat(-1,-1) as ABDoubleVector
  redim Mat(imrows-1,imcols-1)
  dim c as Color
  for y as Integer = 0 to  imrows - 1
    for x as Integer = 0 to imcols - 1
      c = sRGB.Pixel(x,y)
      mat(y,x) = new ABDoubleVector(c.Blue, c.Green, c.Red) ' switch to BRG
  dim s as Double = 64.0 / sqrt(imcols*imrows)
  dim cols as Integer = (s * imcols) + 0.5
  dim rows as Integer = (s * imrows) + 0.5
  dim sigma as Double = 0.05
  dim W() as ABDoubleVector = wei()
  dim P() as ABDoubleVector
  dim det() as Double
  dim pos0() as ABDoublePoint
  dim pos1() as ABDoublePoint
  for i as Integer = 0 to cols - 1
    for j as Integer = 0 to rows - 1
      dim x as Integer = (i+0.5) * imcols/cols
      dim y as Integer = (j+0.5) * imrows/rows
      pos0.Append new ABDoublePoint(x,y)
      pos1.Append new ABDoublePoint(x,y)
  for i as Integer = 0 to pos0.Ubound
    dim c0 as ABDoubleVector = mat(pos0(i).y, pos0(i).x)
    dim c1 as ABDoubleVector = mat(pos1(i).y, pos1(i).x)
    add c0,c1, P, det
  cols = cols / 2
  rows = rows / 2
  for i as Integer = 0 to cols - 2
    for j as integer = 0 to rows - 1
      dim x0 as integer = (i + 0.5) * imcols / cols
      dim x1 as integer = (i + 1.5) * imcols / cols
      dim y as integer = (j + 0.5) * imrows / rows
      dim c0 as ABDoubleVector = mat(y, x0)
      dim c1 as ABDoubleVector = mat(y, x1)
      add(c0, c1, P, det)
  for i as integer = 0 to cols - 1
    for j as Integer = 0 to rows - 2
      dim x as integer = (i + 0.5) * imcols / cols
      dim y0 as integer = (j + 0.5) * imrows / rows
      dim y1 as integer = (j + 1.5) * imrows / rows
      dim c0 as ABDoubleVector = mat(y0, x)
      dim c1 as ABDoubleVector = mat(y1, x)
      add(c0, c1, P, det)
  dim maxES as Double = -99999999999
  dim bw as Integer
  for i as integer = 0 to w.Ubound
    dim es as Double
    for j as integer = 0 to p.Ubound
      dim l as Double = P(j).x * W(i).x + P(j).y * W(i).y + P(j).z * W(i).z
      dim detM as Double = det(j)
      dim a as double = (L + detM) / sigma
      dim b as double = (L - detM) / sigma
      es = es + log(exp(-a * a) + exp(-b * b))
    es = es / (p.Ubound+1)
    if eS > maxEs then
      maxEs = Es
      bw = i
    end if
  dim result(-1,-1) as Double
  redim result(imrows-1,imcols-1)
  for y as Integer = 0 to  imrows - 1
    for x as Integer = 0 to imcols - 1
      result(y,x) = mat(y,x).z*W(bw).x + mat(y,x).y*w(bw).y+0
      result(y,x) = mat(y,x).x*W(bw).z + result(y,x)*1+0
      sRGB.Pixel(x,y) = rgb(result(y,x),result(y,x),result(y,x))
  bw = 0  
End Sub

Potrace is a complete framework to trace an image and converting it to Xojo did take some time. While writing it, I also made some changes to it to optimize the result. One of it was doing my own thresholding using the surrounding pixels to smoothen the edge detection.


  dim v, v1, v2, v3, v4, v5, v6, v7, v8 as Integer
  dim ex,ey, weight, weighttotal, total as Double
  'SISThreshold2 alain
  for y = 1 to H - 2
    for x = 1 to W - 2
      v = sDebugPicRGB.Pixel(x, y).red
      v1 = sDebugPicRGB.Pixel(x+1, y).red
      v2 = sDebugPicRGB.Pixel(x-1, y).red
      v3 = sDebugPicRGB.Pixel(x, y+1).red
      v4 = sDebugPicRGB.Pixel(x, y-1).red
      v5 = sDebugPicRGB.Pixel(x+1, y-1).red
      v6 = sDebugPicRGB.Pixel(x-1, y-1).red
      v7 = sDebugPicRGB.Pixel(x+1, y+1).red
      v8 = sDebugPicRGB.Pixel(x-1, y+1).red
      ex = (v1+v2+v5+v6)/4
      ey = (v3+v4+v7+v8)/4
      if ex > ey then
        weight = ex
        weight = ey
      end if
      weighttotal = weighttotal + weight
      total = total + weight * (v)
  dim  Threshold as Integer = 128
  if weighttotal <> 0 then
    Threshold = total/weighttotal
  end if
  dim ret as Boolean = (sDebugPicRGB.Pixel(0, 0).Red >= Threshold)
  for y = 0 to H
    for x = 0 to W
      c = sDebugPicRGB.Pixel(x, y)
      if c.red >= Threshold then
        Matrix(x+1, y + 1) =true
        Matrix(x+1, y + 1) = false
      end if
  for x = 0 to MatrixW
    Matrix(x,0) = true
    Matrix(x, MatrixH) = true
  for y = 0 to MatrixH
    Matrix(0,y) = true
    Matrix(MatrixW, y) = true

This gave me all the tools to start tracing an image. But for my project I wanted to have a sort of ‘sketchy’ feeling. For this I needed a couple of things because I wanted the drawing and painting to be done gradually. I had to build it with delays, repetition, randomization and color fading. I wanted to start from a picture and create something like this:

DrawImage() does all that. It first draws the beziers with some little random mistakes in grey. A gradual painting is then used to fill in the polygons. Finaly it repeats the process with the correct lines in white.

You may notice that a lot of code is redundant, but this is intended because I needed to have enough delays to mimic a more natural feeling.

Here is a demo video showing the result of this project on my wall. It takes about ten seconds before it starts drawing as I had to grab my camera :-). Five different images are drawn.

The project with full source code can be downloaded here



Xojo: CHIP-8 Emulator

Some weeks ago, Ashot Khachatryan contacted me on the Xojo forum with the question if I would be interested in writing a CHIP-8 Emulator in Xojo. I had no knowledge of the system and he had written a good part of an Emulator himself. It had some hard to find bugs in it and he was kind of stuck. As it is hard to debug someone elses code, especially if the subject is not very well known, I decided to start from scratch. Or, to say it in Barney Stinsons words, Challenge accepted!

CHIP-8 is an interpreted programming language, developed by Joseph Weisbecker. It was initially used on the COSMAC VIP and Telmac 1800 8-bit microcomputers in the mid-1970s. CHIP-8 programs are run on a CHIP-8 virtual machine. It was made to allow video games to be more easily programmed for said computers. Input is done with a hex keyboard that has 16 keys which range from 0 to F. The ‘8’, ‘4’, ‘6’, and ‘2’ keys are typically used for directional input.

There are a number of classic video games ported to CHIP-8, such as Pong, Space Invaders, Tetris, and Pac-Man.

So, the big question was, could we write a CHIP-8 CPU Emulator in Xojo? It needs to be able to read ROMS, interpret Opcodes, show it on the 64×32 pixels screen and handle input. An Opcode is a two bytes code like 00E0 (Clears the screen).

The ‘Virtual Machine’ ABCH8CPU would need to handle a couple of things:
Screen: a picture of 128×64 pixels
Memory: 4096 bytes. I decided a memoryblock would be ideal in Xojo to handle this
Registers: a CHIP-8 has 16 8-bit registers (V0-VF). A Byte array will be used
Timers: a byte array of size 2
Sound: Beep is used
Input: the Keyboard.AsynckeyDown() method would handle the state of the 16 keys.

There are a number of projects on the net in other programming languages available. (Just google CHIP-8 source code). I’ve studied several of them before I’ve wrote my Xojo version.

Here is the result (didn’t spend much time on the GUI):

It can handle CHIP ROMs and SCHIP (Super CHIP) ROMs. Unfortunately, speed is terrible. Xojo may not have been the right language to write this project in, but look at it as a proof of concept. And it can probably be optimized too, as I wrote this emulator in an evening or two.

You can change the keyboard (AZERTY/QUERTY) to emulate the 16-Keys keyboard. A memory dump and a list with the interpreted Opcodes is also shown.

All in all, this was a fun project to do!

The Xojo source code and some ROMs: http://gorgeousapps.com/ABCHIP8.zip

Bye for now!

B4i: 1 … 2 … 3 … Ready … Go!

This weekend I’ve found some time to setup my testing environment for B4i, the latest brainchild of Anywhere Software. I must say, being a novice Mac user, setting everything up went very smooth.

The only parts I got into some trouble was my own fault, as I went though the setup tutorials, videos and Beginners Guide just a little bit to fast. Eager to get started, I skimmed through them and forgot some important steps.

First I paid my obligatory taxes to Apple: $99/year. (Programming for Android only sets you back with a one time fee of $25). Only a couple of minutes later, my account was activated.

One part that may have gone a bit to fast for a first time Apple developer was the creation of an App ID. As Erel had his system already setup when he made the video and could just pick an App ID, he did not show us how to create it in the first place. It is mentioned further in the post you can create a single wildcard App ID if you put a .* at the end, but this was not very clear from the tutorial. So, this is how I did it:

Click to enlarge

Click to enlarge

Another RTFM moment was when I wanted to install the B4i-Bridge app on the device. I started watching the video and forgot to read the bold sentence above it:

Before you install B4i-Bridge you must install the B4I certificate. This step is not shown in the video. Open Safari (device browser) and navigate to: www.b4x.com/ca.pem

Clearly stated, but hey, I was in a hurry…

I first tried the Hosted Builder option to compile the app. Very smooth and a excellent alternative for Windows developers who do not own a Mac. And for $26 a year, a bargain.

But, as I want to experiment with creating libraries myself in Objective-C, I wanted to install the local MacBuildServer. Again, following the tutorial, everything went very well. Downloading XCode took most of the time.

One note: Make sure your Mac is in the same IP range as the rest of your development environment. At first, the Mac had IP while the rest was in the 192.168.1.x range. So it didn’t work.

The rest was pure cosmetic. I added an shortcut on the Mac to start the MacBuildServer, and one on the PC side to shut it down.

Creating the shortcut on the Mac side went like this:

  • Open up a terminal
  • go to the folder where you unzipped the macserver-aa (in my case, it’s on the desktop, so it looked like this:

    $ cd desktop
    $ cd macbuilder-aa

  • create a text file

    $ shout start.command

  • add the following lines (adjust the cd to the path where your MacBuildServer is)

    cd /Users/Alwaysbusy/Desktop/macserver-aa
    java -jar B4iBuildServer.jar

  • save and in the terminal type:

    $ chmod -x start.command

  • Right click on start.command, pic ‘Get Info’ in the menu and rename it to something like ‘B4i Build Server Start.command’.
    Click ‘Hide extension’
  • And change the icon to a nice B4i one. I’ve ripped the B4i icon from the exe (sorry Erel) and saved it as a .png. In case you need it, here it is:
    Open the png on the Mac in preview and copy it (Edit – Copy). In the ‘Info Panel’ of the command file, click on the icon until it gets a blue rectangle. Then you can do ‘Edit – Past’.
    In my case, it looked like this:
  • B4i3

    Coming from Windows and being used to creating .bat files, this is all rather complicated on a Mac I must say.

    On the PC side I created also the icon to shut the MacBuildServer down. Enter http://:51041/kill in your favorite browser. Create a bookmark and drag it to your desktop. Rename it to something like ‘B4i Build Server Kill’. You can also change the icon:

    • Right click on the shortcut and pick ‘Properties’
    • Press ‘change icon’
    • Browse to where you have installed B4i
    • Pick B4i.exe and select the icon

    So (besides my shortcut creation problems on a Mac), setting up B4i is a breeze! I’m ready to add some serious iOS programming experience to my portfolio.

    Here are some quick links to the tutorial parts I used:
    Creating a certificate and provisioning profile
    Installing B4i-Bridge and debugging first app
    Local Mac Builder Installation

    See ya!


    Xojo: Release 2014R3 with iOS support

    Xojo with iOS support
    We are spoiled this Christmas! Xojo has released a new update of their cross-platform development tool, and this time it includes a new one: iOS.

    I think congratulations is in order to the Xojo dev team! The wait has been long and there are a lot of eager programmers wanting to explore the world of mobile development. There are some changes in the framework that will it make somewhat harder for hardcore developers (me included) who have already huge business logic libs. But I’m sure the Xojo community will come up with some tricks to make the transition faster.

    Already some members are trying to set-up some kind of central place to cover some missing controls/functionalities with Declares. I hope they share the source code, so we can all learn from it!

    Here is what the wizards of Xojo have to say:

    Xojo, Inc.:
    Latest release allows users to create high-quality, native iOS applications in the same way they develop desktop and web apps today.

    Xojo users can now build iOS apps in the same way desktop and web applications are created. Users can drag and drop to create the user interface and use one straight-forward programming language to implement the functionality of their app. Xojo makes it significantly faster and easier to create native iOS apps than any other tool. Many iOS business apps rely on a web-based server application that provides business logic and database access. Xojo is the only development tool that provides the ability to create both a native iOS client application and a native server application from a single language and tool. Users experience true multi-platform development with Xojo, creating their app on one platform and delivering a completely native product to users on another platform.

    Geoff Perlman (Xojo Founder and CEO):
    “Xojo 2014 Release 3 represents a huge leap forward for us as we are now have a mobile development platform. Adding iOS to Xojo has been the top feature request from our users and we are pleased to deliver. By expanding their Xojo applications from the desktop and web to iOS, our developers are now able to broaden their target audience to a whole new range of prospects.”

    This latest release adds 160 improvements and over 20 new features. In addition to the new iOS framework, this release also adds improvements to the web framework and includes new classes that make creating international applications easier. Further, web applications can now respond to requests from search engines such as Google, making their content searchable on the web.

    Xojo 2014 Release 3 feature highlights include:

    • New iOS framework.
    • New Text data type and supporting methods for improved text handling.
    • New Auto data type for storing any type or object.
    • New Xojo.Core classes that make creating international applications easier.
    • SSLSockets now support newer security protocols like TLS v1.1 and v1.2, and now defaults to TLS v1 instead of SSLv3.
    • For Web applications, a new HandleURL event allows processing requests for URLs that previously could not be served. This feature also gives you the ability to respond to requests from Google and other search engines.

    So as of now, we programmers, have two new development tools added to our repertoire: Xojo iOS and B4i (see previous article). Both with their advantages and drawbacks. As a Windows programmer it is nice for me to be able to develop iOS apps on my own platform with B4i. At the time of this writing, Xojo iOS is Mac only. But who knows, maybe there is some secret Santa out there that will put a Mac mini under my tree (hint!).

    But this a personal view of course. My code lib for android (B4A) is also vast and the conversion for my mobile apps is probably going to go smoother when I stay in the same language and OS. So in the end, it’s up to you to make a choice (or use both)! After all, it’s almost Christmas, so you all deserve a treat…

    Happy programming!


    B4i: Official release at special introductory price!

    B4I logo
    Great news from Anywhere Software! B4i (a development tool for native iOS applications) is released today.

    I had good hopes we would have an early Christmas this year from Erel, but it looks like he has outdone himself (again!).

    From its beta release only a couple of weeks ago, B4i looked very stable and already feature rich. Knowing how the B4A (Basic4Android) community quickly has grown very solid, with many contributors creating all kind of great libraries, I have no doubt B4i will be any different. Congratulations Erel with another state-of-the-art development tool!

    But let’s give the master himself the stand now (from the official site):

    Erel: B4i follows the same concepts of B4A and B4J and provides a simple yet powerful rapid application development tool for iOS applications.


    – Apple developer account (costs $99 per year).
    – An iOS device running iOS 7+.

    The compilation process requires a Mac computer. You can either use a local Mac computer or use our Hosted Mac Builder service (currently costs $25 per year).


    – Tutorials: http://www.basic4ppc.com/android/forum/forums/ios-tutorials.63/
    You should start with the following three tutorials:
    Creating a certificate and provisioning profile
    Installing B4i-Bridge and debugging first app
    Developers who use a local Mac: Local Mac Builder Installation

    – Formal documentation: http://www.basic4ppc.com/b4i/documentation.html


    B4i can be purchased here: http://www.basic4ppc.com/b4i
    It is now sold for a special introductory price of $99.
    B4i includes two years of free upgrades.

    Hosted Mac Builder

    The builder service allows you to develop iOS applications without a Mac computer.
    All of the development steps can be done with the builder service except of the final step which is uploading the application to Apple App Store. This step requires a Mac or a service such as MacInCloud.
    Note that the builder is currently limited to projects of up to 15mb.

    Looking forward to play with this!

    Xojo: ABXPlay alpha 0.7

    It has been a while since my last post, but I’ve been busy. This is the first alpha release of ABXPlay! For now it is closed source as I want to keep control over changes and bugs, but it will probably be open source when the final version arrives.

    ABXPlay is an advanced WebGL control for Xojo with a fall back to a HTML5 Canvas if the browser does not support WebGL.

    Drawing of primitives (line, rectangles, circles, arcs, polygons, curves, …)
    Sprites and Textures
    Container objects that group primitives and other containers
    Scaling, Alpha, Rotation, Position Tweening for all Containers
    Drag/Drop of Containers
    Multi user events
    Audio support
    Spritesheets and Spines
    Javascript injection
    Filters and Shaders
    Text (fonts, Google fonts and Bitmap fonts)
    Basic DOM object support

    Basic Box2D support
    Basic TMX support

    Included is the help, all the examples shown in the Xojo forum posts with source code and of course the ABXPlay engine/control.

    You can download alpha 0.7 here .
    The help is included in the download, but can also be consulted here

    For those who followed the adventures of our South Park friends, You’ll notice a final chapter. Although Chef solved the Kenny Ghost problem, it seems Eric still is suffering a bit. When he want’s to play some football (yes, I mean football, not soccer), one Kenny keeps giving him trouble!

    This illustrates some basic Box2D support. (Physics engine, Collisions, Joints).

    Box2D in ABXplay


    1. If you create a new project, make sure the control is locked on all sides of the window
    2. Set the properties on the control in the inspector (like the view properties, if it should be interactive, the Scaletype, etc…)
    3. Assets should be copied in the subfolder \Assets\ next to your project.
    4. Make sure also the \Engines\ folder is next to your project!
    5. To test another example, change the ‘DefaultWebPage’ to another one of the example WebPages.

    But most of all, have fun with it!


    Xojo: to fast with report on iOS update

    In my enthousiasm when I skimmed over Pauls blog post it seems I did some wishful thinking.
    Sure hope one day it may come through though…

    Paul Lefebvre:

    Sorry for the confusion, but my blog post only shows 2048 for desktop and web. The iOS screenshot is from the original 2048 game. An iOS version of 2048 written in Xojo is something I’m working on but I don’t have anything to share just yet!

    My apologies to my readers who were just like me already jumping around in anticipation. ‘But at the very least, you did some sport Alwaysbusy’, my doctor likes to add…



    Get every new post delivered to your Inbox.

    Join 446 other followers

    %d bloggers like this: