1/28/2014

(OpenCV Study) -1.#IND, check by cvIsNaN

-1.#IND is generated when sqrt(-1),
IND is abstract of "indeterminate"

To check this value, we can use cvIsNaN function
The function check the input value is indeterminate value or not.
If value is indeterminate value, the function return 1


show the example code

printf ("cvIsNaN (0.0) : %d\n",cvIsNaN (0.0));
printf ("cvIsNaN (1.0/0.0) : %d\n",cvIsNaN (1.0/0.0));
printf ("cvIsNaN (-1.0/0.0) : %d\n",cvIsNaN (-1.0/0.0));
printf ("cvIsNaN (sqrt(-1.0)): %d\n",cvIsNaN (sqrt(-1.0)));

output is
cvIsNaN (0.0)      : 0
cvIsNaN (1.0/0.0)  : 0
cvIsNaN (-1.0/0.0) : 0
cvIsNaN (sqrt(-1.0): 1


1/27/2014

(Python Study) about class (example source code)

__author__ = 'mare'



class MyClass:
 """ very simple class """
 pass

class Person:
 Name = "Default Name"
 def Print(self):
  print("My name is {0}".format( self.Name ))


p1 = Person()
p1.Print()
p1.Name = "yuna"
p1.Print()
#My name is Default Name
#My name is yuna


#class object and instance object namespace
class Person:
 name = "default name"

p1 = Person();
p2 = Person();

print("p1's name: ", p1.name)
print("p2's name: ", p2.name)
#p1's name:  default name
#p2's name:  default name

p1.name = "yuna kim"
print("p1's name: ", p1.name)
print("p2's name: ", p2.name)
#p1's name:  yuna kim
#p2's name:  default name

#new member create
Person.title = "new title"
print("p1's title: ", p1.title)
print("p2's title: ", p2.title)
#p1's title:  new title
# p2's title:  new title

print("Person's title: ", Person.title)
#Person's title:  new title

p1.age = 20
print("p1's age", p1.age)
#p1's age 20
#print("p2's age", p2.age)
#error!!!
#AttributeError: 'Person' object has no attribute 'age'


#notice self keyword
str = "Not class member"
class GString:
 str = ""
 def set(self, msg):
  self.str = msg
 def Print(self):
  print(str)

g = GString()
g.set("First Message")
g.Print()
#Not class member

#exception keyword, __class__

class Test:
 data = "Default"

i2 = Test();
i1 = Test();

i1.__class__.data = "all data will be changed"

print(i1.data)
print(i2.data)
#all data will be changed
#all data will be changed

i2.data = "only i2's data is changed"

print(i1.data)
print(i2.data)
#all data will be changed
#only i2's data is changed


#relationship class object and instance object

class Person:
 pass
class Bird:
 pass
class Student:
 pass

p, s = Person(), Student()
print( isinstance(p, Person) )
#True
print( isinstance(s, Person) )
print( isinstance(p, object) )
print( isinstance(p, Bird) )
print( isinstance(int, object) )
#False
#True
#False
#True

#creator and deleter
class MyClass:
 def __init__(self, value):
  self.Value = value
  print("Class is created! value = ", value)

 def __del__(self):
  print("Class is deleted")

def foo():
 d = MyClass(10)

foo()
#Class is created! value =  10
#Class is deleted



#static method, class method
class CounterManager:
 insCount = 0

 def __init__(self):
  CounterManager.insCount += 1

 def printInstanceCount():
  print("Instance Count: ", CounterManager.insCount)


a, b, c = CounterManager(), CounterManager(), CounterManager()

CounterManager.printInstanceCount()
#Instance Count:  3
#b.printInstanceCount()
#error

# rewrite rightly
print("---")
class CounterManager:
 insCount = 0

 def __init__(self):
  CounterManager.insCount += 1

 def staticPrintCount():
  print("Instance Count: ", CounterManager.insCount)

 SPrintCount = staticmethod(staticPrintCount)

 def classPrintCount(cls):
  print("Instance Count: ", cls.insCount)

 CPrintCount = classmethod(classPrintCount)

a, b, c = CounterManager(), CounterManager(), CounterManager()

CounterManager.SPrintCount()
b.SPrintCount()
CounterManager.CPrintCount()
b.CPrintCount()
#Instance Count:  3
#Instance Count:  3
#Instance Count:  3
#Instance Count:  3

#operator re define

class GString:

 def __init__(self, init=None):
  self.content = init

 def __add__(self, str):
  self.content += str;

 def __sub__(self, str):
  for i in str:
   self.content = self.content.replace(i, '')
  return GString(self.content)

 def __abs__(self):
  return GString( self.content.upper() )

 def Remove(self, str):
  return self.__sub__(str)

g = GString("abcdefgABCD")
print(g.content)
#abcdefgABCD

g+"Apple_"

print(g.content)
#abcdefgABCDApple_

g -= "ade"
print(g.content)
#bcfgABCDAppl_
g -= "QQQ"
print(g.content)
#bcfgABCDAppl_

g = abs(g)
print(g.content)
#BCFGABCDAPPL_


#sequence operator redefine

class Sequencer:
 def __init__(self, maxValue):
  self.maxValue = maxValue

 def __len__(self):
  return self.maxValue

 def __getitem__(self, index):
  if( 0 < index <= self.maxValue ):
   return index * 10
  else:
   raise IndexError("Index out of range")

 def __contains__(self, item):
  return (0 < item <= self.maxValue)

s = Sequencer(5)

print( s[1] )
print( s[3] )
print( [s[i] for i in range(1,6) ] )
#10
#30
#[10, 20, 30, 40, 50]

print( len(s) )
print( 3 in s )
print( 7 in s )
#5
#True
#False


#inheritance
class Person:
 " parent class "

 def __init__(self, name, phoneNumber):
  self.Name = name
  self.PhoneNumber = phoneNumber

 def PrintInfo(self):
  print("Info(Name:{0}, Phone Number: {1}".format(self.Name, self.PhoneNumber))

 def PrintPersonData(self):
  print("Person(Name:{0}, Phone Number:{1})".format(self.Name, self.PhoneNumber))

class Student(Person):
 "child class"

 def __init__(self, name, PhoneNumber, subject, studentID):
  self.Name = name
  self.PhoneNumber = PhoneNumber

  """ #call creator in parent class
  Person.__init__(self, name, phoneNumber)
  """

  self.Subject = subject
  self.StudentID = studentID

 #method addition
 def PrintStudentData(self):
  print("Student(subject: {0}, Student ID: {1})".format(self.Subject, self.StudentID))



p = Person("Derick", "010-123-4556")
s = Student("Marry", "010-123-2222", "Computer science", "990999")

print( p.__dict__ )
#{'Name': 'Derick', 'PhoneNumber': '010-123-4556'}

print( s.__dict__ )
#{'Subject': 'Computer science', 'Name': 'Marry', 'PhoneNumber': '010-123-2222', 'StudentID': '990999'}

print( issubclass(Student, Person) )
print( issubclass(Person, Student) )
print( issubclass(Person, Person) )
print( issubclass(Person, object))
print( issubclass(Student, object))
#True
#False
#True
#True
#True

print( s.PrintStudentData() )
#Student(subject: Computer science, Student ID: 990999)

print( dir(s) )


#Method overriding
class Student2(Person):
 "child class"

 def __init__(self, name, PhoneNumber, subject, studentID):
  self.Name = name
  self.PhoneNumber = PhoneNumber
  self.Subject = subject
  self.StudentID = studentID

 #method addition
 def PrintStudentData(self):
  print("Student(subject: {0}, Student ID: {1})".format(self.Subject, self.StudentID))

 def PrintInfo(self):
  print("Info(Name:{0}, Phone Number: {1}".format(self.Name, self.PhoneNumber))
  print("Student(subject: {0}, Student ID: {1})".format(self.Subject, self.StudentID))

s = Student2("Marry", "010-123-2222", "Computer science", "990999")
print( s.PrintInfo() )
#Info(Name:Marry, Phone Number: 010-123-2222
#Student(subject: Computer science, Student ID: 990999)


#method extension
class Student3(Person):
 "child class"

 def __init__(self, name, PhoneNumber, subject, studentID):
  self.Name = name
  self.PhoneNumber = PhoneNumber
  self.Subject = subject
  self.StudentID = studentID

 #method addition
 def PrintStudentData(self):
  print("Student(subject: {0}, Student ID: {1})".format(self.Subject, self.StudentID))

 def PrintInfo(self):
  Person.PrintInfo(self)
  print("Student(subject: {0}, Student ID: {1})".format(self.Subject, self.StudentID))

s = Student3("Marry", "010-123-2222", "Computer science", "990999")
print( s.PrintInfo() )
#Info(Name:Marry, Phone Number: 010-123-2222
#Student(subject: Computer science, Student ID: 990999)

#calss inheritance space and namespace
class SuperClass:
 x=10
 def printX(self):
  print(self.x)

class SubClass(SuperClass):
 y=20
 def printY(self):
  print(self.y)


s = SubClass()
s.a = 30

print( s.__dict__ )
#{'a': 30}
print( s.y )
print( s.x )
#20
#10


class SuperClass:
 x=10
 def printX(self):
  print(self.x)

class SubClass(SuperClass):
 y=20
 def printY(self):
  print(self.y)

 def printX(self):
  print("subClass:", self.x)

s = SubClass()

s.a = 30
s.x = 50

print("SuperClass: ", SuperClass.__dict__ )
print("SubClass: ", SubClass.__dict__ )
print("S: ", s.__dict__ )

"""
SuperClass:  {'__weakref__': , '__module__': '__main__', '__doc__': None, 'x': 10, '__dict__': , 'printX': }
SubClass:  {'__module__': '__main__', 'y': 20, '__doc__': None, 'printY': , 'printX': }
S:  {'a': 30, 'x': 50}
"""

#multi inheriance

class Tiger:
 def Jump(self):
  print(" jump far like tiger")

class Lion:
 def Bite(self):
  print("bite like lion")
 def Cry(self):
  print("zzzz")

class Liger(Tiger, Lion):
 def Play(self):
  print("play with liger")

l = Liger()
l.Jump()
l.Bite()
l.Play()
#jump far like tiger
#bite like lion
#play with liger

l.Cry()
#zzzz

class Animal:
 def __init__(self):
  print("Animal __init()")


class Tiger(Animal):

 def __init__(self):
  Animal.__init__(self)
  print("Tiger __init()")


class Lion(Animal):
 def __init__(self):
  Animal.__init__(self)
  print("Lion __init()")

class Liger(Tiger, Lion):

 def __init__(self):
  Tiger.__init__(self)
  Lion.__init__(self)
  print("liger __init()")


l = Liger()
#Animal __init()
#Tiger __init()
#Animal __init()
#Lion __init()
#liger __init()


# rewrite by super init
class Animal2:
 def __init__():
  print("Animal __init()")


class Tiger2(Animal):

 def __init__(self):
  super().__init__()
  print("Tiger __init()")


class Lion2(Animal):
 def __init__(self):
  super().__init__()
  print("Lion __init()")


class Liger2(Tiger2, Lion2):

 def __init__(self):
  super().__init__()
  print("liger __init()")

print("---")
l = Liger2()
#Animal __init()
#Lion __init()
#Tiger __init()
#liger __init()




1/23/2014

(python study) about function (example source code)

__author__ = 'mare'


def Times(a, b):
 return a*b

print(Times)
#

print( Times(10, 10) )
#100

myTimes = Times;
r = myTimes(10, 10);
print( r )
#100

#return

def setValue(newValue):
 x = newValue

retval = setValue(10)
print( retval )
#None

def swap(x, y):
 return y, x
swap(1,2)
#(2,1)

a, b = swap(1,2)
#a = 2, b = 1

x = swap(1,2)
print( type(x) )
#


#more complex function
def intersect(prelist, postlist):
 retlist = []
 for x in prelist:
  if x in postlist and x not in retlist:
   retlist.append(x)
 return retlist

list1 = "SPAM"
list2 = "AM"

list3 = intersect(list1, list2)

print(list3)
#['A', 'M']


#parameters
a=10
b=20

def sum1(x,y):
 return x+y

print( sum1(a,b) )
#30

x = 10
def sum2(x,y):
 x = 1
 return x+y

print( sum2(x, b), x )
#21 10

def change(x):
 x[0] = 'H'

wordlist = ['J', 'A', 'M' ]
change(wordlist)
print(wordlist)
#['H', 'A', 'M']



def change(x):
 x = x[:]
 x[0] = 'H'
 return None

wordlist[0] = 'J'

change(wordlist)
print(wordlist)
#['J', 'A', 'M']


#scoping rule
x=1
def func2(a):
 x=2
 return a+x
print( func2(10) )
#12

def func3(a):
 global x
 x = 20
 return x+a

print( func3(10 ), x)
#30 20

dir( __builtins__ )
#you can see inner function names

#arguments
def Times(a=10, b=20):
 return a+b

print( Times() )
#30

print( Times(5) )
#25

#keyword arguments
def connectURI( server, port):
 str = "http://" + server +  ":" + port
 return str

print( connectURI("test.com", "800" ))
print( connectURI(port="8080", server="test.com"))
#http://test.com:800
#http://test.com:8080


#variable argument
def test(*args):
 print( type(args) )

test(1,2)
#


def union2(*ar):
 res = []
 for item in ar:
  for x in item:
   if not x in res:
    res.append(x)
 return res

print( union2( "HAM", "EGG", "SPAM" ) )
print( union2("GIR", "Generation", "gee") )
#['H', 'A', 'M', 'E', 'G', 'S', 'P']
#['G', 'I', 'R', 'e', 'n', 'r', 'a', 't', 'i', 'o', 'g']

def userURIBuilder(server, port, **user):
 str = "Http://" + server + ":" + port + "/?"
 for key in user.keys():
  str += key + "=" + user[key] + "&"
 return str

s = userURIBuilder("Test.com", "8080", id='userid', passwd='1234')
print(s)
#Http://Test.com:8080/?id=userid&passwd=1234&

#lambda function

g = lambda x, y : x*y
g(2,3)
#6

(lambda x: x*x)(3)
#9

#recursive function call
def factorial(x):
 if x == 1:
  return 1
 return x*factorial(x-1)

factorial(10)
#3628800

#pass
#while True:
# pass #control + c if you stop

class temp:
 pass


#help
def factorial(x):
 "return factorial of n, ...."
 if x == 1:
  return 1
 return x*factorial(x-1)

#help( factorial)
#return factorial of n, ....

#iterator
"""
for element in [1, 2, 3]:
for element in (1, 2, 3):
for key in {'one':1, 'two':2}:
for char in "123":
for line in open("myfile.txt") read line by line in the file
"""

#generator
def reverse(data):
 for index in range(len(data) -1, -1, -1):
  yield data[index]

for char in reverse('golf'):
 print( char)
#f
#l
#o
#g


#enumerate
for i, season in enumerate(['spring', 'summer', 'fall', 'winter']):
 print(i, season)
#0 spring
#1 summer
#2 fall
#3 winter

#iter
s='abc'
it = iter(s)
print(next(it))
#a
print(next(it))
#b
print(next(it))
#c
#print(next(it)) -> error




















1/22/2014

(Python study) deep copy and shallow copy (example source code)

#this is Shallow copy
a=[1, 2, 3]
b=a
a[0] = 38
print(a, b)
print(id(a), id(b))
#[38, 2, 3] [38, 2, 3]
#4320547040 4320547040

#this is deep copy
b = a[:]
print(id(a), id(b))
#4320427976 4320427472

a[0] = 50;
print(a, b)
#[50, 2, 3] [38, 2, 3]

import copy

a=[1,2,3]
b = copy.deepcopy(a)
a[0] = 38
print(a, b)
[38, 2, 3] [1, 2, 3]



(Python study) boolean (example)

>>> isRight = False         
>>> type(isRight)       
< type 'bool'>
>>> 1<2            
True
>>> 1 != 2         
True
>>> 1 == 2         
False
>>> True and False 
False
>>> True & True    
True
>>> False | False
False
>>> not True
False
>>> 
>>> bool(0)
False
>>> bool(-1)
True
>>> bool('test')
True
>>> bool(None)
False
>>>     

(python study) about dictionary variable (example source code)

__author__ = 'mare'

d = dict(a=1, b=3, c=5)
#{'a': 1, 'c': 5, 'b': 3}
type(d)
#< type 'dict'>

color = {"apple":"red", "banana":"yellow"}
#{'apple': 'red', 'banana': 'yellow'}

print( color["apple"] )
#red

#color[0] is not support, error

#color += {"cherry":"red"} -> error
color["cherry"] = "red"
#{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
color["apple"] = "green"
#{'cherry': 'red', 'apple': 'green', 'banana': 'yellow'}

#items(), keys(), values()

for c in color.items():
 print(c)
#('apple', 'green')
#('cherry', 'red')
#('banana', 'yellow')

print('--')

for k, v in color.items():
 print(k, v)
#apple green
#cherry red
#banana yellow

print('--')

for k in color.keys():
 print(k)
#apple
#cherry
#banana

print('--')

for v in color.values():
 print(v)
#green
#red
#yellow

del color['cherry']
print(color)

color.clear()
#{'apple': 'green', 'banana': 'yellow'}

print(color)
#{}

#more complex
s = {'age':40.5, 'job':[1, 2, 3], 'name':{'kim':2, 'Cho':1}}
print(s)
#{'name': {'Cho': 1, 'kim': 2}, 'age': 40.5, 'job': [1, 2, 3]}







(Python Study) list, set, tuple type casting

#can change freely
a = set((1,2,3))
b = list(a)
c = tuple(b)
d = set(c)


>>> a
set([1, 2, 3])
>>> b
[1, 2, 3]
>>> d
set([1, 2, 3])
>>> c
(1, 2, 3)
>>> 

(python study) about tuple variable (example source code)

#tuple is similar with list but notation is () and read only
#but access speed is faster than list

t = (1, 2, 3)
print( type(t) )
#< class 'tuple'>

a, b = 1, 2
(a, b) = (1, 2)
print(a, b)
#1 2


(Python study) about set variable (example source code)

a = {1, 2, 3}
print(a)

b = {3, 4, 5}

print( a.union(b) )
#{1, 2, 3, 4, 5}

print( a.intersection(b) )
#{3}

print( a-b )
print( a|b )
print( a&b )
#{1, 2}
#{1, 2, 3, 4, 5}
#{3}




(Python Study) about list variable (example source code)

##list
color = ['red', 'green', 'gold']
print(color)
#['red', 'green', 'gold']

color.append('blue')
print(color)
#['red', 'green', 'gold', 'blue']

color.insert(1, 'black')
print(color)
#['red', 'black', 'green', 'gold', 'blue']

color.extend(['white', 'gray'])
print(color)
#['red', 'black', 'green', 'gold', 'blue', 'white', 'gray']

color += ['red']
print(color)
#['red', 'black', 'green', 'gold', 'blue', 'white', 'gray', 'red']

print( color.index('red') )
print( color.index('red', 1 ) ) #1 is search start position
#0
#7

print( color.count('red') )
#2

color.pop()
color.pop()
color.pop(1)

print( color )
#['red', 'green', 'gold', 'blue', 'white']


color.remove('gold')
print( color )
#['red', 'green', 'blue', 'white']

color += 'red'
print( color )
#['red', 'green', 'blue', 'white', 'r', 'e', 'd']
color += ['red']
print( color )
#['red', 'green', 'blue', 'white', 'r', 'e', 'd', 'red']

color.remove('red')
print( color )
#['green', 'blue', 'white', 'r', 'e', 'd', 'red']

color.sort()
color.reverse()
print(color)
#['white', 'red', 'r', 'green', 'e', 'd', 'blue']

print( color[-1] )
#blue

def mysort(x):
 return x[-1]

color.sort(key=mysort)
print(color)
#['red', 'd', 'white', 'e', 'blue', 'green', 'r']



(Python Study) about variables (examples source code)


print( oct(38) ) #octal
print( hex(38) ) #hex
print( bin(38) ) #binary

#0o46
#0x26
#0b100110


print( type( oct(38) ) )
#

x= 3 - 4j
print( type(x) )
#

print( x.imag )
print( x.real )
print( x.conjugate() )
#-4.0
#3.0
#(3+4j)

x = 5/2
y = 5//2

print(x, y)
#2.5 2

##string##

print(""" aa
dd dd ff
dd dd s""")
# aa
#dd dd ff
#dd dd s

print(''' aa
dd dd ff
dd dd s''')
# aa
#dd dd ff
#dd dd s

print('py' 'thon')
#python
print("py" "thon")
#python
print('py' + 'thon')
#python

print('py'*3)
#pypypy

a="python"
print( a[0], a[5])
#p n

# a[5] = 'a' is error, cannot copy

print( a[0:1] )
print( a[1:4] )
print( a[:2] )
print( a[-2:] )
#p
#yth
#py
#on

print( a[:] )
print( a[::2] )
#python
#pto

##casting
print( str(3.14) )
print( int("49") )
print( float(23) )
#'3.14'
#49
#23.0



(Arduino Study) the method to make library

Original source code is like that

---
//sos_without_lib.pde
void dot();
void dash();

int pin = 13;

void setup()
{
  pinMode(pin, OUTPUT);
}

void loop()
{
  dot(); dot(); dot();
  dash(); dash(); dash();
  dot(); dot(); dot();
  delay(3000);
}

void dot()
{
  digitalWrite(pin, HIGH);
  delay(250);
  digitalWrite(pin, LOW);
  delay(250);
}

void dash()
{
  digitalWrite(pin, HIGH);
  delay(1000);
  digitalWrite(pin, LOW);
  delay(250);
}

...


To make library, we have to do 4 steps process,

step 1, write .h , .cpp files,   it is same c++ class, and copy into libraries\morse folder.
step 2, make keywords.txt,  and copy into libraries\morse folder.
step 3, make SOS.pde and copy libraries\morse\Examples\SOS
step 4, programing using the library

.h, .cpp

...
.h ->
#ifdef Morse_H
#define Morse_H

#include "WProgram.h"

class Morse{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;

#endif

.cpp ->
#include "WProgram.h"
#include "morse.h"

Morse::Morse(int pin)
{
  pinMode(pin, OUTPUT);
  _pin = pin)
}

void Morse::dot()
{
  digitalWrite(pin, HIGH);
  delay(250);
  digitalWrite(pin, LOW);
  delay(250);
}

void Morse::dash()
{
  digitalWrite(pin, HIGH);
  delay(1000);
  digitalWrite(pin, LOW);
  delay(250);
}
---



...
//SOS.pde
#include < Morse.h>

Morse morse(13);
void setup(){}

void loop(){
     morse.dot();morse.dot();morse.dot();
     morse.dash();morse.dash();morse.dash();
     morse.dot();morse.dot();morse.dot();
     delay(3000);
}

---


so the directory is like that

\arduino-0022\libraries\Morse\keyword.txt,  Morse.cpp, Morse.h
\arduino-0022\libraries\Morse\Examples\SOS\SOS.pde


1/21/2014

(OpenCV Study) Color Mat convert to gray Mat, cvtColor function example

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

and

cv::cvtColor(greyMat, colorMat, CV_GRAY2BGR);


(python study) for a loop (example source)


print('-- for example')

l = ['Apple', 100, 15.23]
for i in l:
 print(i, type(i))


print('-- dictionary')

d = {"Apple":100, "Orange":200, "Banana":300}
for k, v in d.items(): #print dictionary
 print(k, v)


print('-- iterator')

l = [10, 20, 30]
iterator = iter(l)
for i in iterator:
 print(i)


print('-- 9*9 ')

for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
 print("-- {0} step --".format(n))
 for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
  print("{0} * {1} = {2}".format(n, i, n*i))


print('-- break, continue and else example')

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in l:
 if i > 5:
  break
 print("Item:{0}".format(i))


for i in l:
 if i % 2 == 0:
  continue
 print("Item: {0}".format(i))


for i in l:
 if i > 5:
  break
 print("Item:{0}".format(i))
else:
 print("Exit without break")
print("Always this is printed")


print("-- useful function")

list( range(10) )
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list( range(5,10) )
#[5, 6, 7, 8, 9]
list( range(10, 0, -1))
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list( range(10, 20 , 2))
#[10, 12, 14, 16, 18]

for i in range(10, 20, 2):
 print(i)



print("-- to get index and value concurrently")

l = ['Apple', 'orange', 'Banana']
for i in range(len(l)):
 print("index:{0}, value:{1}".format(i, l[i]))


print("-- enumerate example")
l = ["Apple", 100, 15.5]
for i in enumerate(l):
 print(i)

for i in enumerate(l, 300):
 print(i)


#list comprehensions
l = [1, 2, 3, 4, 5]
print( [i ** 2 for i in l] )
#[1, 4, 9, 16, 25]

t = ("apple", "banana", "orange")
print( [len(i) for i in t] )
#[5, 6, 6]

d = {100:"apple", 200:"banana", 300:"orange"}
print( [v.upper() for v in d.values() ] )

print( [i ** 3 for i in range(5)] )
#[0, 1, 8, 27, 64]

print( [i for i in t if len(i) > 5 ] )
#['banana', 'orange']

l1 = [3, 4, 5]
l2 = [1.5, -0.5, 4]
print( [x*y for x in l1 for y in l2 ] )
#[4.5, -1.5, 12, 6.0, -2.0, 16, 7.5, -2.5, 20]


print("-- filter example")
l=[10, 25, 30]
IterL = filter(None, l)
for i in IterL:
 print("Item: {0}".format(i))

def GetBiggerThan20(i):
 return i > 20

print("---")

IterL = filter(GetBiggerThan20, l)
for i in IterL:
 print("Item: {0}".format(i))

print("using lambda")
IterL = filter(lambda i: i>20, l)
for i in IterL:
 print("Item: {0}".format(i) )

print("-- zip")

X = [10, 20, 30]
Y = ['A', 'B', 'C']
for i in zip(X, Y):
 print("Item: {0}".format(i))

RetList = list(zip(X,Y))
[(10, 'A'), (20, 'B'), (30, 'C')]
#unzip
X2, Y2 = zip(*RetList)

X = [10, 20, 30]
Y = "ABC"
Z = (1.5, 2.5, 3.5)
RetList = list(zip(X, Y, Z))

print("another example for zip")

X = [10, 20, 30]
Y = "ABCD"
RetList = list(zip(X, Y))
#[(10, 'A'), (20, 'B'), (30, 'C')]

print("-- map function example")

L = [1, 2, 3]

def Add10(i):
 return i+10

for i in map(Add10, L):
 print("Item: {0}".format(i) )

RetList = list( map((lambda i: i+10), L))
print(RetList)

X = [1, 2, 3]
Y = [2, 3, 4]
RetList = list(map(pow, X, Y))
print(RetList)

print("--join function example")

l = ['Apple', 'Orange', 'Banana']
for i in l:
 print(i)

#--> join form
print("\n".join(l))


print("-- processing time compare with noraml print and joint")

import time

l = range(1000)

t = time.mktime(time.localtime())
for i in l:
 print(i, )
t1 = time.mktime(time.localtime()) - t

t = time.mktime(time.localtime())
print(",".join(str(i) for i in l))
t2 = time.mktime(time.localtime()) - t

print("for -> Take {0} seconds".format(t1))
print("join -> Take {0} seconds".format(t2))

#result is 0.0 second both.. -.-














1/16/2014

(Python study) Check Python version on the Mac

On the terminal, input 'python -V', then version will be showed.
In the mac, python is already installed.







1/15/2014

(OpenCV Stitching) matchesGraphAsString function

"matchesGraphAsString " is useful function to see the stitching relationship graph.

The function gives the result as to string.

 
 
As figure, we can know m6-m7-m8-m9 is linked and S1, S6 is not correlation with the group.
You have to get pairwise_matches before using the function.
The matching method is introduced on
cpu version -> http://feelmare.blogspot.kr/2013/12/finding-largest-subset-images-that-is.html
gpu version-> http://feelmare.blogspot.kr/search?updated-max=2014-01-14T00:52:00-08:00&max-results=2&start=2&by-date=false


After get pairwise_matches, you can get the result of stitching grouping as this example source code.

...
float conf_thresh=1.0;
 vector< cv::String > img_names;
 img_names.push_back( "m7.jpg");   
 img_names.push_back( "S1.jpg");   
 img_names.push_back( "m9.jpg");   
 img_names.push_back( "m6.jpg");   
 img_names.push_back( "S6.jpg");   
 img_names.push_back( "m8.jpg"); 
 ofstream f("graph.txt");
 f << detail::matchesGraphAsString(img_names, pairwise_matches, conf_thresh);
---

(Visual Studio) Where is command agument input window in Visual Studio?


That is here
Configuration Properties ->
Debugging ->
The command argument


(Math) Mathematical symbol, let's remember~ 0≦t< 1 --> t∈[0,1)



0 ≦ t < 1

-> t ∈ [0,1)

don't forget~!!

1/14/2014

(Arduino Study) Led on/off using piezo speaker knock.




source code


...
const int ledPin = 13;
const int knockSensor = A0;
const int threshold = 100;

int sensorReading = 0;
int ledState = LOW;

void setup(){
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  
}

void loop(){
  sensorReading = analogRead(knockSensor);
  Serial.println(sensorReading);
  
  if(sensorReading >= threshold)
  {
    ledState = !ledState;
    digitalWrite(ledPin, ledState);
    Serial.println("Knock!");
  }
  
  delay(100);
}
---

(OpenCV, MatchesInfo) MatchesInfo includes correlation information between matched images.

After using BestOf2NearestMatcher function,
We can see correlation value between matched images.

MatchesInfo has follow element.

struct CV_EXPORTS MatchesInfo

 {

 MatchesInfo();

 MatchesInfo(const MatchesInfo &other);

    const MatchesInfo& operator =(const MatchesInfo &other);

    int src_img_idx, dst_img_idx;       // Images indices (optional)

    std::vector matches;
     std::vector inliers_mask;    // Geometrically consistent matches mask
     int num_inliers;                    // Number of geometrically consistent matches
     Mat H;                              // Estimated homography
     double confidence;                  // Confidence two images are from the same panorama
  };


http://feelmare.blogspot.kr/2013/12/finding-largest-subset-images-that-is.html-> you can see find feature and matching example source.

we can see correlation value from below source code.
...
printf("pairwise_matches %d \n", pairwise_matches.size() );
 for(int i=0; i < pairwise_matches.size(); ++i)
 {
  printf("%d \n", i );
  printf("%d -> %d \n", pairwise_matches[i].src_img_idx, pairwise_matches[i].dst_img_idx );
  printf("num inliers = %d\n", pairwise_matches[i].num_inliers);
  cout << "H " << pairwise_matches[i].H << endl;
  printf("confidence = %lf \n", pairwise_matches[i].confidence );
  printf("---\n");
 }

---

In here, confidence value is calculate by

...
// These coeffs are from paper M. Brown and D. Lowe. "Automatic Panoramic Image Stitching
    // using Invariant Features"
    matches_info.confidence = matches_info.num_inliers / (8 + 0.3 * matches_info.matches.size());

    // Set zero confidence to remove matches between too close images, as they don't provide
    // additional information anyway. The threshold was set experimentally.
    matches_info.confidence = matches_info.confidence > 3. ? 0. : matches_info.confidence;
---

If cofidenc value is lower than 1, we think the images are not relative image(no overlap image).

1/13/2014

(OpenCV GPU) Finding largest subset images that is only adjacent(subsequnce) images, (OpenCV, SurfFeaturesFinder, BestOf2NearestMatcher, leaveBiggestComponent funcions example souce code)


This is GPU version of this page ->http://feelmare.blogspot.kr/2013/12/finding-largest-subset-images-that-is.html
Please refer detail description on that page.

The gpu mode is showed  about 10 times faster than gpu processing.



I think GPU programing is very ensential in computer vision, if you don't have contraint on the performance of equipment.

...
#include < stdio.h >     
#include < opencv2\opencv.hpp >     
#include < opencv2\features2d\features2d.hpp >   
#include < opencv2\nonfree\features2d.hpp >   
#include < opencv2\stitching\detail\matchers.hpp >   
#include < opencv2\stitching\stitcher.hpp >   


#ifdef _DEBUG     
#pragma comment(lib, "opencv_core247d.lib")      
//#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing     
//#pragma comment(lib, "opencv_objdetect247d.lib")      
#pragma comment(lib, "opencv_gpu247d.lib")     
#pragma comment(lib, "opencv_features2d247d.lib")     
#pragma comment(lib, "opencv_highgui247d.lib")     
//#pragma comment(lib, "opencv_ml247d.lib")   
#pragma comment(lib, "opencv_stitching247d.lib");   
#pragma comment(lib, "opencv_nonfree247d.lib");   

#else     
#pragma comment(lib, "opencv_core247.lib")     
//#pragma comment(lib, "opencv_imgproc247.lib")     
//#pragma comment(lib, "opencv_objdetect247.lib")     
#pragma comment(lib, "opencv_gpu247.lib")     
#pragma comment(lib, "opencv_features2d247.lib")     
#pragma comment(lib, "opencv_highgui247.lib")     
//#pragma comment(lib, "opencv_ml247.lib")     
#pragma comment(lib, "opencv_stitching247.lib");   
#pragma comment(lib, "opencv_nonfree247.lib");   
#endif     

using namespace cv;     
using namespace std;   


void main()     
{   

 //processign tiem measurement   
 unsigned long AAtime=0, BBtime=0;   
 //processing time measure   
 AAtime = getTickCount();

 vector< Mat > vImg;   
 Mat rImg;

 vImg.push_back( imread("./stitching_img/m7.jpg",0) );   
 vImg.push_back( imread("./stitching_img/S1.jpg",0) );   
 vImg.push_back( imread("./stitching_img/m9.jpg",0) );   
 vImg.push_back( imread("./stitching_img/m6.jpg",0) );   
 vImg.push_back( imread("./stitching_img/S6.jpg",0) );   
 vImg.push_back( imread("./stitching_img/m8.jpg",0) );   


 //feature extract   
 gpu::SURF_GPU FeatureFinder_gpu(400);
 gpu::GpuMat inImg_g;   
 gpu::GpuMat src_keypoints_gpu, src_descriptors_gpu;

 vector< cv::KeyPoint> src_keypoints;   
 vector< float> src_descriptors;

 vector< detail::ImageFeatures> features;   

 for(int i=0; i< vImg.size(); ++i)   
 {     
  detail::ImageFeatures F;
  inImg_g.upload(vImg[i]);
  FeatureFinder_gpu(inImg_g, gpu::GpuMat(), src_keypoints_gpu, src_descriptors_gpu, false);
  
  //descriptor down   
  FeatureFinder_gpu.downloadKeypoints(src_keypoints_gpu, src_keypoints);
  FeatureFinder_gpu.downloadDescriptors(src_descriptors_gpu, src_descriptors);  

  //make ImageFeatures
  F.img_idx=i;
  F.img_size = Size(vImg[i].cols, vImg[i].rows);
  F.keypoints = src_keypoints;
  Mat M = Mat(src_descriptors.size()/64.0, 64, CV_32FC1);
  F.descriptors = M;
  memcpy(M.data, src_descriptors.data(), src_descriptors.size()*sizeof(float));  

  //Add vector
  features.push_back(F);

  //data confirm
  printf("%d - key:%d \n", features[i].img_idx, features[i].keypoints.size() );
  printf("    des:cols:%d, rows:%d \n", features[i].descriptors.cols, features[i].descriptors.rows);
  
 }

 

 
 //match
 vector< int> indices_;   
 double conf_thresh_ = 1.0;   
 Mat matching_mask;   
 vector< detail::MatchesInfo> pairwise_matches;   
 detail::BestOf2NearestMatcher Matcher(true);
 Matcher(features, pairwise_matches, matching_mask);   
 Matcher.collectGarbage();


 //grouping
 indices_ = detail::leaveBiggestComponent(features, pairwise_matches, (float)conf_thresh_);   
 Matcher.collectGarbage();   

 for (size_t i = 0; i < indices_.size(); ++i)   
 {   
  printf("%d \n", indices_[i] );   
 }   

 //Processing time measurement   
 BBtime = getTickCount();
 printf("Processing time = %.2lf(sec) \n",  (BBtime - AAtime)/getTickFrequency() );   

 
}  

(Arduino Study) temperature sensing

Temperature sensing  using thermister
Thermister gives resistance value depend on temperature changing.







...
#include < math.h>

void setup(void)
{
  Serial.begin(9600);
}

double Thermister(int RawADC){
  double Temp;
  Temp = log(((10240000/RawADC) - 10000));
  Temp = 1 / (0.001129148 + (0.000234125 * Temp) + (0.0000000876741 * Temp * Temp * Temp));
  Temp = Temp - 273.15;  
  
  return Temp;
}

void printTemp(void){
  double fTemp;
  double temp = Thermister( analogRead(0) );
  
  //read sensor value
  Serial.println("Temperature is:");
  Serial.println(temp);
}

void loop(void)
{
  printTemp();
  delay(1000);
}
---

(OpenCV, data type change, copy) vector to Mat, Mat to vector


This post is about how to copy Mat data to vector and copy vector data to Mat.
Reference this example source code.


printf("/////////////////////////////////////////////////////////////\n");
printf("//vector to Mat\n");
int r=3;
int c=4;

vector< float> Vf;

//insert value
int cnt=0;
for(int i=0; i< c; ++i)
for(int j=0; j< r; ++j)
Vf.push_back(cnt++);
//create Mat
Mat M=Mat(r,c,CV_32FC1);
//copy vector to mat
memcpy(M.data,Vf.data(),Vf.size()*sizeof(float));

//print Mat
cout < < M < < endl;


printf("/////////////////////////////////////////////////////////////\n");
printf("//Mat to vector\n");
vector< float> Vf2;

//copy mat to vector
Vf2.assign((float*)M.datastart, (float*)M.dataend);
//confirm
cnt=0;
for(int i=0; i< c; ++i)
{
for(int j=0; j< r; ++j)
printf("%lf ", Vf2[cnt++]);
printf("\n");
}


--

You want to copy image buffer to Mat example source code.
Reference on this page -> http://feelmare.blogspot.kr/2014/01/opencv-mat-class-image-bufferpoint-copy.html

1/10/2014

(Arduino Study) LED control using potentiometer





...
int potPin = 0;
int ledPin = 13;

int val=0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  val = analogRead(potPin);
  Serial.print(val);
  Serial.print("\n");
  digitalWrite(ledPin, HIGH);
  delay(val);
  digitalWrite(ledPin, LOW);
  delay(val);
}
--- LED brightness control using potentiometer ...
int potPin = 0;
int ledPin = 12;

