Installing PIL in Mac OS

PIL(Python Imaging Library) is an image processing library for python.

In this post I will show you how to install PIL.


  1. Python should be already installed on the machine. To make sure, just type ‘python’ in terminal and see if its already there.
  2. Xcode should already be installed

I installed PIL using pip.

If you dont have pip, do the following. Open the terminal and type the following:

curl -O
tar xzf pip-0.7.2.tar.gz
cd pip-0.7.2
sudo /usr/bin/python install

This will install pip. Once pip is installed, you can install PIL by following steps.

First make sure you have lib jpeg install for JPEG handling. To do that,

curl -O
tar zxvf jpegsrc.v8c.tar.gz
cd  jpeg-8c/
sudo make install

Then install PIL using pip

sudo pip install PIL



  1. Python for Mac OS
  2. Python Imaging Library (PIL)

bashrc in Mac OS

If you are working with CUDA or OpenCV on Mac OS, you need to provide proper paths before you compile. And in some cases you need to give these paths every time you open a terminal. In Linux, there is bashrc file in which we can add all the paths. But in Mac OS, I could not find it. We need to create a profile and it loads every time we open a terminal.

To make your own profile, open the terminal and type

sudo vi /etc/bashrc

At the end of this file, add the following line

source ~/.bashrc

Now if you restart the terminal, you get a warning :

-bash: /Users/username/.bashrc: No such file or directory

Now create this file

vim .bashrc

Add whatever the paths you want into this file. For example, I would add

export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
export LD_LIBRARY_PATH=/usr

Save the file.

Now restart the terminal. Whenever you start a terminal from now on all the settings in bashrc file are loaded.

Done and done!:)

Using OpenCL with Eclipse on Mac OS

It’s very easy to execute an openCL code in Mac, by simply using the flag ‘-framework OpenCL’ during compilation.

But some times when dealing with large projects, it becomes necessary to have a visual structure of the code tree, just the command line won’t do the trick. In this post, I will show how to integrate an OpenCL project with Eclipse IDE.

Eclipse is an open-source, cross-platform IDE for developing applications using many languages. Firstly, make sure that you have OpenCL installed on your machine. Latest versions of Xcode are shipped with OpenCL, so no extra installation is required.

  1. Install Eclipse IDE for C/C++ from here
  2. Once installed, open the application
  3. From File menu, select New -> C++ Project
  4. One the project is created, add a C++ source file, name it as test.cpp and write the following code into it:
    #include <stdio.h>
    #include <stdlib.h>
    #ifdef __APPLE__
    #include <OpenCL/opencl.h>
    #include <CL/cl.h>
    using namespace std;
    int main(int argc, char* const argv[])
        //Number of devices
        cl_uint num_devices, i;
        //Getting device ids
        clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices);
        cl_device_id* devices = (cl_device_id*)calloc(sizeof(cl_device_id), num_devices);
        clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, num_devices, devices, NULL);
        char buf[128];
        for (i = 0; i < num_devices; i++)
                clGetDeviceInfo(devices[i], CL_DEVICE_NAME, 128, buf, NULL);
                fprintf(stdout, "Device %s supports ", buf);
                clGetDeviceInfo(devices[i], CL_DEVICE_VERSION, 128, buf, NULL);
                //Printing device info
                fprintf(stdout, "%s\n", buf);

    The above code basically prints out the details of the devices available on your machine.

  5. Right click on the project and click settings. In C/C++ build, choose settings. Click MacOS X C++ Linker. In command field, it should be g++ -framework OpenCL
  6. Click on GCC C++ compiler, in inlcudes field paste this


    Choose other flags as needed

  7. Then, right click on project and select build. Then run your program.
    This is the output from the console

    Device GeForce 320M supports OpenCL 1.0
    Device Intel(R) Core(TM)2 Duo CPU     U9600  @ 1.60GHz supports OpenCL 1.0


Update: To use the same settings again for a different project, try the following

  1. Start an Empty C++ project
  2. Add a cpp source file and write some openCL code into it
  3. In the Project Explorer, right click on the project and click Import…. You will see the following dialog box
  4. In C/C++, select C/C++ Project Settings, then click Next
  5. Create the file ‘OpenCL_properties.xml‘ and write the following into it
    <?xml version="1.0" encoding="UTF-8"?>
    <section name="org.eclipse.cdt.internal.ui.wizards.settingswizards.IncludePaths">
    <language name="Object File">
    <language name="Assembly Source File">
    <language name="C++ Source File">
    <language name="C Source File">
    <section name="org.eclipse.cdt.internal.ui.wizards.settingswizards.Macros">
    <language name="Object File">
    <language name="Assembly Source File">
    <language name="C++ Source File">
    <language name="C Source File">
  6. For the Settings File, use the above xml file
  7. One more thing left to do. Right click on the Project and select Properties
  8. Under MacOS X C++ Linker, make sure you have g++ -framework OpenCL


  9. Done and done! You can build and run the project now. You can use the same configuration file for other projects

Asilomar Conference

