Tag Archives: Python

First Demo “Threshold.py”

How about we open a image, do some calcs and save it?

This is the first post about it, so how can we open a image in python? usually images can be in a lot of different formats so to solve this puzze and to simplify the thinks a little bit we will use a tool called PIL (Python Imaging Library).

To simplify the things we will use a library called NumPy (Numeric Python) to deal with matrices.

First of all, if you don’t have PIL or Numpy install it. On ubuntu you can just type “sudo apt-get install python-imaging python-numpy

File: threshold.py

Selec All Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/python
#-*- coding: utf-8 -*-
# 
# Author: Fernando Paolieri Neto | 07-aug-2011
# 
 
#import needed libraries
import Image
import numpy
import sys
 
#function to convert numpy to pil
def array2pil(arr):
  nd = len(arr.shape)
  x = arr.astype('B')
  if nd == 2:
    d, h, w = (1,) + arr.shape
    mode = 'L'
  elif nd == 3:
    if arr.dtype.char == '?':
      raise TypeError, "Binary array cannot be RGB"
    h, w, d = arr.shape
    if   d == 1: mode = 'L'
    elif d == 3: mode = 'RGB'
    elif d == 4: mode = 'RGBA'
    else:
      raise TypeError, "Array first dimension must be 1, 3 or 4 (%d)" % d
  else:
    raise TypeError, "Array must have 2 or 3 dimensions (%d)" % nd
  pil = Image.fromstring(mode, (w,h), x.tostring())
  if arr.dtype.char == '?':
    pil = pil.point(lambda i: i>0, '1')
  return pil
 
if __name__ == "__main__":
  #read image using Pil
  img = Image.open(sys.argv[1])
 
  #convert Pil image to Numpy Array
  F = numpy.asarray(img)
 
  #if -B is passed by argument we will do the averege
  #of the 3 channels R,G and B
  if '-B' in sys.argv:
    F= (F[:,:,0]/3 + F[:,:,1]/3 + F[:,:,2]/3)
 
  #Do the threshold
  F = (F>127)*numpy.uint8(255)
 
  #If -I is passed, the image will be inverted
  if '-I' in sys.argv:
    F = 255-F
 
  #convert to pil
  img = array2pil(F)
  #save output
  img.save("out.png","PNG")

Save your file as threshold.py or get it from GitRepository.

Now lets us just run the program (example on ubuntu):

python threshold.py imageIn.jpg -B -I

If you set -B will be used the average, and if you set -I the image will be inverted.
As result a new image called out.png will be generated.

A demo was build in CGI to show this code running on a webserver. Threshold Demo

Tagged , , ,

Encoding, Decoding, Weird characters??

Have you haver had a problem with charset encoding?

I had, a lot. Why? us on Brazil use a lot of ‘é’, ‘ç’, ‘ã’, ‘í’ and a lot of other chars that have different definitions on different encoding like (ISO 8895-1, UTF-8 and some others).

So often happens that you wrote a full document on latex (by example), and save it as UTF-8 on your text editor. When u open it on the next time all your special characters will be like %% and other weird characters.

To prevent it try always to put on your source code a explicitly definition of the used encoding on the header of your file.

Selec All Code:
1
#-*- coding: utf-8 -*-

Most of the text editors will read this header and understand that you want to use UTF-8.

If you really need to convert between charsets, this is the source of a iso8859-1 to utf-8 conversor and vice versa. It can be easily be changed to other encodings.

Selec All Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
import sys
 
def my_decode(s):
  raw = s.decode("iso8859-1")
  return raw.encode("utf-8");
try:
  txt = open(sys.argv[1])
  print my_decode(txt.read())
  txt.close();
except IndexError:
  print my_decode(sys.stdin.read())
  sys.stdin.close()

How hard is that?
I’am sure that this core runs on python 2.x. It may need some changes to work on python 3.0 like the use of the print function.

Updated Version on our GitRepository.

Tagged , ,

Hello Everybody

This is actually my first post in English. I am native from Brazil, and will try on this website show my achievements and accomplishments in academy life and real life. I really hope you all enjoy.

Sorry about my english. Ill do my best.

Selec All Code:
1
2
from __future__ import print_function
print("Hello World") # support for python 3.0
Tagged ,