analitics

Pages

Thursday, September 13, 2012

Simple python script - Voronoi diagram

Today I show you how to make Voronoi diagram using python.

I use this to make textures for underwater.

This is just one example. But you can improve to control all cells of voronoi diagram.

The theory say:

In mathematics, a Voronoi diagram is a special kind of decomposition of a metric space, determined by distances to a specified family of objects (subsets) in the space. These objects are usually called the sites or the generators...Source : wikipedia.

I used the euclidean distance to make the Voronoi diagram because it's the most familiar case.

About wikipedia - Euclidean_distance: In mathematics, the Euclidean distance or Euclidean metric is the "ordinary" distance between two points that one would measure with a ruler, and is given by the Pythagorean formula...

My python script use the next python modules:

PIL - this allow me to use image functions.

random - this module give me... random numbers.

math - some math functions.

Let's see the source code :


from PIL import Image
import random
import math

Now I make the function named gen_voronoi.

This take the height and width of the output image and the number of cells.

The function has some random variables for red , green , blue - nr,ng,nb.

The function hypot is not accessible directly so we need to import math module and using math static object.

The return value is the Euclidean norm : sqrt(x*x + y*y).


def gen_voronoi(w, h, cells):
 image = Image.new("RGB", (w, h))
 putpixel = image.putpixel
 img_x, img_y = image.size
 nx = []
 ny = []
 nr = []
 ng = []
 nb = []
 for i in range(cells):
  nx.append(random.randrange(img_x))
  ny.append(random.randrange(img_y))
  nr.append(random.randrange(256))
  ng.append(random.randrange(256))
  nb.append(random.randrange(256))
 for y in range(img_y):
  for x in range(img_x):
   dmin = math.hypot(img_x-1, img_y-1)
   j = -1
   for i in range(cells):
    d = math.hypot(nx[i]-x, ny[i]-y)
    if d < dmin:
     dmin = d
     j = i
   putpixel((x, y), (nr[j], ng[j], nb[j]))
 image.save("output.png", "PNG")
 image.show()

Use the function to make the output.png image.


gen_voronoi(200, 200, 55)

The result is :

Thursday, August 30, 2012

Python script using OpenCV to detect / recognition faces on photos

This is old tutorial make long time ago by me to detect faces on photos.

If you know more about OpenCV module , then is easy to understand source code.

First I load the modules:

import opencv.cv as cv
import opencv.highgui as gui
import opencv

Next I set the variables and data blocks processed some particular features of the modules loaded.

hc = cv.cvLoad("haarcascade_frontalface_default.xml")
img = gui.cvLoadImage("me.jpg",cv.CV_BGR2RGB)
storage = cv.cvCreateMemStorage(0)
cascade = cv.cvLoadHaarClassifierCascade('haarcascade_frontalface_alt.xml',cv.cvSize(1, 1))
grayscale = cv.cvCreateImage(cv.cvSize(img.width, img.height), 8, 1)
cv.cvCvtColor(img, grayscale, cv.CV_BGR2GRAY)

This is part where is detect faces and save the output like a jpeg image.

faces = cv.cvHaarDetectObjects(grayscale, cascade,\ 
storage,1.2,2,cv.CV_HAAR_DO_CANNY_PRUNING, cv.cvSize(5, 5))

if faces:
 for i in faces:
  cv.cvRectangle(img, cv.cvPoint( int(i.x), int(i.y)),cv.cvPoint(int(i.x + i.width), int(i.y + i.height)),cv.CV_RGB(0, 255, 0), 3, 8, 0)
gui.cvSaveImage("faces_detected.jpg", img)

The haarcascade_frontalface_default.xml file it's from internet, but you can create one if you want.

Maybe in the next tutorial I will show how.

Let's see the result. The input image file is:

... and the result is:

Saturday, August 25, 2012

The new tutorial about pstats python module.

Today I make a new tutorial about pstats python module.

The pstats module is a statistics browser for reading and examining profiler program.

This is provided in the modules cProfile, profile and pstats.

Because it's a long tutorial with long row , I put this tutorial on my tutorials website.

You can find it here on Python section.

Friday, August 24, 2012

Python 3.2 : Start with Django 1.4.