During my final year at Indian Institute of Technology Madras, I worked on accelerating a decoder for Polar Codes. My project was titled ‘A GPU implementation of Belief Propagation Decoder for Polar Codes’. I used GPUs to accelerate the decoding process for Polar Codes.

Polar Codes are a class of capacity achieving codes for any Binary-input Discrete Memoryless Channel (B-DMC). These are based on the concept of channel polarization which suggests that given N-independent copies of a channel, we can synthesize another set of N-channels, that show a polarization effect in the sense that as N grows large, the channels tend to become either completely noisy or completely noise-free, with the noise-free channels approaching the capacity. Channel polarization suggests that we transmit information with rate 1 over these noise-free channels, while fixing the symbols over the noisy-channels to values known to both the sender and receiver.

I implemented the Belief Propagation decoder  for Polar Codes using GPUs and observed a good throughput rate. I submitted an extended abstract at Asilomar Conference on Signals, Systems and Computers, 2012. It was accepted and I was invited to present my results at the conference which was held at Asilomar Conference Grounds, Pacific Grove, California from November 4th to 7th.

Firstly, the place was really awesome. It was along the coast and the conference housing had a great view of the ocean. The lodging was like one of those medieval-style architecture.

Conference Housing

The place itself was really beautiful. The weather was pleasant. And I have been longing for a good beach for quite some time. My professor joined me for the conference. After checking into the hotel room, the first thing he said, “Come on, let’s go to the beach!”😉

Asilomar Beach, Pacific Grove, California

It was a great place to watch sunset all the way.

Sunset at Asilomar beach

This was my paper

I might have been one of the youngest persons to present at this conference. And these are my presentation slides. My paper would soon be published in the IEEE proceedings.:)


Search and replace a word in a file using Vim editor

There are many times when you want to replace multiple occurrences of a word in a file with another word. In small files you can do it manually. But in large files, you can’t take on that method. Vim editor provides a simple command to do this. Say you want to replace a word ‘begin‘ with the word ‘end‘ from a file ‘test‘.

In the terminal,

vim test

Once you have the file opened, simply type this command


This command will replace all the occurrences of ‘begin‘ with ‘end

Vector Addition – OpenCL

In this post, I will show you how to write a vector addition code using OpenCL . The code is listed below:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

#ifdef __APPLE__
#include <OpenCL/opencl.h>
#include <CL/cl.h>

#define DATA_SIZE 10

using namespace std;

const char *ProgramSource =
"__kernel void add(__global float *inputA, __global float *inputB, __global float *output)\n"\
"  size_t id = get_global_id(0);\n"\
"  output[id] = inputA[id] + inputB[id];\n"\

int main(void)
cl_context context;
cl_context_properties properties[3];
cl_kernel kernel;
cl_command_queue command_queue;
cl_program program;
cl_int err;
cl_uint num_of_platforms=0;
cl_platform_id platform_id;
cl_device_id device_id;
cl_uint num_of_devices=0;
cl_mem inputA, inputB, output;

size_t global;

float inputDataA[DATA_SIZE]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float inputDataB[DATA_SIZE]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float results[DATA_SIZE]={0};

int i;

// retreive a list of platforms avaible
if (clGetPlatformIDs(1, &platform_id, &num_of_platforms)!= CL_SUCCESS)
printf("Unable to get platform_id\n");
return 1;

// try to get a supported GPU device
if (clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 1, &device_id, &num_of_devices) != CL_SUCCESS)
printf("Unable to get device_id\n");
return 1;

// context properties list - must be terminated with 0
properties[0]= CL_CONTEXT_PLATFORM;
properties[1]= (cl_context_properties) platform_id;
properties[2]= 0;

// create a context with the GPU device
context = clCreateContext(properties,1,&device_id,NULL,NULL,&err);

// create command queue using the context and device
command_queue = clCreateCommandQueue(context, device_id, 0, &err);

// create a program from the kernel source code
program = clCreateProgramWithSource(context,1,(const char **) &ProgramSource, NULL, &err);

// compile the program
if (clBuildProgram(program, 0, NULL, NULL, NULL, NULL) != CL_SUCCESS)
printf("Error building program\n");
return 1;

// specify which kernel from the program to execute
kernel = clCreateKernel(program, "add", &err);

// create buffers for the input and ouput

inputA = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float) * DATA_SIZE, NULL, NULL);
inputB = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(float) * DATA_SIZE, NULL, NULL);
output = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * DATA_SIZE, NULL, NULL);

// load data into the input buffer
clEnqueueWriteBuffer(command_queue, inputA, CL_TRUE, 0, sizeof(float) * DATA_SIZE, inputDataA, 0, NULL, NULL);
clEnqueueWriteBuffer(command_queue, inputB, CL_TRUE, 0, sizeof(float) * DATA_SIZE, inputDataB, 0, NULL, NULL);

// set the argument list for the kernel command
clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputA);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &inputB);
clSetKernelArg(kernel, 2, sizeof(cl_mem), &output);


