Installing OpenCV python

Tested on Ubuntu 12.04.4 Desktop (32-bit)
http://releases.ubuntu.com/12.04/ubuntu-12.04.4-desktop-i386.iso.torrent

See instructions at
http://www.samontab.com/web/2012/06/installing-opencv-2-4-1-ubuntu-12-04-lts/

I created a installation script
https://github.com/baligena/opencv_installation

but found a better more successfull shell one
https://github.com/jayrambhia/Install-OpenCV/blob/master/Ubuntu/2.4/opencv2_4_8.sh

updated 2014-08-19

Global Modules for Python

When importing inside a python script it first looks to see if the file is inside the current directory but if not it looks to see its in the python global folder(source) which in:

/usr/lib/python2.7/
or
/usr/lib/python3.2/

I like to create a symbolic links so I can still have my files inside a directory of my choosing and it being global.

$ ln -s /var/fsq/python/fsq_modules/ /usr/lib/python3.2/fsq_modules

PS.
there must be a __init__.py in the directory for it to work
http://stackoverflow.com/questions/338768/python-importerror-no-module-named

Python script in the browser

This site shows you how to setup apache2 so you can run python script in the browser (lampp). He shows a method on how to use an html form to fetch date from python using POST.

Running a script directly without POST and using urllib2 to fetch a website:
in the browser type:
http://localhost/cgi-bin/web.py

script:
#!/usr/bin/python
import cgi
import cgitb
import urllib2
cgitb.enable()

# Begin HTML generation, must be here
print "Content-Type: text/html; charset=UTF-8" # Print headers
print "" # Signal end of headers

# HTML is pushed to the page with print
# To save time you can use ''' to open and close a print
# statement for block printing

response = urllib2.urlopen('http://facebook.com')
print response.read()

print "hello world"

tags:
run python script html apache2 server
run python script html
urllib2 execute html

Create executable ubuntu icons for python script

First create you python script
pyqt_test.py:

#!/usr/bin/env python3

import sys
from PyQt4 import QtGui, QtCore
 
class HelloQt(QtGui.QDialog):
    def __init__(self):
        QtGui.QDialog.__init__(self)
 
        self.setWindowTitle("Hello Qt")
 
        # Vertical layout
        self.layout = QtGui.QVBoxLayout(self)
 
        # Create widgets
        self.label = QtGui.QLabel("What's your name?")
        self.name = QtGui.QLineEdit()
        self.output = QtGui.QLineEdit()
        self.output.setReadOnly(True)
 
        # Add widgets to the layout
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.name)
        self.layout.addWidget(self.output)
 
        # Connect self.name with self.sayHello(name) when text is changed
        self.connect(self.name, QtCore.SIGNAL("textChanged(const QString&)"), self.sayHello)
 
    def sayHello(self, name):
        # Set the output text
        self.output.setText("Hello " + name + "!")
 
if __name__ == "__main__":
        # Create QApplication
        app = QtGui.QApplication(sys.argv)
 
        # Create a HelloQt window and show it
        helloqt = HelloQt()
        helloqt.show()
       
        # Run the mainloop
        sys.exit(app.exec_())

make sure that your python script has the shebang on the first line.
Make pyqt_test.py an executable file by running
$ chmod +x pyqt_test.py

Now create the file /usr/share/applications/runPythonIcon.desktop:

[Desktop Entry]
Type=Application
Name=python gui
Exec=/home/bigbang/Desktop/python/pyqt_test.py 
Icon=/usr/share/icons/xchats_icon

make this file also executable by running
$ chmod +x runPythonIcon.desktop

Done.

Resource

Communication between Arduino and Computer using Python

Python code:

#communications between arduino and computer using python
import serial

#enter your device file
ser = serial.Serial('/dev/<your_device_file>', 9600) //windows: '/dev/com4' | linux: '/dev/ttyACM0'
while 1:
	print ser.readline().strip('\n')

Arduino Code:

/*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * http://arcfn.com
 */

#include 

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

Additional information

Python Barebones Web Server

"""
page 56 from Programming python O'Reilly 4th edition
Implement an HTTP web server in Python that knows how to run server-side
CGI scripts coded in Python; serves files and scripts from current working
dir; Python scripts must be stored in webdir\cgi-bin or webdir\htbin;
"""
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler

webdir = '.' # where your html files and cgi-bin script directory live
port = 80 # default http://localhost/, else use http://localhost:xxxx/

os.chdir(webdir) # run in HTML root dir
srvraddr = ("", port) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()# run as perpetual daemon

tag:
mini small

Python and MySQL

I needed a better way to prevent spammers from coming to my site.  I was manually retrieving their IP address and blocking on my .htaccess file.  However, I decided to automate it by using a python script, crontab, wordpress and MySQL.  My biggest issue was to get python to connect to mysql.

I build a script that fetches every IP address marked as spam in wordpress. Crontab runs this script every week which creates and replaces the .htaccess file with updated data.

stop_spam.py

htaccess python script, Clean URL

I enjoy the clean URL when it looks like http://baligena.com/home/page

However every time I create a new app I have to re-edit/create a htaccess file. This is too much work and remembering. Below is a python script for windows and linux that once ran inside the root folder of your site it will create an htaccess file to make that clean URL you always wanted. You can also fork it at GitHub

Warning! You may need to configure apache and php for the htaccess file to work. Click me for instructions.

createhtaccess.py

 

# this script customizes and creates the .htaccess to correspond to the current directory

import os

def create_htaccess():
f = open(‘./.htaccess’,’w’)
# get directory path
directory = os.getcwd()

# if linux
if os.name == ‘posix’:
dirname = directory[directory.rfind(‘/’)+1:]
# if windows
elif os.name == ‘nt’:
dirname = directory[directory.rfind(“\\”)+1:]
else:
exit(‘error occurred: couldnt determine the system this computer is on’)

f.write(”’
# http://codeigniter.com/wiki/mod_rewrite
# make sure you change the root url on line 27 RewriteRule ^(.*)$ directory/index.php?/$1 [L]
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#’system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn’t in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename ‘application’ to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ”’+ dirname + ”’/index.php?/$1 [L]
# If we don’t have mod_rewrite installed, all 404’s
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php

”’)
f.close()

if __name__ == ‘__main__’:
create_htaccess()