OpenCV install

I can finally use OpenCV in Python after several attempts over the last few months. Previously, I could not import or use it even though it appeared to be installed along with Python XY.

In a nutshell:
1) Installed PythonXY 2.7.2.1
2) import cv2.cv as cv (for running older cv examples)

I tried searching for a simple solution but all I found were complicated install instructions involving ‘builds’ or ‘building’ on your system and other sources that made this all seem easy.
Finally, I came across the revision listing for Python XY and found that the newest version solves some issue with it. So I updated from 2.6 to 2.7.
But no where did I see anything about having to ‘import cv2.cv’. All of the code snippets I’ve seen just ‘import cv’. I finally came across a code that had ‘import cv2.cv’ and tried it and everything finally worked, the door was finally unlocked. Except for having seen that import statement in some code, how was I to know that I needed to import cv2 instead of cv?

MATLAB to Python

In case I need to convert MatLab code to Python again…

origunits(1:3)
->    
origunits[:3]
## Because MatLab starts with 1 and includes the last number
## and Python does neither
fgetl(fid)  
->    
fid.readline().rstrip()
strcmp(unt(1:3),'ori')
->    
unt[:3] == 'ori'
error('Unknown units')
->    
raise Exception('Unknown units')
switch unt(1:3),
    case 'fee',
       ...
    case 'met',
       ...
->    
if unt[:3] == 'fee':
    ...
elif unt[:3] == 'met':
    ...
## Python does not have a 'switch-case' control
fprintf('Station: %s\n',pred.station);
->    
print( 'Station: {0}'.format(pred.station) )
## Newline char not needed
clear pred
->    
del pred
xtide=struct('name',repmat(' ',ncon,8),'speed',zeros(ncon,1),...
             'startyear',0,'equilibarg',zeros(ncon,68),...
             'nodefactor',zeros(ncon,68));
->
xtide = dict({'name':numpy.tile(' ',(ncon,8)), 
              'speed':zeros((ncon,1)),
    	      'startyear':0,
              'equilibarg':zeros((ncon,68)),
              'nodefactor':zeros((ncon,68)) })
## Numpy.tile replaces 'repmat'. Add parenthesis for 'zeros'.

Monty Hall Python

Monty Hall problem simulation.
Player picks one of three doors (to win a car). Without opening the players door, the host opens a non-winning door (or win a goat). The player then can switch to the other closed door and stay with the first choice.

import random

def main(trials=12345, number_doors=3):
    # SHOW THE RANDOMNESS OF THE GAME SETUP
    show_game_randomness(trials, number_doors)
    
    # TEST NEVER SWITCHING AND ALWAYS SWITCHING
    # TRY NEVER SWITCHING
    trues = 0
    for trial in xrange(trials):
        is_car = play_a_game(SWITCH=False, number_doors=number_doors)
        if is_car: trues += 1
    print '{0} games and never switching: {1} wins ({2:.2%})'.format(
           trials, trues, trues/float(trials))
    # TRY ALWAYS SWITCHING
    trues = 0
    for trial in xrange(trials):
        is_car = play_a_game(SWITCH=True, number_doors=number_doors)
        if is_car: trues += 1
    print '{0} games and always switching: {1} wins ({2:.2%})'.format(
           trials, trues, trues/float(trials))
    
    
def play_a_game(SWITCH=False, number_doors=3):
    doors = newgame(number_doors)
    whose_door = ['']*number_doors
    # PLAYER SELECTS A DOOR
    whose_door[random.randint(0,number_doors-1)] = 'player'
    
    # HOST SHOWS A GOAT (SELECTS A GOAT DOOR)
    while True:
        host_sel = random.randint(0,number_doors-1)
        if doors[host_sel] != 'car' and whose_door[host_sel] != 'player':
            whose_door[host_sel] = 'host'
            break
        
    # SWITCH DOORS?
    if SWITCH:
        while True:
            player_sel = random.randint(0,number_doors-1)
            if whose_door[player_sel] != 'host' and whose_door[player_sel] != 'player':
                break
        whose_door[whose_door.index('player')] = 'nevermind'
        whose_door[player_sel] = 'player'
        
    # RETURN RESULT
    return True if doors[whose_door.index('player')] == 'car' else False
        
     
def newgame(number_doors=3):
    car_index = random.randint(0,number_doors-1)
    doors = ['goat']*number_doors
    doors[car_index] = 'car'
    return doors
    
    
def show_game_randomness(trials, number_doors=3):
    trial_results = [0]*number_doors    
    while True:
        doors = newgame(number_doors)
        trial_results[doors.index('car')] += 1
        
        if sum(trial_results) >= trials:
            print 'Car occurance:',
            print trial_results, 'times.',
            print ['{0:.2%}'.format(x/float(sum(trial_results))) for x in trial_results]
            break


if __name__ == '__main__':
    main()

When I read this problem and how switching doors is the best solution, it was a little hard to believe. I realized why switching is a good idea when programming the host’s selection process to show a goat. Since 2/3rds of the time, the host is constrained in his choice of the two remaining doors, therefor, 2/3rds of the time, the car is behind the door the host does not pick.

Saving a canvas animation

The only built-in image save function for Tkinter canvas is a postscript save. This didn’t work for me and instead of finding out why, I thought of another way which works great.
Create a frameless canvas window using ‘overrideredirect(1)’, place the canvas in the top corner and use PIL’s ImageGrab and save the images. Finally, ‘destroy’ the window when finished, since there is no kill button in the top corner. Here is an example that animates a polygon moving on the canvas.

from Tkinter import *
from PIL import ImageGrab
from numpy import array
import os


class App(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.overrideredirect(1)
        
        self.width = 900
        self.height = 640
        self.initialize()
        
    def initialize(self):
        self.c = Canvas(self, width=self.width, height=self.height, background='white')
        self.c.pack(side=RIGHT, expand=YES, fill=BOTH)
        self.update()
        
        self.run_anim()
        self.destroy()
        
        
    def run_anim(self):
        print os.getcwd()
        c = self.c
        polyo = array([34,60,226,15,419,60,359,151,91,151])
        polyd = array([205,253,296,187,388,253,353,360,239,360])
        trantime = 20
        for i in xrange(trantime):
            c.delete('pol')
            ptrans = (float(i)/trantime)*polyd+(trantime-float(i))/trantime*polyo
            c.create_polygon(list(ptrans), width=4, outline='black', fill='red', tags='pol')


            self.update()
            savename = 'im_{0:0>6}'.format(i)
            ImageGrab.grab((0,0,900,640)).save(savename + '.jpg')
            

app = App(None)
app.mainloop()