今天给大家介绍20个非常实用的Python项目,帮助大家更好的学习Python。
① 猜字游戏
在这个游戏中,你必须一个字母一个字母的猜出秘密单词。
如果你猜错了一个字母,你将丢掉一条命。
正如游戏名那样,你需要仔细选择字母,因为你的生命数量非常有限。
import random
# 生命次数
lives = 3
# 神秘单词, 随机选择
words = ['pizza', 'fairy', 'teeth', 'shirt', 'otter', 'plane']
secret_word = random.choice(words)
# print(secret_word)
clue = list('?????')
heart_symbol = u'\u2764'
guessed_word_correctly = False
def update_clue(guessed_letter, secret_word, clue):
index = 0
while index < len(secret_word):
if guessed_letter == secret_word[index]:
clue[index] = guessed_letter
index = index + 1
while lives > 0:
print(clue)
print('剩余生命次数: ' + heart_symbol * lives)
guess = input('猜测字母或者是整个单词: ')
if guess == secret_word:
guessed_word_correctly = True
break
if guess in secret_word:
update_clue(guess, secret_word, clue)
else:
print('错误。你丢了一条命\n')
lives = lives - 1
if guessed_word_correctly:
print('你赢了! 秘密单词是 ' + secret_word)
else:
print('你输了! 秘密单词是 ' + secret_word)
② 闹钟
闹钟是一种具有可以在预先设定的时间被激活以响铃的功能的时钟,用于唤醒打工人们。
使用Python中的DateTime模块来创建闹钟,并用Python中的playsound库来播放闹钟声音。
from datetime import datetime
from playsound import playsound
# 输入
alarm_time = input("请输入闹钟时间, 示例: 09:50:00 am\n")
# 时
alarm_hour = alarm_time[0:2]
# 分
alarm_minute = alarm_time[3:5]
# 秒
alarm_seconds = alarm_time[6:8]
# 上午或下午
alarm_period = alarm_time[9:11].upper()
print("完成闹钟设置..")
while True:
now = datetime.now()
current_hour = now.strftime("%I")
current_minute = now.strftime("%M")
current_seconds = now.strftime("%S")
current_period = now.strftime("%p")
# 时间判断
if alarm_period == current_period:
if alarm_hour == current_hour:
if alarm_minute == current_minute:
if alarm_seconds == current_seconds:
print("起来啦!")
# 闹钟铃声
playsound('audio.mp3')
break
③ 骰子模拟器
可以通过选择1到6之间的随机整数,来完成骰子模拟。
import random
# 设置最大值和最小值
min_val = 1
max_val = 6
# 是否继续
roll_again = "yes"
# 循环
while roll_again == "yes" or roll_again == "y":
print("开始掷骰子")
print("骰子数值是 :")
# 第一轮
print(random.randint(min_val, max_val))
# 第二轮
print(random.randint(min_val, max_val))
# 是否继续
roll_again = input("是否继续掷骰子?(是的话, 输入yes或者y)")
使用random.randint()函数。函数根据我们指定的开始和结束范围返回一个随机整数。
④ 二维码
二维码是用于将数据编码和解码为机器可读的方法。
包含一个白色背景上的黑色方块网格,可以被任何成像设备(如手机)读取,并进行处理以从图案中提取所需的数据。
import pyqrcode
# 设置二维码信息
s = "https://www.baidu.com"
# 生成二维码
url = pyqrcode.create(s)
# 保存二维码
url.svg("baidu.svg", scale=8)
⑤ 语言检测
当你需要处理包含不同语言数据,且数据非常大的时候,语言检测就派上用场了。
使用Python中的langdetect包,可以在几行代码内检测超过55种不同的语言。
from langdetect import detect
text = input("输入信息: ")
print(detect(text))
⑥ 加密和解密
密码术意味着更改消息的文本,以便不知道你秘密的人永远不会理解你的消息。
下面就来创建一个GUI应用程序,使用Python进行加密和解密。
在这里,我们需要编写使用无限循环的代码,代码将不断询问用户是否要加密或解密消息。
from tkinter import messagebox, simpledialog, Tk
def is_even(number):
return number % 2 == 0
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
return even_letters
def get_odd_letters(message):
odd_letters = []
for counter in range(0, len(message)):
if not is_even(counter):
odd_letters.append(message[counter])
return odd_letters
def swap_letters(message):
letter_list = []
if not is_even(len(message)):
message = message + 'x'
even_letters = get_even_letters(message)
odd_letters = get_odd_letters(message)
for counter in range(0, int(len(message) / 2)):
letter_list.append(odd_letters[counter])
letter_list.append(even_letters[counter])
new_message = ''.join(letter_list)
return new_message
def get_task():
task = simpledialog.askstring('任务', '你是否想要加密或解密信息?')
return task
def get_message():
message = simpledialog.askstring('信息', '输入相关信息: ')
return message
root = Tk()
while True:
task = get_task()
if task == '加密':
message = get_message()
encrypted = swap_letters(message)
messagebox.showinfo('密电的密文为:', encrypted)
elif task == '解密':
message = get_message()
decrypted = swap_letters(message)
messagebox.showinfo('密电的明文为:', decrypted)
else:
break
root.mainloop()
示例。
⑦ URL缩短
短网址由于易于记忆和输入,因此在数字营销领域非常受欢迎。
这里给大家介绍一下,如何使用Python创建URL缩短器。
from __future__ import with_statement
import contextlib
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import sys
def make_tiny(url):
request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url': url}))
# print(request_url)
with contextlib.closing(urlopen(request_url)) as response:
return response.read().decode('utf-8')
def main():
for tinyurl in map(make_tiny, ['https://baijiahao.baidu.com/s?id=1719379508156841662']):
print(tinyurl)
if __name__ == '__main__':
main()
运行代码,输出如下。
# 输出
https://tinyurl.com/y4z6z2gq
⑧ 音乐播放器
音乐播放器,可让你快速轻松地管理和收听所有音乐文件。
应该不少小伙伴都使用过,网易云音乐、QQ音乐、酷狗音乐等。
这里小F将使用Pygame和Tkinter,来创建一个音乐播放器。
import pygame
import tkinter as tkr
from tkinter.filedialog import askdirectory
import os
music_player = tkr.Tk()
music_player.title("我的音乐播放器")
music_player.geometry("450x350")
directory = askdirectory()
os.chdir(directory)
song_list = os.listdir()
play_list = tkr.Listbox(music_player, font="Helvetica 12 bold", bg='yellow', selectmode=tkr.SINGLE)
for item in song_list:
pos = 0
play_list.insert(pos, item)
pos += 1
pygame.init()
pygame.mixer.init()
def play():
"""播放"""
pygame.mixer.music.load(play_list.get(tkr.ACTIVE))
var.set(play_list.get(tkr.ACTIVE))
pygame.mixer.music.play()
def stop():
"""停止"""
pygame.mixer.music.stop()
def pause():
"""暂停"""
pygame.mixer.music.pause()
def unpause():
"""取消暂停"""
pygame.mixer.music.unpause()
Button1 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="播放", command=play, bg="blue", fg="white")
Button2 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="停止", command=stop, bg="red", fg="white")
Button3 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="暂停", command=pause, bg="purple", fg="white")
Button4 = tkr.Button(music_player, width=5, height=3, font="Helvetica 12 bold", text="取消暂停", command=unpause, bg="orange", fg="white")
var = tkr.StringVar()
song_title = tkr.Label(music_player, font="Helvetica 12 bold", textvariable=var)
song_title.pack()
Button1.pack(fill="x")
Button2.pack(fill="x")
Button3.pack(fill="x")
Button4.pack(fill="x")
play_list.pack(fill="both", expand="yes")
music_player.mainloop()
⑨ 生命游戏
生命游戏由英国数学家约翰·H·康威设计的,是一种类似于生物社会的兴衰和交替的游戏。
游戏使用无限大小的矩形网格,其中每个网格都是空的或被有机体占据。被占用的细胞是活的,而空的细胞是死的。
游戏在特定时期内进行,每一轮都会根据当前配置中生物体的排列创建一个新的世代。
下一代网格的状态,是通过将以下四个基本规则应用于当前配置的每个网格来确定的:
- 如果一个细胞还活着并且有两个或三个活着的邻居,那么该细胞在下一代中仍然活着;
- 一个没有活邻居或只有一个活邻居的活细胞会在下一代死于孤立;
- 有四个或更多活邻居的活细胞会因下一代人口过剩而死亡;
- 一个只有三个活着的邻居的死细胞会导致出生并在下一代中存活;
board = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
# 邻居数组为给定的单元格找到8个相邻的单元格
neighbors = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]
rows = len(board)
cols = len(board[0])
# 创建一个原始板的副本
copy_board = [[board[row][col] for col in range(cols)] for row in range(rows)]
# 逐个单元地迭代
for row in range(rows):
for col in range(cols):
# 对于每个单元计算邻居的数量
live_neighbors = 0
for neighbor in neighbors:
r = (row + neighbor[0])
c = (col + neighbor[1])
# 检查相邻细胞的有效性,以及它是否原来是一个活细胞
# 评估是针对副本进行的,因为它永远不会更新。
if (r < rows and r >= 0) and (c < cols and c >= 0) and (copy_board[r][c] == 1):
live_neighbors += 1
# 规则1或规则3
if copy_board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[row][col] = 0
# 规则4
if copy_board[row][col] == 0 and live_neighbors == 3:
board[row][col] = 1
print(board)
结果如下。
# 输入
board = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
# 输出
board = [[0, 0, 0], [1, 1, 0], [0, 0, 0]]
⑩ Turtle绘图
Turtle模块提供了在二维平面上移动的环境。
Turtle可以实现位置、航向和各种可能的状态和动作。
import turtle as tu
roo = tu.Turtle() # 创建对象
wn = tu.Screen() # 屏幕对象
wn.bgcolor("black") # 屏幕背景
wn.title("分形树")
roo.left(90) # 移动
roo.speed(20) # 速度
def draw(l): # 以长度'l'作为参数的递归函数
if l < 10:
return
else:
roo.pensize(2) # 设置画笔大小
roo.pencolor("yellow") # 画笔颜色
roo.forward(l) # 朝向
roo.left(30) # 移动
draw(3 * l / 4) # 绘制
roo.right(60) # 移动
draw(3 * l / 4) # 绘制
roo.left(30) # 移动
roo.pensize(2)
roo.backward(l) # 返回初始位置
draw(20) # 绘制20次
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor("magenta") # magenta
roo.forward(l)
roo.left(30)
draw(3 * l / 4)
roo.right(60)
draw(3 * l / 4)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(20)
roo.left(270)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor("red") # red
roo.forward(l)
roo.left(30)
draw(3 * l / 4)
roo.right(60)
draw(3 * l / 4)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(20)
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor('#FFF8DC') # white
roo.forward(l)
roo.left(30)
draw(3 * l / 4)
roo.right(60)
draw(3 * l / 4)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(20)
########################################################
def draw(l):
if (l < 10):
return
else:
roo.pensize(3)
roo.pencolor("lightgreen") # lightgreen
roo.forward(l)
roo.left(30)
draw(4 * l / 5)
roo.right(60)
draw(4 * l / 5)
roo.left(30)
roo.pensize(3)
roo.backward(l)
draw(40)
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(3)
roo.pencolor("red") # red
roo.forward(l)
roo.left(30)
draw(4 * l / 5)
roo.right(60)
draw(4 * l / 5)
roo.left(30)
roo.pensize(3)
roo.backward(l)
draw(40)
roo.left(270)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(3)
roo.pencolor("yellow") # yellow
roo.forward(l)
roo.left(30)
draw(4 * l / 5)
roo.right(60)
draw(4 * l / 5)
roo.left(30)
roo.pensize(3)
roo.backward(l)
draw(40)
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(3)
roo.pencolor('#FFF8DC') # white
roo.forward(l)
roo.left(30)
draw(4 * l / 5)
roo.right(60)
draw(4 * l / 5)
roo.left(30)
roo.pensize(3)
roo.backward(l)
draw(40)
########################################################
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor("cyan") # cyan
roo.forward(l)
roo.left(30)
draw(6 * l / 7)
roo.right(60)
draw(6 * l / 7)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(60)
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor("yellow") # yellow
roo.forward(l)
roo.left(30)
draw(6 * l / 7)
roo.right(60)
draw(6 * l / 7)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(60)
roo.left(270)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor("magenta") # magenta
roo.forward(l)
roo.left(30)
draw(6 * l / 7)
roo.right(60)
draw(6 * l / 7)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(60)
roo.right(90)
roo.speed(2000)
# recursion
def draw(l):
if (l < 10):
return
else:
roo.pensize(2)
roo.pencolor('#FFF8DC') # white
roo.forward(l)
roo.left(30)
draw(6 * l / 7)
roo.right(60)
draw(6 * l / 7)
roo.left(30)
roo.pensize(2)
roo.backward(l)
draw(60)
wn.exitonclick()
⑪ 计算器
Kivy是一个免费的开源Python库,可以快速轻松地开发高度交互的跨平台应用程序。
这里我将使用Python中的Kivy包来构建一个计算器GUI。
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
class myApp(App):
def build(self):
root_widget = BoxLayout(orientation='vertical')
output_label = Label(size_hint_y=0.75, font_size=50)
button_symbols = ('1', '2', '3', '+',
'4', '5', '6', '-',
'7', '8', '9', '.',
'0', '*', '/', '=')
button_grid = GridLayout(cols=4, size_hint_y=2)
for symbol in button_symbols:
button_grid.add_widget(Button(text=symbol))
clear_button = Button(text='Clear', size_hint_y=None, height=100)
def print_button_text(instance):
output_label.text += instance.text
for button in button_grid.children[1:]:
button.bind(on_press=print_button_text)
def resize_label_text(label, new_height):
label.fontsize = 0.5*label.height
output_label.bind(height=resize_label_text)
def evaluate_result(instance):
try:
output_label.text = str(eval(output_label.text))
except SyntaxError:
output_label.text = 'Python Syntax error!'
button_grid.children[0].bind(on_press=evaluate_result)
def clear_label(instance):
output_label.text = " "
clear_button.bind(on_press=clear_label)
root_widget.add_widget(output_label)
root_widget.add_widget(button_grid)
root_widget.add_widget(clear_button)
return root_widget
myApp().run()
⑫ 猜数游戏
猜数字游戏目的是猜测出程序想出的数字,基本逻辑:
- 程序随机选择1到100之间的一个数字或任何其他数字组合;
- 然后它会要求玩家输入它的建议;
- 然后它会检查这个数字是否与计算机随机生成的数字相同;如果是,则玩家获胜;
- 如果玩家的猜测不一样,那么它会检查数字是否高于或低于猜测并告诉玩家;
import random
# 创建随机数
n = random.randrange(1,100)
# 获取输入
guess = int(input("输入任意数值: "))
while n != guess: # 判断是否正确
# 小于
if guess < n:
print("太小了")
guess = int(input("再次输入数值: "))
# 大于
elif guess > n:
print("太大了!")
guess = int(input("再次输入数值: "))
else:
break
print("真棒,你猜对了!!")
⑬ 图像转换器
我们知道有大量的图像文件格式可用于存储图形数据,最流行的便是JPG和PNG。
使用Python中的Tkinter库和PIL库,创建一个将PNG图像转换为JPG的应用程序。
import tkinter as tk
from tkinter import filedialog
from PIL import Image
root = tk.Tk()
canvas1 = tk.Canvas(root, width=300, height=250, bg='azure3', relief='raised')
canvas1.pack()
label1 = tk.Label(root, text="图像转换器", bg='azure3')
label1.config(font=('helvetica', 20))
canvas1.create_window(150, 60, window=label1)
def getPNG():
global im1
import_file_path = filedialog.askopenfilename()
im1 = Image.open(import_file_path)
browse_png = tk.Button(text="选择PNG文件", command=getPNG, bg="royalblue", fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 130, window=browse_png)
def convert():
global im1
export_file_path = filedialog.asksaveasfilename(defaultextension='.jpg')
im1.save(export_file_path)
saveasbutton = tk.Button(text="转换PNG成JPG", command=convert, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 180, window=saveasbutton)
root.mainloop()
⑭ 重量转换器
重量换算是指单位值乘以标准换算值。
使用Python中的Tkinter库创建一个重量转换器应用程序。
from tkinter import *
# 创建一个GUI窗口
window = Tk()
def from_kg():
gram = float(e2_value.get())*1000
pound = float(e2_value.get())*2.20462
ounce = float(e2_value.get())*35.274
t1.delete("1.0", END)
t1.insert(END, gram)
t2.delete("1.0", END)
t2.insert(END, pound)
t3.delete("1.0", END)
t3.insert(END, ounce)
e1 = Label(window, text="输入重量(单位KG)")
e2_value = StringVar()
e2 = Entry(window, textvariable=e2_value)
e3 = Label(window, text="Gram")
e4 = Label(window, text="Pound")
e5 = Label(window, text="Ounce")
t1 = Text(window, height=5, width=30)
t2 = Text(window, height=5, width=30)
t3 = Text(window, height=5, width=30)
b1 = Button(window, text="Convert", command=from_kg)
e1.grid(row=0, column=0)
e2.grid(row=0, column=1)
e3.grid(row=1, column=0)
e4.grid(row=1, column=1)
e5.grid(row=1, column=2)
t1.grid(row=2, column=0)
t2.grid(row=2, column=1)
t3.grid(row=2, column=2)
b1.grid(row=0, column=2)
window.mainloop()
⑮ 年龄和性别检测
使用Python编程语言带你完成使用机器学习进行年龄和性别检测的任务。
首先需要编写用于检测人脸的代码,因为如果没有人脸检测,我们将无法进一步完成年龄和性别预测的任务。
下一步是预测图像中人的性别。在这里,我将性别网络加载到内存中,并将检测到的人脸通过网络传输,用于性别检测任务。
下一个任务是预测图像中人类的年龄。这里我将加载网络并使用前向传递来获取输出。由于网络架构与性别网络相似,我们可以充分利用所有输出来获得任务的预期年龄组来检测年龄。
import cv2 as cv
def getFaceBox(net, frame, conf_threshold=0.7):
# 获取位置
frameOpencvDnn = frame.copy()
frameHeight = frameOpencvDnn.shape[0]
frameWidth = frameOpencvDnn.shape[1]
blob = cv.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False)
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
cv.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight/150)), 8)
return frameOpencvDnn, bboxes
# 性别
genderProto = "gender_deploy.prototxt"
genderModel = "gender_net.caffemodel"
genderNet = cv.dnn.readNet(genderModel, genderProto)
# 性别参数
genderList = ['Male', 'Female']
# 年龄
ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"
ageNet = cv.dnn.readNet(ageModel, ageProto)
# 年龄参数
ageList = ['(0 - 2)', '(4 - 6)', '(8 - 12)', '(15 - 20)', '(25 - 32)', '(38 - 43)', '(48 - 53)', '(60 - 100)']
MODEL_MEAN_VALUES = (78.4263377603, 87.7689143744, 114.895847746)
padding = 20
# 人脸
faceProto = 'opencv_face_detector.pbtxt'
faceModel = 'opencv_face_detector_uint8.pb'
faceNet = cv.dnn.readNet(faceModel, faceProto)
# 读取图片
frame = cv.imread('image1.jpg')
frameFace, bboxes = getFaceBox(faceNet, frame)
for bbox in bboxes:
face = frame[max(0, bbox[1] - padding):min(bbox[3] + padding, frame.shape[0] - 1),
max(0, bbox[0] - padding):min(bbox[2] + padding, frame.shape[1] - 1)]
blob = cv.dnn.blobFromImage(face, 1, (227, 227), MODEL_MEAN_VALUES, swapRB=False)
genderNet.setInput(blob)
genderPreds = genderNet.forward()
gender = genderList[genderPreds[0].argmax()]
print("Gender Output : {}".format(genderPreds))
print("Gender : {}".format(gender))
ageNet.setInput(blob)
agePreds = ageNet.forward()
age = ageList[agePreds[0].argmax()]
print("Gender Output : {}".format(agePreds))
print("Gender : {}".format(age))
label = "{}, {}".format(gender, age)
cv.namedWindow("Age Gender Demo", 0)
cv.resizeWindow("Age Gender Demo", 900, 500)
cv.putText(frameFace, label, (bbox[0], bbox[1] - 20), cv.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 3, cv.LINE_AA)
cv.imshow("Age Gender Demo", frameFace)
cv.waitKey(0)
⑯ 人脸检测
构建一个检测人脸的程序是开始机器学习计算机视觉任务的好方法。
使用Python的OpenCV库进行人脸检测的任务。
import cv2
face_cascade = cv2.CascadeClassifier('face_detector.xml')
img = cv2.imread('image.jpg')
faces = face_cascade.detectMultiScale(img, 1.1, 10)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imwrite("face_detected.png", img)
print('Successfully saved')
⑰ 铅笔素描
使用不到20行的Python代码将图像转换为铅笔素描。
import cv2
image = cv2.imread("dog.jpg")
cv2.imshow("Dog", image)
cv2.waitKey(0)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("New Dog", gray_image)
cv2.waitKey(0)
inverted_image = 255 - gray_image
cv2.imshow("Inverted", inverted_image)
cv2.waitKey()
blurred = cv2.GaussianBlur(inverted_image, (21, 21), 0)
inverted_blurred = 255 - blurred
pencil_sketch = cv2.divide(gray_image, inverted_blurred, scale=256.0)
cv2.imshow("Sketch", pencil_sketch)
cv2.waitKey(0)
cv2.imshow("original image", image)
cv2.imshow("pencil sketch", pencil_sketch)
cv2.waitKey(0)
⑱ 文本编辑器
使用Python创建一个文本编辑器GUI,它可以创建、打开、编辑和保存文本文件。
所有小部件的排列方式应使按钮小部件位于窗口布局的左侧,而文本框小部件位于右侧。
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def open_file():
"""打开"""
filepath = askopenfilename(
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if not filepath:
return
txt_edit.delete(1.0, tk.END)
with open(filepath, "r") as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f"文本编辑器 - {filepath}")
def save_file():
"""保存"""
filepath = asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if not filepath:
return
with open(filepath, "w") as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f"文本编辑器 - {filepath}")
window = tk.Tk()
window.title("文本编辑器")
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)
txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="打开", command=open_file)
btn_save = tk.Button(fr_buttons, text="保存", command=save_file)
btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)
fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")
window.mainloop()
⑲ 图像分割
图像分割是机器视觉应用中将数字图像划分为一组像素的关键过程之一。
如果具有视觉的机器人是按颜色来计算糖果的数量,那么了解糖果之间的界限对它来说就很重要。
from skimage.io import imread
from skimage import color
import numpy as np
import matplotlib.pyplot as plt
# 读取图片
cimage = imread('photo.jpg')
fig, ax = plt.subplots(figsize=(20, 20))
ax.imshow(cimage)
ax.axis('off')
# RGB转为LAB
lab_img = color.rgb2lab(cimage)
x, y, z = lab_img.shape
# 显示颜色
to_plot = cimage.reshape(x * y, 3)
colors_map = to_plot.astype(np.float) / 256
# 创建数据
scatter_x = []
scatter_y = []
for xi in range(x):
for yi in range(y):
L_val = lab_img[xi, yi][0]
A_val = lab_img[xi, yi][1]
B_val = lab_img[xi, yi][2]
scatter_x.append(A_val)
scatter_y.append(B_val)
plt.figure(figsize=(20, 20))
plt.xlabel("a* from green to red")
plt.ylabel("b* from blue to yellow")
plt.scatter(scatter_x, scatter_y, c=colors_map)
# 显示
plt.show()
我们可以使用散点图,根据糖果的颜色对图像进行分割。
最后我们可以根据颜色,正确地分割图像中的糖果。
def filter_color(L_val_min, A_val_min, A_val_max, B_val_min, B_val_max):
filtered_image = np.copy(cimage)
for xi in range(x):
for yi in range(y):
L_val = lab_img[xi, yi][0]
A_val = lab_img[xi, yi][1]
B_val = lab_img[xi, yi][2]
if L_val > L_val_min and A_val > A_val_min and A_val < A_val_max and B_val > B_val_min and B_val < B_val_max:
pass
else:
filtered_image[xi, yi] = [255,255,255]
return filtered_image
lab_img = color.rgb2lab(cimage)
yellow = filter_color(70, -50, 0, 30, 100)
red = filter_color(30, 25, 100, 0, 100)
green = filter_color(50, -128, -20, 0, 50)
blue = filter_color(50, -40, 30, -128, -20)
white = filter_color(93, -25, 25, -25, 25)
pink = filter_color(50, 20, 128, -50, 0)
fig, ax = plt.subplots(nrows=3, ncols=2, figsize=(20,20))
ax[0][0].imshow(pink)
ax[0][0].set_title("pink Candies")
ax[0][0].axis('off')
ax[0][1].imshow(yellow)
ax[0][1].set_title("yellow Candies")
ax[0][1].axis('off')
ax[1][0].imshow(red)
ax[1][0].set_title("red Candies")
ax[1][0].axis('off')
ax[1][1].imshow(green)
ax[1][1].set_title("green Candies")
ax[1][1].axis('off')
ax[2][0].imshow(white)
ax[2][0].set_title("white Candies")
ax[2][0].axis('off')
ax[2][1].imshow(blue)
ax[2][1].set_title("blue Candies")
ax[2][1].axis('off')
plt.show()
⑳ 模拟时钟
使用Tkinter制作一个简单的模拟时钟GUI应用程序。
try:
import Tkinter
except:
import tkinter as Tkinter
import math
import time
class main(Tkinter.Tk):
def __init__(self):
Tkinter.Tk.__init__(self)
self.x = 150 # 中心点x坐标
self.y = 150 # 中心点y坐标
self.length = 50
self.creating_all_function_trigger()
# 触发器
def creating_all_function_trigger(self):
self.create_canvas_for_shapes()
self.creating_background_()
self.creating_sticks()
return
# 创建背景
def creating_background_(self):
self.image = Tkinter.PhotoImage(file='clock.gif')
self.canvas.create_image(150, 150, image=self.image)
return
# 创建画布
def create_canvas_for_shapes(self):
self.canvas = Tkinter.Canvas(self, bg='black')
self.canvas.pack(expand='yes', fill='both')
return
# 创建移动的线条
def creating_sticks(self):
self.sticks = []
for i in range(3):
store = self.canvas.create_line(self.x, self.y, self.x+self.length, self.y+self.length, width=2, fill='red')
self.sticks.append(store)
return
# 定期刷新
def update_class(self):
now = time.localtime()
t = time.strptime(str(now.tm_hour), "%H")
hour = int(time.strftime("%I", t))*5
now = (hour, now.tm_min, now.tm_sec)
# 改变坐标
for n, i in enumerate(now):
x, y = self.canvas.coords(self.sticks[n])[0:2]
cr = [x, y]
cr.append(self.length*math.cos(math.radians(i*6)-math.radians(90))+self.x)
cr.append(self.length*math.sin(math.radians(i*6)-math.radians(90))+self.y)
self.canvas.coords(self.sticks[n], tuple(cr))
return
if __name__ == '__main__':
root = main()
while True:
root.update()
root.update_idletasks()
root.update_class()
四.总结
好了,以上就是今天分享的内容,大家可以自行去动手练习。
用到了不少的Python库,大家直接pip安装即可,下面是示例。
pip安装
pip install opencv-python -i https://simple.baidu.com/pypi...
顺便给大家推荐一些Python爬虫视频教程,希望对大家有所帮助:
https://www.bilibili.com/vide...
对文章有问题的,或者有其他关于python的问题,可以在评论区留言哦
觉得我分享的文章不错的话,可以关注一下我,或者给文章点赞(/≧▽≦)/