Python & Computer Vision
Rino Tri Aji Pamungkas (50663)
Research & Development Team
8 Maret 2019
Basic Python - Conditional Structure
a = 200; b = 33
- Variable and Expression if b > a:
Example : print("b is greater than a")
a="Hello Python“; b=9*9 elif a == b:
print(type(a)); print(type(b)) print("a and b are equal")
else:
print("a is greater than b")
- Loops
- Function for x in range(2, 30, 3):
• Return Value print(x)
def hitungLuas(a, b):
return a*b - Classes
class Person:
• Not Return Value def __init__(self, name, age):
def testVariabel(): [Link] = name; [Link] = age
a="Hello Python“; b=9*9 def myfunc(self):
print(type(a));print(type(b)) print("Hello my name is " + [Link] + ",
and my age is " + str([Link]))
p1 = Person("Rino", 36); [Link]()
Working with Date and Time Python
Library Datetime :
from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta
-Date, Time and Datetime Classes
today = [Link]()
print("Today is : "+str(today))
print("Date Component :", [Link], [Link], [Link])
print("Today's Weekday # is :", [Link]())
days = ["senin","selasa","rabu","kamis","jumat","sabtu","minggu"]
print("Which is a :", days[[Link]()])
today = [Link]()
print("The current date and time is :", today)
t = [Link]([Link]())
d = [Link]([Link]())
c = [Link]([Link]())
print(t); print(d); print(c)
Working with Date and Time Python
- Formatting time output
now = [Link]()
x = datetime(2018, 6, 1)
print([Link]("The current Year is %Y"))
print([Link]("%A, %d %b, %Y"))
xx = "09/19/18 [Link]"
testStrptime = [Link](xx, "%m/%d/%y %H:%M:%S")
print(testStrptime)
- Using timedelta object
now = [Link]()
print(timedelta(days=365, hours=5, minutes=1))
print("today is :", now)
print("One year from now is :", (now + timedelta(days=366)))
print("In 2 days 3 week from now is :", (now +
timedelta(days=2, weeks=3)))
- Calendars
Working with Date and Time Python
- Calendars
import calendar
c = [Link]([Link])
st = [Link](2017,1,0,0)
print(st)
Working with Files
- Read and Write file
Write File :
def writeTextFile():
f = open("[Link]", "w+")
for i in range(10):
[Link]("This is Line "+ str(i) +"\n")
[Link]()
Read File :
f = open("[Link]", "r")
if [Link] == "r":
# print("---Read All Content---")
# contents = [Link](); print(contents)
print("---Read Per Line---")
fl = [Link]()
for x in fl:
print(x)
[Link]()
Working with Files
- Library added
import os
from os import path
- Working with OS path utilities
Disini source yang di gunakan untuk mendapatkan info dari System OS maupun file,
seperti contoh untuk mendapatkan Nama OS menggunakan perintah :
print("Name my OS is", [Link])
atau perintah untuk mendapat file exist or not exist :
print("Item exist :", [Link]("[Link]"))
print("Item is a file :", [Link]("[Link]"))
print("Item is a directory :", [Link]("[Link]"))
Working with Files
- Using file system shell methods
Disini source untuk memanipulasi file, seperti copy file, rename file, zip file.
Seperti contoh berikut perintah untuk copy file :
if [Link]("[Link]"):
src = [Link]("[Link]")
# Create file backup
dst = src + ".bak"
# copy file : dengan kondisi yang baru.
[Link](src, dst)
# copy status file : over permission, date modified, time modified,
and ther info
[Link](src, dst)
Working with Web Data
- Library to be added
import [Link]
- Fetching Internet Data
webUrl = [Link]("[Link]
print("result code : " + str([Link]()))
# Get data html from [Link]
data = [Link]()
print(data)
Working with Web Data
- JSON Data
urlData = "[Link]
webUrl = [Link](urlData)
print("result code : " + str([Link]()))
if ([Link]() == 200):
data = [Link]()
printResults(data)
else:
print("Received Error, cannot parse results")
def printResults(data):
theJSON = [Link](data)
for d in theJSON["features"]:
if(d["properties"]["mag"] >= 4.0):
print("%2.1f" % d["properties"]["mag"], d["properties"]["place"])
print("------------\n")
Working with Web Data
- Parsing and Processing HTML - Lanjutan Manipulating XML
metacount = 0 def printResultXml(data, url):
doc = [Link](data)
parser = MyHTMLParser() root = [Link](data)
f = open("[Link]") for gempa in [Link]("gempa"):
if [Link] == 'r': magnitude = [Link]("Magnitude").text
contens = [Link]() wilayah = [Link]("Wilayah").text
[Link](contens) print(wilayah, magnitude)
print("Meta tag found: "+str(metacount))
- Manipulating XML
xmlUrl =
"[Link]
webUrl = [Link](xmlUrl)
print("result code : " + str([Link]()))
if ([Link]() == 200):
data = [Link]()
printResultXml(data, xmlUrl)
else:
print("Received Error, cannot parse
results")
Working with Computer Vision in Python
Installation and Library to add :
•Download dan Install Anaconda for python 3
•conda install –c conda-forge opencv
•conda install –c menpo dlib
•Install pip tesseract
•Install pip py tesseract
•Install pip tensorflow
•Install pip tensorflow-gpu
•Install pip tensorflow-hub
•Install pip tflearn
•Install pip keras
MNIST DIGIT DATA
Library used MNIST data traning and data test
MNIST DIGIT DATA
Example Image digit from sklearn
#what kind of data do we already have?
from sklearn import datasets
digits = datasets.load_digits()
example_image = [Link][0]
print(type(example_image))
[Link](example_image)
[Link]()
example_image.reshape((8*8,1))
MNIST DIGIT DATA
Example Image train data from MNIST
# acquire standard MNIST handwritten digit data
# [Link]
data_dir = '/tmp/tensorflow/mnist/input_data'
mnist = input_data.read_data_sets(data_dir, one_hot=True)
# now we load and examine the data
train_data=[Link]
print(train_data.shape)
n_samples = train_data.shape[0]
train_labels=[Link]([Link]([Link]==1))[1]
[Link](train_data[1234].reshape((28,28)))
[Link]()
DIGIT RECOGNITION
Predict Test data MNIST from train data MNIST
# Train Create a classifier: a support vector classifier
classifier = [Link](gamma=0.001)
# Train the model
[Link](train_data, train_labels)
# Now predict the value of the digit on the test data:
test_data=[Link]
test_labels=[Link]([Link]([Link]==1))[1]
expected = test_labels
predicted = [Link](test_data)
images_and_predictions = list(zip(test_data, predicted))
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
[Link](2, 4, index + 5)
[Link]('off')
[Link]([Link]((28,28)), cmap=[Link].gray_r,
interpolation='nearest')
[Link]('Prediction: %i' % prediction)
[Link]()
DIGIT RECOGNITION
Predict Draw Image From Train Data MNIST
#Let's test our model on images we draw ourselves!
img = [Link]((28,28,3),dtype='uint8')
fig, axes = [Link](figsize=(3,3))
[Link](img)
[Link]("off"); [Link]();
annotator = Annotator(axes)
[Link]('motion_notify_event', annotator.mouse_move)
[Link]('button_release_event', annotator.mouse_release)
[Link]('button_press_event', annotator.mouse_press)
[Link](); [Link]();
digimg = [Link]((28,28,3),dtype='uint8')
for ind, points in enumerate([Link][:-1]):
digimg=[Link](digimg, [Link][ind], [Link][ind+1],(255,0,0),1)
digimg = [Link](digimg,(5,5),1.0)
digimg = ([Link]('float') *1.0/[Link](digimg)).astype('float')[:,:,0]
digimg **= 0.5; digimg[digimg>0.9]=1.0
#The model is expecting the input in a particular format
testim = [Link]((-1,28*28))
print("Support vector machine prediction:",[Link]( testim ))
outimg = [Link]((28,28))
figure(figsize=(3,3)); imshow(outimg);