Category Archive: ImageProcessing

Subcategories: No categories

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 , , ,