// enqueue the kernel command for execution
clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global, NULL, 0, NULL, NULL);

// copy the results from out of the output buffer
clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sizeof(float) *DATA_SIZE, results, 0, NULL, NULL);

// print the results
printf("output: ");

for(i=0;i<DATA_SIZE; i++)
printf("%f ",results[i]);

// cleanup - release OpenCL resources

return 0;


To compile the code on a Mac, open terminal and type

g++ -o add add.c -framework OpenCL

The output is :

output: 2.000000

Take a look at line number 53, CL_DEVICE_TYPE_GPU is used to select a GPU device. Other alternatives for this flag include CL_DEVICE_TYPE_CPUCL_DEVICE_TYPE_ACCELERATORCL_DEVICE_TYPE_ALL etc . Refer to OpenCL documentation for more details (see here).

OpenCL code structure

OpenCL is the first open, royalty-free standard for cross-platform, parallel programming of modern processors found in personal computers, servers and handheld/embedded devices. OpenCL (Open Computing Language) greatly improves speed and responsiveness for a wide spectrum of applications in numerous market categories from gaming and entertainment to scientific and medical software.

The Khronos consortium that manages the OpenCL standard has developed an applications programming interface (API) that is general enough to run on significantly different architectures while being adaptable enough that each hardware platform can still obtain high performance. The OpenCL API is a C with a C++ Wrapper API that is defined in terms of the C API. There are third-party bindings for many languages, including Java, Python, and .NET. The code that executes on an OpenCL device, which in general is not the same device as the host CPU, is written in the OpenCL C language. OpenCL C is a restricted version of the C99 language with extensions appropriate for executing data-parallel code on a variety of heterogeneous devices.

Let’s get started with OpenCL program structure. In the process, I will also indicate the analogy between CUDA and OpenCL commands later. In this way, it will be easy to learn CUDA and OpenCL side by side. In general, writing a code in OpenCL can be generalized in the following steps:

  1. Discover and initialize the platforms
  2. Discover and initialize the devices
  3. Create a context
  4. Create a command queue
  5. Create device buffers
  6. Write host data to device buffers
  7. Create and compile the program
  8. Create the kernel
  9. Set the kernel arguments
  10. Configure the work-item structure
  11. Enqueue the kernel for execution
  12. Read the output buffer back to the host
  13. Release OpenCL resources

Discover and initialize the platforms

In the OpenCL platform model, there is a single host that coordinates execution on one or more devices. The API function clGetPlatformIDs( ) is used to discover the set of available platforms for a given system.

Discover and initialize the devices

clGetDeviceIDs( ) is used to discover the devices. clGetDeviceInfo( ) is called to retrieve information such as name, type, and vendor from each device.

Create a context

A context is an abstract container that exists on the host. A context coordinates the mechanisms for host–device interaction, manages the memory objects that are available to the devices, and keeps track of the programs and kernels that are created for each device. The API function to create a context is clCreateContext( ).

Create a command queue

Communication with a device occurs by submitting commands to a command queue. The command queue is the mechanism that the host uses to request action by the device. The API clCreateCommandQueue( ) is used to create a command queue and associate it with a device.

Create device buffers

In order for data to be transferred to a device, it must first be encapsulated as a memory object. The API function clCreateBuffer( ) allocates the buffer and returns a memory object.

Write host data to device buffers

Data contained in host memory is transferred to and from an OpenCL buffer using the commands clEnqueueWriteBuffer( ) and clEnqueueReadBuffer( ), respectively.

Create and compile the program

OpenCL C code is called a program. A program is a collection of functions called kernels, where kernels are units of execution that can be scheduled to run on a device.

The process of creating a kernel is as follows:

  • The OpenCL C source code is stored in a character string. If the source code is stored in a file on a disk, it must be read into memory and stored as a character array.
  • The source code is turned into a program object,cl_program,by calling clCreate ProgramWithSource( ).
  • The program object is then compiled, for one or more OpenCL devices, with clBuildProgram( ).

Create the kernel

Now we have to obtain a cl_kernel object that can be used to execute kernels on a device is to extract the kernel from the cl_program. Extracting a kernel from a program is similar to obtaining an exported function from a dynamic library. The name of the kernel that the program exports is used to request it from the compiled program object. The name of the kernel is passed to clCreateKernel( ), along with the program object, and the kernel object will be returned if the program object was valid and the particular kernel is found.

Set the kernel arguments

Each kernel argument individually using the function clSetKernelArg( ). 

Configure the work-item structure

Define an index space (global work size) of work items for execution.

Enqueue the kernel for execution

Requesting that a device begin executing a kernel is done with a call to clEnqueueNDRangeKernel( ).

Read the output buffer back to the host

Use clEnqueueReadBuffer( ) to read the OpenCL output

Release OpenCL resources

This is done using appropriate clRelease commands.

In the next post, I will show an OpenCL equivalent of CUDA vector addition code from the previous post and then the command analogy between CUDA and OpenCL.


  3. Book – Heterogeneous Computing With OpenCL: