03.python & Computer Vision
03.python & Computer Vision
- 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
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)
- 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
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
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
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)
expected = test_labels
predicted = classifier.predict(test_data)
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