Examples 31-40

Example 31: Client to tcp Socket Server

This example uses the socket module to:

  • open a socket
  • send a string
  • wait for reply
  • close the socket
from socket import *

ip='localhost'
port=9901
csock=socket(AF_INET,SOCK_STREAM)
csock.settimeout(1.0)
csock.connect( (ip,port) )
csock.send('PartPresent')
reply = csock.recv(100)
csock.close()

Note

Example 23 shows a socket server implementation

Example 32: Read / Write External Data from / to file

This example demonstrate file access for an ExternalData tool

def WriteToFile():

  list=[]
  list.append(GetIntValue('Data.s1'))
  list.append(GetFloatValue('Data.s2'))
  list.append(GetStringValue('Data.t1'))
  list.append(GetBoolValue('Data.l1'))
  list.append(GetBoolValue('Data.l2'))
  list.append(GetFloatValue('Data.p1_x'))
  list.append(GetFloatValue('Data.p1_y'))
  print list
  f=open('storedtext.txt','w') #file stored in the Scorpion directory
  str0='%(list)s' %vars()
  f.write(str0) #overwite with the new text

  f.close()
def ReadFromFile():

  #The script can be put in Central Start
  #for automatic reading when Scorpion is started

  f=open('storedtext.txt','r') #file stored in the Scorpion directory
  l=f.readlines()
  print l
  a=eval(l[0]) #Make it readable as a Python list
  print a

  SetValue('Data.s1',a[0])
  SetValue('Data.s2',a[1])
  SetValue('Data.t1',a[2])
  SetValue('Data.l1',a[3])
  SetValue('Data.l2',a[4])
  SetValue('Data.p1_x',a[5])
  SetValue('Data.p1_y',a[6])

  f.close()

Example: content of file

[5, 9.0, 'Hello!!', False, True, 2.5, 1.5]

Example 33: Changing a tool’s ROI using ExecuteCmd

This example demonstrates how to move or change a tools’ ROI position/size from a script

Most tools are positioned in the image (the ROI) either as a rectangle with center/size/angle (e.g. LineFinder) or as a set of polygons (e.g. Blob3).

The ROI can be changed as shown below. One or more points are given;

  • one point means move ROI center,
  • several points means reshape ROI.

Example 1 - Move rectangle

LF=GetTool('LF') # rectangle tool, e.g. LineFinder
LF.executeCmd('set;object=roi;value=((200;200))') # moves the ROI center

Example 2 - Set rectangle

LF=GetTool('LF') # rectangle tool, e.g. LineFinder
LF.executeCmd('set;object=roi;value=((100;100)(200;100)(200;150)(100;150))')
#specify four corners of the ROI. The angle is calculated from the first two points

Example 3 - Move first polygon

B3=GetTool('B3') # polygon tool, e.g. Blob3
B3.executeCmd('set;object=roi;value=((200;200))')
# moves blob3 first polygon to new center (defined as center of gravity for polygon)

Example 4 - Set first polygon

B3=GetTool('B3') # polygon tool, e.g. Blob3
B3.executeCmd('set;object=roi;value=((100;100)(200;100)(100;200))')
# polygon defines ROI directly

Example 5 - Move another polygon

B3=GetTool('B3') # polygon tool, e.g. Blob3
B3.executeCmd('set;object=roi;number=2;value=((200;200))')
# moves blob3 second polygon to new center (defined as center of gravity for polygon)

Note

The object=roi command is defined pr tool

Example 34: Histogram Equalization

This example calculates the histogram from an Image and performs Histogram Equalization on the same image.

def HistEqualize(image,report=0):

  im  =GetImageMatr(image)
  rows,cols=im.dim()
  if report: print image,rows,cols

  hist=range(0,256)
  for i in range(0,256): hist[i]=0
  for i in range(0,rows*cols): hist[ im[i] ]+=1

  nump  = rows*cols
  alpha = 255.0/nump

  def printhist(hist):
     max=0
     for it in hist:
         if it>max:max=it
     for i in range(0,len(hist)):
        print '%03d %03d' % (i,hist[i]),'*' * int((hist[i]/(max*1.0)) * 100)

  if report:
    printhist(hist)
    print '='*30

  cumfreq   =range(0,256)
  cumfreq[0]=hist[0]
  cum       =hist[0]
  cumfreq[0]=cum
  for i in range(1,256):
    cum+=hist[i]
    cumfreq[i]=cum

  for i in range(0,rows*cols):
      v= int(cumfreq[im[i]]*alpha)
      if v>255:v=255
      im[i] = v
  if report:
     for i in range(0,256): hist[i]=0
     for i in range(0,rows*cols): hist[ im[i] ]+=1
     printhist(hist)

  SetImageMatr(image,im)

