Python series of projects, including crawler, basic information, reinforcement learning
- face : 人脸识别
- gui: 图形界面
- Splder: 爬虫
- v11 js加密,案例破解有道翻译。详细内容请看: https://blog.csdn.net/July_whj/article/details/81588856
- js.js 为有道翻译js源码
- 网络编程:网络编程tcp
- lp.*: 强化学习
Python series of projects, including crawler, basic information, reinforcement learning
Python series of projects, including crawler, basic information, reinforcement learning
你好 请教一下 pyqt5的怎么调用模型 看到您的数字识别 没太看明白
# 定义一个返回函数,返回fun2。通过变量fun进行接收返回值,打印返回值类型,并调用返回函数。
def fun(a):
def fun2():
print "this is fun2"
print a
return fun2
fun = fun(2)
print (type(fun))
print fun()
原意就是映射,即把集合或列表得元素,每一个元素都按照一定规则进行操作,生成一个新的列表或者集合
map函数是系统提供得具有映射功能得函数,返回值是一个迭代对象
map python2 传入什么类型数据返回什么类型数据
map python3 传入什么类型数据返回 ..."map"... 类型数据
map(...)
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
# map 举例
# 将一个列表中的元素乘以10,并得到新列表
l1 = [i for i in range(10)]
print(l1)
l2 = []
for i in l1:
l2.append(i * 10)
print(l2)
# map 实现以上功能
def mulTen(n):
return n * 10
l3 = map(mulTen,l1)
print (l3)
from functools import reduce
# 定义个操作函数
def add(x,y):
return x + y
# 对于列表【1,2,3,4,5,6】执行add 操作
rst = reduce(add ,[1,2,3,4,5,6])
print (rst)
# 以上reduce可看作下面进行运算
rst2 =add(add(add(add(add(1,2),3),4),5),6)
print(rst2)
# filter 函数
# 对一个列表,对其进行过滤,偶数组成一个新列表
# 需要定义过滤函数
# 过滤函数要求有输入,返回布尔值
def isEven(a):
return a % 2 == 0
l = [1,2,3,4,54,3,2,32,32,32,3,333,44,32,4325]
res = filter(isEven,l)
#返回一个可迭代对象
print(res)
print([i for i in res])
#排序案例1
a = [12,32,43,543,56,654,6576,5765,765,645,6546645,654645]
al = sorted(a)
ad = sorted(a,reverse=True)
print(al)
print(ad)
#排序案例2
a = [-12,2,32,-455,321,32]
# 按照绝对值进行排序
# abs是求绝对值的意思
# 即按照绝对值的倒叙进行排序
al = sorted(a, key=abs, reverse=True)
print(al)
#sorted 排序案例
astr = ['dana','whj','jin','WTt','Zs','sz']
str1 = sorted(astr)
print(str1)
str2 = sorted(astr,key=str.lower)
print(str2)
# 负责一点的返回函数的例子
# args 参数列表
# myF4 定义函数,返回内部定义的函数myF5
# myF5使用了外部变量,这个变量是myF4的参数
def myF4( *args):
def myF5():
rst = 0
for n in args:
rst += n
return rst
return myF5
f5 = myF4(1,2,3,4,5,6,7,8,9,10)
f5()
f6 = myF4(10,20,30)
f6()
# 闭包常见的坑
def count():
# 定义列表
fs = []
for i in range(1,4):
# 定义了一个函数f
def f():
return i*i
fs.append(f)
return fs
f1,f2,f3 = count()
print(f1())
print(f2())
print(f3())
# 修改上述函数
def count1():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1,4):
fs.append(f(i))
return fs
f1,f2,f3 = count1()
print(f1())
print(f2())
print(f3)
# 我们要想拓展原来函数代码,最直接的办法就是侵入代码里面修改,例如:
import time
def hello():
startTime = time.time()
print("hello")
time.sleep(1)
print("world")
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
hello()
import time
def deco(func):
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
def func():
print("hello")
time.sleep(1)
print("world")
f = func
deco(f)#只有把func()或者f()作为参数执行,新加入功能才会生效
#既不需要侵入,也不需要函数重复执行
import time
def deco(func):
def wrapper():
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
# 上面定义装饰器,使用的时候需要用到@ ,此符号是python的语法糖
@deco
def func():
print("hello")
time.sleep(1)
print("world")
f = func #这里f被赋值为func,执行f()就是执行func()
f()
import time
def deco(func):
def wrapper(a,b):
startTime = time.time()
func(a,b)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
f = func
f(3,4)
import time
def deco(func):
def wrapper(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
@deco
def func2(a,b,c):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b+c))
f = func
func2(3,4,5)
f(3,4)
import time
def deco01(func):
def wrapper(*args, **kwargs):
print("this is deco01")
startTime = time.time()
func(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
print("deco01 end here")
return wrapper
def deco02(func):
def wrapper(*args, **kwargs):
print("this is deco02")
func(*args, **kwargs)
print("deco02 end here")
return wrapper
@deco01
@deco02
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
f = func
f(3,4)
# 把字符串转换十进制数字
int("12345")
# 求八进制的字符串12345,表示成十进制的数字是多少
int("12345",base=8)
# 新建一个函数,此函数是默认输入的字符串是16进制数字
# 把此字符串返回十进制的数字
def int16(x,base=16):
return int(x,base)
int16("12345")
import functools
int16 = functools.partial(int,base=16)
int16("12345")
评论
python 手写数字识别知识不用多说,本文用深度学习Python库Keras实现深度学习入门教程mnist手写数字识别。mnist手写数字识别是机器学习和深度学习领域的“hello world”,MNIST数据集是手写数字的数据集合,训练集规模为60000,测试集为10000。
模型优化和提高识别率请关注后续文章。本文知识对整体代码和原型预演
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')
seed = 7
numpy.random.seed(seed)
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
X_train = X_train / 255
X_test = X_test / 255
# one hot encode
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
def baseline_model():
# create model
model = Sequential()
model.add(Convolution2D(30, 5, 5, border_mode='valid', input_shape=(1, 28, 28), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(15, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
model = baseline_model()
model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=10, batch_size=200, verbose=2)
#
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100 - scores[1] * 100))
model.save('model.h5')
可看到,最终模型训练结果错误率0.75%
# -*- coding:utf-8 -*-
"""
Based on CNN neural network, training handwritten numeral recognition model model.h5.
The class refers to the trained model for handwritten numeral recognition
"""
import numpy as np
from PIL import Image
from keras import backend as K
from keras.models import load_model
from cn.org.whj.ai.day_two.ImageUtils import changeImage28
class Recognition:
def __init__(self,path):
K.set_image_dim_ordering('th')
self.my_model = load_model(path+'/day_one/model.h5')
def readImage2result(self, rimg):
width, height = rimg.size
im = rimg.convert("L")
data = im.getdata()
data = np.matrix(data, dtype='float') / 255.0
new_data = np.reshape(data * 255.0, (height, width))
new_data = new_data[np.newaxis, np.newaxis, :]
pred = self.my_model.predict(new_data)
return np.argmax([pred[0]])
if __name__ == '__main__':
re = Recognition()
rimg = Image.open('only.png')
rimg = changeImage28(rimg)
resut = re.readImage2result(rimg)
print(resut)
# -*- coding:utf-8 -*-
"""
Write the number generator, first, into the tablet, which is set to interfere with the picture,
press the m key, the handwritten number. Second, after the handwritten number is completed,
press the w key on the keyboard and perform the screenshot operation.
Drag the screenshot area with the left mouse button, and save the screenshot information automatically after release.
Finally, press q on the keyboard and exit the script
"""
import numpy as np
import cv2 as cv
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix, iy = -1, -1
class Mouse():
# mouse callback function
def __init__(self):
self.img = np.zeros((200, 200, 3), np.uint8)
def draw_circle(self, event, x, y, flags, param):
global ix, iy, drawing, mode
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv.EVENT_MOUSEMOVE:
if drawing:
if self.mode:
cv.rectangle(self.img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv.circle(self.img, (x, y), 5, (0, 0, 255), -1)
elif event == cv.EVENT_LBUTTONUP:
drawing = False
if self.mode:
cv.rectangle(self.img, (ix, iy), (x, y), (0, 255, 0), -1)
else:
cv.circle(self.img, (x, y), 5, (0, 0, 255), -1)
def on_mouse(self, event, x, y, flags, param):
global img, point1, point2
img2 = self.img.copy()
if event == cv.EVENT_LBUTTONDOWN: # 左键点击
point1 = (x, y)
cv.circle(img2, point1, 10, (0, 255, 0), 5)
cv.imshow('Digital writing pad', img2)
elif event == cv.EVENT_MOUSEMOVE and (flags & cv.EVENT_FLAG_LBUTTON): # 按住左键拖曳
cv.rectangle(img2, point1, (x, y), (255, 0, 0), 5)
cv.imshow('Digital writing pad', img2)
elif event == cv.EVENT_LBUTTONUP: # 左键释放
point2 = (x, y)
cv.rectangle(img2, point1, point2, (0, 0, 255), 5)
cv.imshow('Digital writing pad', img2)
min_x = min(point1[0], point2[0])
min_y = min(point1[1], point2[1])
width = abs(point1[0] - point2[0])
height = abs(point1[1] - point2[1])
cut_img = self.img[min_y:min_y + height, min_x:min_x + width]
cv.imwrite('only.png', cut_img)
def create_image(self):
self.mode = True
cv.namedWindow('Digital writing pad')
cv.setMouseCallback('Digital writing pad', self.draw_circle)
while (1):
cv.imshow('Digital writing pad', self.img)
k = cv.waitKey(1) & 0xFF
if k == ord('m'):
self.mode = not mode
elif k == 27:
break
elif k == ord('w'):
cv.setMouseCallback('Digital writing pad', self.on_mouse)
elif k == ord('q'):
break
cv.destroyAllWindows()
if __name__ == '__main__':
mn = Mouse()
mn.create_image()
# -*- coding:utf-8 -*-
from tkinter import *
import tkinter as tk
from cn.org.whj.ai.day_two.Mouse import Mouse
from PIL import Image, ImageTk
from cn.org.whj.ai.day_one.handwriting_recognition import Recognition
from cn.org.whj.ai.day_two.ImageUtils import changeImage28
import os
def creat_image():
mn = Mouse()
mn.create_image()
class App(tk.Frame):
def __init__(self, root):
super().__init__(root)
root.title('手写识别')
w = Canvas(root, width=500, height=20)
w.pack()
Label(root, text='欢迎使用手写识别系统,以下为使用说明').pack(side=TOP)
Label(root, text='1、点击生成手写图片按钮,摁下m切换到手写状态,点击鼠标左键,进行手写操作。').pack(side=TOP, anchor=W)
Label(root, text='2、手写✅后,摁下w进行切图操作,点击鼠标左键,选择截取数字区域').pack(side=TOP, anchor=W)
Label(root, text='3、点击刷新按钮,回显截图').pack(side=TOP, anchor=W)
Label(root, text='4、点击数字识别按钮,识别截图中数字(0~9)').pack(side=TOP, anchor=W)
Label(root, text='识别到数字是:').pack(side=TOP, anchor=W)
self.numLabel = Label(root, text='', relief=RAISED,fg="red", font=("黑体", 30, "bold"))
self.numLabel.pack(side=TOP, anchor=CENTER)
Label(root, text='').pack(side=TOP, anchor=W)
fm = Frame(root)
# Button是一种按钮组件,与Label类似,只是多出了响应点击的功能
Button(fm, text='生成手写图片', command=creat_image).pack(side=TOP, anchor=W, fill=X, expand=YES)
Button(fm, text='刷新', command=self.changeImage).pack(side=TOP, anchor=W, fill=X, expand=YES)
Button(fm, text='数字识别', command=self.recognition).pack(side=TOP, anchor=W, fill=X, expand=YES)
Button(fm, text='汉字识别').pack(side=TOP, anchor=W, fill=X, expand=YES)
fm.pack(side=LEFT, fill=BOTH, expand=YES, padx=20)
self.pilImage = Image.open("only.png")
self.tkImage = ImageTk.PhotoImage(image=self.pilImage)
self.label = Label(root, image=self.tkImage)
self.label.pack()
Label(root, text="按住鼠标左键并移动,开始绘制你的理想蓝图吧......").pack(side=BOTTOM)
def changeImage(self):
self.png = tk.PhotoImage(file="only.png") # 需要储存为实例属性,否则会被垃圾回收
self.label.configure(image=self.png)
def recognition(self):
base_dir = os.path.dirname(os.getcwd())
re = Recognition(base_dir)
img = Image.open('only.png')
img = changeImage28(img)
results = re.readImage2result(rimg=img)
self.numLabel.configure(text=str(results))
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
源码地址:https://github.com/hongjieWang/python-Splder/tree/master/cn/org/whj/ai
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.