Although most of us prefer the python version 2.6, today I tried to install the latest version of django and python 2.3.2 .
Make a new folder , named test-dj .
$mkdir test-dj
$cd test-dj/
On the official site, I got the two archives:
django-django-1.4-919-ge57338f.zip
Python-3.2.3.tar.bz2
I will start with the installation of python. We unzip the archive:
$tar xvjf Python-3.2.3.tar.bz2 
We execute the following commands to install python:
$cd Python-3.2.3
$./configure
$make all
$sudo make altinstall
# python3.2 setup.py install 
Let's see what we have.
$ whereis  python3
python3: /usr/lib/python3.0 /usr/local/bin/python3.2m-config
/usr/local/bin/python3.2 /usr/local/bin/python3.2m 
/usr/local/lib/python3.2
As you see it's ...
python3.2
python3.2m
python3.2m-config
In accordance with the PEP-3149 we can got this:
Python implementations MAY include additional flags in the file name tag as appropriate. For example, on POSIX systems these flags will also contribute to the file name:

        * --with-pydebug (flag: d)
        * --with-pymalloc (flag: m)
        * --with-wide-unicode (flag: u)

Now we need to install django.
$unzip django-django-1.4-919-ge57338f.zip
Go to the django folder:
$cd django-django-e57338f/
# python3.2 setup.py install 
Now , we can test it:
# python3.2
Python 3.2.3 (default, Aug 24 2012, 19:24:21) 
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django 
>>> print(django.get_version())
1.5
>>> 
I will make another tutorial about how to configure the django to have one website.

Monday, June 25, 2012

Access system version information using python platform module.

The platform module includes the tools to take some infos about operating system, and hardware platform where a program is running.

import platform
dir(platform)

Show all about this module.

Also you can use the help.

help(platform)

Let's try another

print platform.win32_ver()
('', '', '', '')

So is not Windosw OS.

print platform.system()
Linux

Can be 'Linux', 'Windows' or 'Java' ...

print platform.version()

Show you the system's release version ( can be Debian , Ubuntu , Fedora ).

print platform.architecture()
('32bit', 'ELF')
print platform.uname()

Show the infos like uname linux command.

print platform.release()

Show the kernel use by system.

print platform.machine()
i686
print platform.node()

Show the computer's network name.

print platform.linux_distribution()

Show you the linux distribution.

Monday, April 30, 2012

Create tile image for your game using python script

What is tile image?
Tile image is a method of storing a sequence of images placed in a single image file.
These images are then processed according to user needs.
Here's an example below:
How we can create these images?
We can use graphics editing software to create them separately.
I used Blender 3D to create separate images.
A tutorial how to do this can be found here on section Blender 3D.
After I rendered images separately and named: 0000.png , 0001.png , 0002.png , 0003.png
I created a python script to put in an tile image, see below:
import os
import PIL
from PIL import Image
from PIL import ImageDraw
o=Image.new("RGBA",(192,48))
d= ImageDraw.Draw(o)
for pic in range(0,4):
        strpic=str(pic)
        filnam="000"+strpic+".png"
        x=pic*48
        img=Image.open(filnam)
        o.paste(img,(0+x,0))
        o.save("out.png")
The script reads the image files of size 48 pixels and puts them into one image called out.png

Resize screenshot with PIL python module .

The script that I've created is made ​​to shrink images. Some screenshots are large and should be resized to be used later on the Internet. It is a simple example that uses PIL module. This script reads the image name that I want to resize and filename that will be saved image. I use python PIL functions how to create a new image.
"""
This python script read the name of image and will create a new image with the given width and height.

$ python imgresz.py 
filename input image:test.png
test.png
filename output image:test-out.jpg
->width:500
->height:400
"""
import os 
import sys
from PIL import Image 
from PIL import ImageDraw
filnaminp=raw_input("filename input image:")
filnamout=raw_input("filename output image:")
w=input("->width:")
h=input("->height:")
imgi=Image.open(str(filnaminp))
imgo=imgi.resize((w,h),Image.BILINEAR)
imgo.save(str(filnamout))

Saturday, April 7, 2012

When to use '__main__' ?

When your script is run it as a command to the Python interpreter: python your_script.py all of the code that is at indentation level 0 gets executed and functions and classes that are defined but none of their code gets ran. If will then read :
if __name__ == '__main__'
so it will execute the block standalone. In other words, when you use the __main__ this means the module is being run standalone
if __name__ == '__main__':
 print '... is being run by itself'
else:
 print '... is being run directly'

Sunday, February 26, 2012

The wx module - tutorial 02 - class and button function

In this tutorial I will show how to use wx using one class example.

This tutorial is based on some code from a previous tutorial.

Let's see the source code:

import wx

class my_gui_form(wx.Frame):
 def __init__(self):
  wx.Frame.__init__(self, None, -1, 'Example windows wx with Python',size=(300,150))
  wx.StaticText(self, -1, 'User', (10, 20))
  user = wx.TextCtrl(self, -1, '',  (110, 20), (160, -1))
  wx.StaticText(self, -1, 'Password', (10, 50))
  passwd = wx.TextCtrl(self, -1, "", (110,50),(160, -1), style=wx.TE_PASSWORD)
  conn = wx.Button(self, -1,'Connect',(10,80),(260, -1))
  conn.Bind(wx.EVT_BUTTON, self.onButton)
  
 def onButton(self, event):
  button = event.GetEventObject()
  print "The button's label is: " + button.GetLabel()
  print "The button's name is: " + button.GetName()

