0% found this document useful (0 votes)
26 views17 pages

03.python & Computer Vision

This document discusses using Python for computer vision tasks. It covers loading and working with the MNIST digit dataset for training and testing image classification models. It demonstrates predicting digits from the test set after training a support vector machine classifier on the training data. It also shows how to draw a digit, preprocess it, and use the trained model to predict the digit. Finally, it discusses installing common Python libraries for computer vision like OpenCV, Dlib, TensorFlow and Keras.

Uploaded by

rino tri a.p
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
26 views17 pages

03.python & Computer Vision

This document discusses using Python for computer vision tasks. It covers loading and working with the MNIST digit dataset for training and testing image classification models. It demonstrates predicting digits from the test set after training a support vector machine classifier on the training data. It also shows how to draw a digit, preprocess it, and use the trained model to predict the digit. Finally, it discusses installing common Python libraries for computer vision like OpenCV, Dlib, TensorFlow and Keras.

Uploaded by

rino tri a.p
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 17

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(): self.name = name; self.age = age
a="Hello Python“; b=9*9 def myfunc(self):
print(type(a));print(type(b)) print("Hello my name is " + self.name + ",
and my age is " + str(self.age))
p1 = Person("Rino", 36); p1.myfunc()
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 = date.today()
print("Today is : "+str(today))
print("Date Component :", today.day, today.month, today.year)
print("Today's Weekday # is :", today.weekday())
days = ["senin","selasa","rabu","kamis","jumat","sabtu","minggu"]
print("Which is a :", days[today.weekday()])

today = datetime.now()
print("The current date and time is :", today)
t = datetime.time(datetime.now())
d = datetime.date(datetime.now())
c = datetime.ctime(datetime.now())
print(t); print(d); print(c)
Working with Date and Time Python
- Formatting time output
now = datetime.now()
x = datetime(2018, 6, 1)
print(now.strftime("The current Year is %Y"))
print(now.strftime("%A, %d %b, %Y"))
xx = "09/19/18 13:55:26"
testStrptime = datetime.strptime(xx, "%m/%d/%y %H:%M:%S")
print(testStrptime)

- Using timedelta object


now = datetime.now()
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 = calendar.TextCalendar(calendar.SUNDAY)
st = c.formatmonth(2017,1,0,0)
print(st)
Working with Files
- Read and Write file
Write File :
def writeTextFile():
f = open("textfile.txt", "w+")
for i in range(10):
f.write("This is Line "+ str(i) +"\n")
f.close()

Read File :
f = open("textfile.txt", "r")
if f.mode == "r":
# print("---Read All Content---")
# contents = f.read(); print(contents)
print("---Read Per Line---")
fl = f.readlines()
for x in fl:
print(x)
f.close()
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", os.name)

atau perintah untuk mendapat file exist or not exist :


print("Item exist :", path.exists("textfile.txt"))
print("Item is a file :", path.isfile("textfile.txt"))
print("Item is a directory :", path.isdir("textfile.txt"))
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 path.exists("textfile.txt"):
src = path.realpath("textfile.txt")
# Create file backup
dst = src + ".bak"
# copy file : dengan kondisi yang baru.
shutil.copy(src, dst)
# copy status file : over permission, date modified, time modified,
and ther info
shutil.copystat(src, dst)
Working with Web Data
- Library to be added
import urllib.request

- Fetching Internet Data


webUrl = urllib.request.urlopen("http://www.google.com")
print("result code : " + str(webUrl.getcode()))
# Get data html from google.com
data = webUrl.read()
print(data)
Working with Web Data
- JSON Data
urlData = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson"
webUrl = urllib.request.urlopen(urlData)
print("result code : " + str(webUrl.getcode()))
if (webUrl.getcode() == 200):
data = webUrl.read()
printResults(data)
else:
print("Received Error, cannot parse results")

def printResults(data):
theJSON = json.loads(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 = xml.dom.minidom.parseString(data)
parser = MyHTMLParser() root = ET.fromstring(data)
f = open("demoLayoutHTML.html") for gempa in root.findall("gempa"):
if f.mode == 'r': magnitude = gempa.find("Magnitude").text
contens = f.read() wilayah = gempa.find("Wilayah").text
parser.feed(contens) print(wilayah, magnitude)
print("Meta tag found: "+str(metacount))

- Manipulating XML
xmlUrl =
"http://data.bmkg.go.id/gempaterkini.xml"
webUrl = urllib.request.urlopen(xmlUrl)
print("result code : " + str(webUrl.getcode()))
if (webUrl.getcode() == 200):
data = webUrl.read()
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 = digits.images[0]
print(type(example_image))
plt.imshow(example_image)
plt.show()
example_image.reshape((8*8,1))
MNIST DIGIT DATA
Example Image train data from MNIST
# acquire standard MNIST handwritten digit data
# http://yann.lecun.com/exdb/mnist/

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=mnist.train.images
print(train_data.shape)
n_samples = train_data.shape[0]
train_labels=np.array(np.where(mnist.train.labels==1))[1]
plt.imshow(train_data[1234].reshape((28,28)))
plt.show()
DIGIT RECOGNITION
Predict Test data MNIST from train data MNIST

# Train Create a classifier: a support vector classifier


classifier = svm.SVC(gamma=0.001)

# Train the model


classifier.fit(train_data, train_labels)
# Now predict the value of the digit on the test data:
test_data=mnist.test.images
test_labels=np.array(np.where(mnist.test.labels==1))[1]

expected = test_labels
predicted = classifier.predict(test_data)

images_and_predictions = list(zip(test_data, predicted))


for index, (image, prediction) in enumerate(images_and_predictions[:4]):
plt.subplot(2, 4, index + 5)
plt.axis('off')
plt.imshow(image.reshape((28,28)), cmap=plt.cm.gray_r,
interpolation='nearest')
plt.title('Prediction: %i' % prediction)
plt.show()
DIGIT RECOGNITION
Predict Draw Image From Train Data MNIST
#Let's test our model on images we draw ourselves!
img = np.zeros((28,28,3),dtype='uint8')
fig, axes = plt.subplots(figsize=(3,3))
axes.imshow(img)
plt.axis("off"); plt.gray();
annotator = Annotator(axes)
plt.connect('motion_notify_event', annotator.mouse_move)
plt.connect('button_release_event', annotator.mouse_release)
plt.connect('button_press_event', annotator.mouse_press)
axes.plot(); plt.show();

digimg = np.zeros((28,28,3),dtype='uint8')
for ind, points in enumerate(annotator.xy[:-1]):
digimg=cv2.line(digimg, annotator.xy[ind], annotator.xy[ind+1],(255,0,0),1)
digimg = cv2.GaussianBlur(digimg,(5,5),1.0)
digimg = (digimg.astype('float') *1.0/np.amax(digimg)).astype('float')[:,:,0]
digimg **= 0.5; digimg[digimg>0.9]=1.0

#The model is expecting the input in a particular format


testim = digimg.reshape((-1,28*28))
print("Support vector machine prediction:",classifier.predict( testim ))
outimg = testim.reshape((28,28))
figure(figsize=(3,3)); imshow(outimg);

You might also like