Note

Histogram Equalisation is also available from the STC-0035 ImageFilter

Example 35: Robust Adam 6060 scripts

This is an example on how you can make Adam 6060 modules handle disconnect without stopping

Note

In Scorpion Vision XI the SIO - Scorpion IO System provides functionality to avoid IO scripting

Central Start

class Globals:
  pass

globals=Globals() # globals used as property container

from adam6060 import * #Adam6060.py must be in the Python directory

try:
  globals.io=Adam6060('10.0.0.1')
except:
  print 'No connection'
  globals.IoOK=0
else:
  print 'Adam connected'
  globals.IoOK=1
  #Read Digital Input 0
  ok,txt,val=globals.io.ReadDI(0)
  globals.Cur=val
  #Reset all output relays
  #ResetOutputRelays()

Central Stop

io.close()

Central Methods

def IsTrigger():
  if globals.IoOK:
    try:
      ok,txt,val=globals.io.ReadDI(0)
      if ok==0:
        globals.IoOK=0
        print 'lost connection to Adam'
      else:
        RisingEdge=val-globals.Cur
        globals.Cur=val
        if RisingEdge==1:
          print 'trigger detected'
          ResetOutputRelays()
          ExecuteCmd('GrabExecute','')

    except:
      globals.IoOK=0
      print 'lost connection to Adam'

  if not globals.IoOK:
    ReconnectAdam(1)
def ReconnectAdam(a):
  try:
    globals.io=Adam6060('10.0.0.1')
    print 'try to connect'
  except:
    print ' No connection with Adam6060'
    globals.IoOK=0
  else:
    globals.IoOK=1
    print ' Adam reconnected ','IoOK=',globals.IoOK

  if globals.IoOK==1:
    if a == 0:
      ResetOutputRelays()
    if a == 1:
      IsTrigger()
    if a == 2:
      SetOutputRelays()
def ResetOutputRelays():
  if globals.IoOK:
    try:
      ok,txt,msg=globals.io.WriteRelay(0,0)
      ok,txt,msg=globals.io.WriteRelay(1,0)
      ok,txt,msg=globals.io.WriteRelay(2,0)
      ok,txt,msg=globals.io.WriteRelay(3,0)
      ok,txt,msg=globals.io.WriteRelay(4,0)
      ok,txt,msg=globals.io.WriteRelay(5,0)
      if ok==0:
        globals.IoOK=0
      else:
        print 'Reset relays, output =0 0 0 0 0 0'
    except:
      globals.IoOK=0

  if not globals.IoOK:
    ReconnectAdam(0)
def SetOutputRelays():
  a=int(GetValue('Pass1.Value'))
  b=int(GetValue('Fault1.Value'))
  c=int(GetValue('Pass2.Value'))
  d=int(GetValue('Fault2.Value'))
  e=int(GetValue('Pass3.Value'))
  f=int(GetValue('Fault3.Value'))
  if globals.IoOK:
    try:
      ok,txt,msg=globals.io.WriteRelay(0,a)
      ok,txt,msg=globals.io.WriteRelay(1,b)
      ok,txt,msg=globals.io.WriteRelay(2,c)
      ok,txt,msg=globals.io.WriteRelay(3,d)
      ok,txt,msg=globals.io.WriteRelay(4,e)
      ok,txt,msg=globals.io.WriteRelay(5,f)
      if ok==0:
        globals.IoOK=0
      else:
        print 'New relay output',a,b,c,d,e,f
    except:
      print ' cannot connect'
      globals.IoOK=0

  if not globals.IoOK:
    ReconnectAdam(2)

Example 36: Bubble Sorting

Bubble sort, sometimes shortened to bubblesort, also known as exchange sort, is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top (i.e. the beginning) of the list via the swaps. Because it only uses comparisons to operate on elements, it is a comparison sort. This is the easiest comparison sort to implement.

def bubblesort(l):
    "Sorts l in place and returns it."
    for passesLeft in range(len(l)-1, 0, -1):
        for index in range(passesLeft):
            if l[index] < l[index + 1]:
               l[index], l[index + 1] = l[index + 1], l[index]
    return l

More information: http://en.wikipedia.org/wiki/Bubble_sort