if __name__ == "__main__":
 app1 = wx.App(False)
 frame = my_gui_form()
 frame.Show()
 app1.MainLoop()

First , I make a class named my_gui_form.

Also I add the self on each function from this class.

I make the onButton function to working with the button Connect.

I read the event of the button with event.GetEventObject.

The link with this function is make by:

conn.Bind(wx.EVT_BUTTON, self.onButton)

Source Code Optimization:

The -1 from is can replace with wx.ID_ANY.

Thursday, February 23, 2012

The wx module - tutorial 01

Install wx python module using root account.

# yum install wxPython.i686 

The most simple example is show bellow.


$python 
Python 2.7.2 (default, Oct 27 2011, 01:36:46) 
[GCC 4.6.1 20111003 (Red Hat 4.6.1-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> app1=wx.App()
>>> frame=wx.Frame(None,-1,'Example windows wx with Python')
>>> frame.Show()
True
>>> app1.MainLoop()
>>> 

Let's see the result of this python script:

Let's take a look at the source code.

import wx

This line of code allows us to use wx python module.

app1=wx.App()

This line defines our application named app1.

A frame is a window whose size and position can be changed by the user.

Let's see:

frame=wx.Frame(None,-1,'Example windows wx with Python')
frame.Show()

Finally, processing and display function in main function.

app1.MainLoop()

Bellow, we can see a more complex example, where we find : labels , two editbox and one button.

The event-processing function button has not been implemented.

import wx
app1=wx.App()
frame=wx.Frame(None,-1,'Example windows wx with Python',size=(300,150))
wx.StaticText(frame, -1, 'User', (10, 20))
user = wx.TextCtrl(frame, -1, '',  (110, 20), (160, -1))
wx.StaticText(frame, -1, 'Password', (10, 50))
passwd = wx.TextCtrl(frame, -1, "", (110,50),(160, -1), style=wx.TE_PASSWORD)
conn = wx.Button(frame, -1,'Connect',(10,80),(260, -1))
frame.Show()
app1.MainLoop()

Let's see the result of this python script:

I will illustrate how this working in a future tutorial.

Saturday, November 26, 2011

Simple socket client with python

I made version of client server socket program.
This example was presented in a previous post named Simple socket server with python.
The program is simple, the algorithm uses connection and some data processing input from the console.
I used the same test method as for the program created in C + +.
The program breaks the connection when the client enter: end connection
Here's the source code:
import socket
import sys

HOST = 'your-IP'
PORT = 5001             
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
 s = socket.socket(af, socktype, proto)
    except socket.error, msg:
 s = None
 continue
    try:
 s.connect(sa)
    except socket.error, msg:
 s.close()
 s = None
 continue
    break
if s is None:
    print 'could not open socket'
    sys.exit(1)
data=''
while data<>'end connection':
 data=raw_input()
 s.send(data)
 data = s.recv(1024)

s.close()
print 'Received', repr(data)

Sunday, November 20, 2011

Simple socket server with python

It is a small example I created a server to see how it works with a client program made ​​in C + +.
I can not say that it really is a server that does not accept multiple connections.
The script worked stable sending manually entered text.
I not checked the stability for the large data streams.
It is also normal because as you see below is just one example.

import socket 
HOST = 'your-IP'
PORT = 5001
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn,addr=s.accept()
print 'Conectat la =',addr
while 1:
 data = conn.recv(1024)
 if not data : 
  break
 conn.send(data)
 print data
conn.close()
The distance between me and the server was considerable.

Tuesday, October 25, 2011

The python module : spynner

On official site we see the description of the spynner module :
Spynner is a stateful programmatic web browser module for Python with Javascript/AJAX support based upon the QtWebKit framework.
The module is esay to use. With few lines of codes you can use this module to parse ,view and use web pages.
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import re
import spynner
from BeautifulSoup import BeautifulSoup
import time
br = spynner.Browser()
br.create_webview()
br.show()
br.set_html_parser(BeautifulSoup)
br.load("http://www.linuxtoday.com/")
br.fill("input[name=username]", "name")
br.fill("input[name=passwd]", "pass")
#br.simulate_click("input[name=submit]",True)
#br.select("IBESNA~US")
#br.select('option[value="IBESNA~US"]')
#br.wait_page_load()
br.browse()

The result is show in the image bellow:
The source code is not complete. I make this simple example just to show us how to fill some editbox.
If you wantthen you can develop this script and make more useful.
I wait your answers with source code additions and new ways of using this python module.