int val=0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  val = analogRead(potPin);
  Serial.print(val);
  Serial.print("\n");
  analogWrite(ledPin, val/4);
}
---

1/08/2014

(Arduino Study) Led on/off duration changed by value of brightness is checked by potentiometer

the simple source code

---
int sensorPin = A0;
int ledPin = 13;
int ledBrightnessPin = 12;
int sensorValue = 0;

void setup(){
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}


void loop(){
  sensorValue = analogRead(sensorPin);
  
  Serial.print(sensorValue);
  Serial.print("\n");
  digitalWrite(ledPin, HIGH);
  delay(sensorValue);
  digitalWrite(ledPin, LOW);
  delay(sensorValue);
}
...




1/07/2014

(OpenCV, RotatedRect) How to make RotatedRect class


This is example class creation.

RotatedRect tRect(Point2f(p2.x, p2.y), Size2f(W,H), atan(mn.first)*180/3.1415);

In Here,
p2.x, p2.y is center coordinate.
in Size2f(W,H), W, H is withd and Height of rectangle.
at last, atan(mn.first)*180/3.1415 means degree, atan(mn.first) is some radian
*180/3.1415 means calculation radian to degree.

Simplify,

RotatedRect tRect(Point2f(centerX, cneterY), Size2f(W,H), rotation_degree);