All text is available under the terms of the GNU Free Documentation License.

Example 37: Element Statistics

The python class is designed to calculate the Mean and the Standard Deviation of a collection of elements.

def ElementStatistics():
  import math

  class ElementStat:
    def __init__(self):
      self.Reset()

    def Add(self,x):
      print ' x ', x
      self.n = self.n +1
      delta = x - self.mean
      self.mean = self.mean + delta / self.n
      self.S = self.S + delta*(x - self.mean)

    def N(self):
      return self.n

    def Mean(self):
      return self.mean

    def Variance(self):
      return self.S / (self.n - 1)

    def Std(self):
      return math.sqrt(self.Variance())

    def Reset(self):
      self.n = 0
      self.mean = 0
      self.S = 0

  return ElementStat()

Example 1: Using Element Stat

obp = GetTool('obp')
mref = GetTool('mref')
img = GetImageMatr('1')
points = GetResultValue('polygons.Polygon[1]')
statX = ElementStatistics()
statY = ElementStatistics()
statZ = ElementStatistics()
for pos in points:
  mref.setConfigValue('OrigoX',pos[0],0)
  mref.setConfigValue('OrigoY',pos[1])
  mref.execute(img)
  obp.execute(img)
  x = obp.getFloatValue('Position_x')
  y = obp.getFloatValue('Position_y')
  z = obp.getFloatValue('Position_z')
  dev = obp.getFloatValue('Deviation')
  if 0.0 < dev < 1.0 :
    statX.Add(x)
    statY.Add(y)
    statZ.Add(z)
DrawMarker3D('1-3DRef',statX.Mean(),statY.Mean(),statZ.Mean(),'Red',6)
DrawText3D('1-3DRef',statX.Mean(),statY.Mean(),statZ.Mean(),
  ' %.0f,%.0f,%.0f' % (statZ.Mean(),statZ.Std(),statZ.N()), 'Red',16,'Arial')

More information: http://en.wikipedia.org/wiki/Standard_deviation

Example 38: Saving Scorpion 3D Image

The example show how to store a 3D Image to a comma separated format.

def SavePointCloud(ImageName, Filename):
  img=GetImageMatr(ImageName)
  f=open(Filename,'w')
  if img<>None:
    if   img.elemtype()=='XYZf'  : fmt='%f,%f,%f\n'       #3 element pr. point
    elif img.elemtype()=='XYZWVf': fmt='%f,%f,%f,%f,%f\n' #5 element pr. point

    if img.isvec() and img.elemtype()=='XYZWVf':
      cnt=img.dim()[0]
      for i in range(cnt):
        f.write(fmt % img[i])
    elif img.ismat() and img.elemtype()=='XYZWVf':
      rows,cols = img.dim()
      for r in range(rows):
        offs=r*cols
        for c in range(cols):
          f.write(fmt % (img[offs+c]))
      f.close()
  f.close()

Example 1: Save 3D Point Cloud with 5 elements

SavePointCloud('3D','image.csv')

Example 39 - Disabling Zoom in Image Windows

The example shows how to disable zoom in an image windows.

def Handle_System_MouseDown(Image,Shift,X,Y):
  #
  # Image = VT_BSTR
  # Shift = VI_I4
  # X = VT_R4
  # Y = VT_R4
  #
  # Return 1 if handled by script
  # Return 0 if default handling
  #
  return 1

Example 40 - Filtering timeseries

This example contains two use filters for arrays:

def MedianFilter(x,n):
  # median filter of array x, length n
  # filter behaves pretty well at the edges (shortens the length as needed)
  def med(x):
    x.sort()
    return x[len(x)/2]
  # force odd filter order (better filters then)
  if n%2==0:
    n += 1
  nh = n/2
  l = len(x)
  p = list(x)
  for i in range(nh):
    v = x[0:n-nh+i]
    p[i] = med(v)
  for i in range(nh,l-nh):
    v = x[i-nh:i-nh+n]
    p[i] = med(v)
  for i in range(l-nh,l):
    v = x[i-nh:l]
    p[i] = med(v)
  return p
def LowpassFilter(p,N,C):
  # N-tap running average, run C times
  l = len(p)
  if (N%2): N += 1 # N odd: zero phase
  NH = N / 2
  r = list(p)
  for c in range(C):
    lpad = [r[0] for i in range(NH)]
    rpad = [r[l-1] for i in range(NH)]
    rr = lpad + r + rpad
    r = [sum(rr[i:i+N])/N for i in range(l)]
  return r