Thank you.

(OpenCV, Mat class) Image buffer(point) copy to Mat

when you want to copy "unsigned char * pData" image buffer to Mat class in OpenCV.

This source is simple example code.

Mat InImg(height, width, CV_8UC1);
memcpy(InImg.data, pData, sizeof(unsigned char)*width*height);


(Arduino study) LED brightness change by pwm ( analogWrite function )

A analogWrite function generate PWM pules easy.
It can use to a motor control.




very very simple source code.
---
int ledPin = 10;

void setup(){
}

void loop(){
  //increase brightness step by +5
  for(int fadeValue = 0; fadeValue < 256; fadeValue +=5)
  {
    analogWrite(ledPin, fadeValue);
    delay(30); //wait 0.01sec
  }
  
  //decrease brightness step by -5
  for(int fadeValue=255; fadeValue >=0; fadeValue-=5)
  {
    analogWrite(ledPin, fadeValue);
    delay(30); //wait 0.01sec
  }
}
...

(iOS app Study) where File's Owner icon to set to connect outlet to actions


The answer is click View Controller then you can see property window on the right side.


1/05/2014

(Arduino study) 피에쑰 μŠ€ν”Όμ»€λ‘œ μ†Œλ¦¬λ‚΄κΈ° ( piezo speaker make a sound )

simple sound source code

generate 1000hz, 1000 duration sound


---
int speakerPin = 10;

void setup(){
  
}

void loop(){
 
 tone(speakerPin, 1000, 1000); //5000hz, duration 1sec
 delay(2000); //rest 2sec
}
---


---
#include "pitches.h"

int speakerPin = 8;
int melody[]={
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, 
  NOTE_B3, NOTE_C4};
  
int noteDurations[] = {4, 8, 8, 4, 4, 4, 4, 4};
  
void soundGo(){
  for(int thisNote = 0; thisNote < 8; thisNote++){
    //melody repeat
    int noteDuration = 1000/noteDurations[ thisNote ] ;
    tone(speakerPin, melody[thisNote], noteDuration);
    //delay between sounds
    int pauseBetweenNotes = noteDuration * 1.30;
    delay( pauseBetweenNotes);
    noTone(8);
  }
}

void setup(){
  
}

void loop(){
  soundGo();
}

---
In the demo video, we can know principle of piezo speaker that is sounded by vibration.


pitches.h source code is here
---
/*************************************************
 * Public Constants
 *************************************************/

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

...