欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

精選20個(gè)好玩又實(shí)用的的Python實(shí)戰(zhàn)項(xiàng)目(有圖文代碼)

 更新時(shí)間:2025年08月02日 11:43:15   作者:小魚Python  
文章介紹了20個(gè)實(shí)用Python項(xiàng)目,涵蓋游戲開發(fā)、工具應(yīng)用、圖像處理、機(jī)器學(xué)習(xí)等,使用Tkinter、PIL、OpenCV、Kivy等庫實(shí)現(xiàn)功能,適合學(xué)習(xí)和練習(xí),項(xiàng)目包括猜字游戲、鬧鐘、二維碼生成、語言檢測(cè)、音樂播放器等,用戶可直接pip安裝所需庫并動(dòng)手實(shí)踐

今天給大家介紹20個(gè)非常實(shí)用的Python項(xiàng)目,幫助大家更好的學(xué)習(xí)Python。

① 猜字游戲

在這個(gè)游戲中,你必須一個(gè)字母一個(gè)字母的猜出秘密單詞。

如果你猜錯(cuò)了一個(gè)字母,你將丟掉一條命。

正如游戲名那樣,你需要仔細(xì)選擇字母,因?yàn)槟愕纳鼣?shù)量非常有限。

import random

# 生命次數(shù)
lives = 3

# 神秘單詞, 隨機(jī)選擇
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('剩余生命次數(shù): ' + heart_symbol * lives)
    guess = input('猜測(cè)字母或者是整個(gè)單詞: ')

    if guess == secret_word:
        guessed_word_correctly = True
        break

    if guess in secret_word:
        update_clue(guess, secret_word, clue)
    else:
        print('錯(cuò)誤。你丟了一條命\n')
        lives = lives - 1


if guessed_word_correctly:
    print('你贏了! 秘密單詞是 ' + secret_word)
else:
    print('你輸了! 秘密單詞是 ' + secret_word)

下面就來玩一下。

② 鬧鐘

鬧鐘是一種具有可以在預(yù)先設(shè)定的時(shí)間被激活以響鈴的功能的時(shí)鐘,用于喚醒打工人們。

使用Python中的DateTime模塊來創(chuàng)建鬧鐘,并用Python中的playsound庫來播放鬧鐘聲音。

from datetime import datetime
from playsound import playsound

# 輸入
alarm_time = input("請(qǐng)輸入鬧鐘時(shí)間, 示例: 09:50:00 am\n")
# 時(shí)
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("完成鬧鐘設(shè)置..")

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")

    # 時(shí)間判斷
    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

測(cè)試一下,設(shè)置一個(gè)鬧鐘,到指定時(shí)間就會(huì)有音樂響起。

③ 骰子模擬器

可以通過選擇1到6之間的隨機(jī)整數(shù),來完成骰子模擬。

import random

# 設(shè)置最大值和最小值
min_val = 1
max_val = 6

# 是否繼續(xù)
roll_again = "yes"

# 循環(huán)
while roll_again == "yes" or roll_again == "y":
    print("開始擲骰子")
    print("骰子數(shù)值是 :")

    # 第一輪
    print(random.randint(min_val, max_val))

    # 第二輪
    print(random.randint(min_val, max_val))

    # 是否繼續(xù)
    roll_again = input("是否繼續(xù)擲骰子?(是的話, 輸入yes或者y)")

使用random.randint()函數(shù)。函數(shù)根據(jù)我們指定的開始和結(jié)束范圍返回一個(gè)隨機(jī)整數(shù)。

④ 二維碼

二維碼是用于將數(shù)據(jù)編碼和解碼為機(jī)器可讀的方法。

包含一個(gè)白色背景上的黑色方塊網(wǎng)格,可以被任何成像設(shè)備(如手機(jī))讀取,并進(jìn)行處理以從圖案中提取所需的數(shù)據(jù)。

import pyqrcode

# 設(shè)置二維碼信息
s = "https://www.baidu.com"

# 生成二維碼
url = pyqrcode.create(s)

# 保存二維碼
url.svg("baidu.svg", scale=8)

結(jié)果如下。

⑤ 語言檢測(cè)

當(dāng)你需要處理包含不同語言數(shù)據(jù),且數(shù)據(jù)非常大的時(shí)候,語言檢測(cè)就派上用場(chǎng)了。

使用Python中的langdetect包,可以在幾行代碼內(nèi)檢測(cè)超過55種不同的語言。

from langdetect import detect

text = input("輸入信息: ")
print(detect(text))

示例。

⑥ 加密和解密

密碼術(shù)意味著更改消息的文本,以便不知道你秘密的人永遠(yuǎn)不會(huì)理解你的消息。

下面就來創(chuàng)建一個(gè)GUI應(yīng)用程序,使用Python進(jìn)行加密和解密。

在這里,我們需要編寫使用無限循環(huán)的代碼,代碼將不斷詢問用戶是否要加密或解密消息。

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('任務(wù)', '你是否想要加密或解密信息?')
    return task


def get_message():
    message = simpledialog.askstring('信息', '輸入相關(guān)信息: ')
    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縮短

短網(wǎng)址由于易于記憶和輸入,因此在數(shù)字營銷領(lǐng)域非常受歡迎。

這里給大家介紹一下,如何使用Python創(chuàng)建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()

運(yùn)行代碼,輸出如下。

# 輸出
https://tinyurl.com/y4z6z2gq

⑧ 音樂播放器

音樂播放器,可讓你快速輕松地管理和收聽所有音樂文件。

應(yīng)該不少小伙伴都使用過,網(wǎng)易云音樂、QQ音樂、酷狗音樂等。

這里小F將使用Pygame和Tkinter,來創(chuàng)建一個(gè)音樂播放器。

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()

選擇音樂文件所在的文件夾,點(diǎn)擊播放,即可聽見音樂。

⑨ 生命游戲

生命游戲由英國數(shù)學(xué)家約翰·H·康威設(shè)計(jì)的,是一種類似于生物社會(huì)的興衰和交替的游戲。

游戲使用無限大小的矩形網(wǎng)格,其中每個(gè)網(wǎng)格都是空的或被有機(jī)體占據(jù)。被占用的細(xì)胞是活的,而空的細(xì)胞是死的。

游戲在特定時(shí)期內(nèi)進(jìn)行,每一輪都會(huì)根據(jù)當(dāng)前配置中生物體的排列創(chuàng)建一個(gè)新的世代。

下一代網(wǎng)格的狀態(tài),是通過將以下四個(gè)基本規(guī)則應(yīng)用于當(dāng)前配置的每個(gè)網(wǎng)格來確定的:

  • 如果一個(gè)細(xì)胞還活著并且有兩個(gè)或三個(gè)活著的鄰居,那么該細(xì)胞在下一代中仍然活著;

  • 一個(gè)沒有活鄰居或只有一個(gè)活鄰居的活細(xì)胞會(huì)在下一代死于孤立;

  • 有四個(gè)或更多活鄰居的活細(xì)胞會(huì)因下一代人口過剩而死亡;

  • 一個(gè)只有三個(gè)活著的鄰居的死細(xì)胞會(huì)導(dǎo)致出生并在下一代中存活;

board = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

# 鄰居數(shù)組為給定的單元格找到8個(gè)相鄰的單元格
neighbors = [(1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1)]

rows = len(board)
cols = len(board[0])

# 創(chuàng)建一個(gè)原始板的副本
copy_board = [[board[row][col] for col in range(cols)] for row in range(rows)]

# 逐個(gè)單元地迭代
for row in range(rows):
    for col in range(cols):

        # 對(duì)于每個(gè)單元計(jì)算鄰居的數(shù)量
        live_neighbors = 0
        for neighbor in neighbors:

            r = (row + neighbor[0])
            c = (col + neighbor[1])

            # 檢查相鄰細(xì)胞的有效性,以及它是否原來是一個(gè)活細(xì)胞
            # 評(píng)估是針對(duì)副本進(jìn)行的,因?yàn)樗肋h(yuǎn)不會(huì)更新。
            if (r < rows and r >= 0) and (c < cols and c >= 0) and (copy_board[r][c] == 1):
                live_neighbors += 1

        # 規(guī)則1或規(guī)則3
        if copy_board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
            board[row][col] = 0
        # 規(guī)則4
        if copy_board[row][col] == 0 and live_neighbors == 3:
            board[row][col] = 1

print(board)

結(jié)果如下。

# 輸入
board = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

# 輸出
board = [[0, 0, 0], [1, 1, 0], [0, 0, 0]]

⑩ Turtle繪圖

Turtle模塊提供了在二維平面上移動(dòng)的環(huán)境。

Turtle可以實(shí)現(xiàn)位置、航向和各種可能的狀態(tài)和動(dòng)作。

import turtle as tu

roo = tu.Turtle()  # 創(chuàng)建對(duì)象
wn = tu.Screen()  # 屏幕對(duì)象
wn.bgcolor("black")  # 屏幕背景
wn.title("分形樹")
roo.left(90)  # 移動(dòng)
roo.speed(20)  # 速度


def draw(l):  # 以長(zhǎng)度'l'作為參數(shù)的遞歸函數(shù)
    if l < 10:
        return
    else:
        roo.pensize(2)  # 設(shè)置畫筆大小
        roo.pencolor("yellow")  # 畫筆顏色
        roo.forward(l)  # 朝向
        roo.left(30)  # 移動(dòng)
        draw(3 * l / 4)  # 繪制
        roo.right(60)  # 移動(dòng)
        draw(3 * l / 4)  # 繪制
        roo.left(30)  # 移動(dòng)
        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()


繪制時(shí)間較長(zhǎng),結(jié)果如下,挺好看的。

? 計(jì)算器

Kivy是一個(gè)免費(fèi)的開源Python庫,可以快速輕松地開發(fā)高度交互的跨平臺(tái)應(yīng)用程序。

這里我將使用Python中的Kivy包來構(gòu)建一個(gè)計(jì)算器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()

運(yùn)行代碼,出現(xiàn)一個(gè)計(jì)算器,非常好用!

? 猜數(shù)游戲

猜數(shù)字游戲目的是猜測(cè)出程序想出的數(shù)字,基本邏輯:

  • 程序隨機(jī)選擇1到100之間的一個(gè)數(shù)字或任何其他數(shù)字組合;
  • 然后它會(huì)要求玩家輸入它的建議;
  • 然后它會(huì)檢查這個(gè)數(shù)字是否與計(jì)算機(jī)隨機(jī)生成的數(shù)字相同;如果是,則玩家獲勝;
  • 如果玩家的猜測(cè)不一樣,那么它會(huì)檢查數(shù)字是否高于或低于猜測(cè)并告訴玩家;
import random

# 創(chuàng)建隨機(jī)數(shù)
n = random.randrange(1,100)
# 獲取輸入
guess = int(input("輸入任意數(shù)值: "))

while n != guess: # 判斷是否正確
    # 小于
    if guess < n:
        print("太小了")
        guess = int(input("再次輸入數(shù)值: "))
    # 大于
    elif guess > n:
        print("太大了!")
        guess = int(input("再次輸入數(shù)值: "))
    else:
        break
print("真棒,你猜對(duì)了!!")

運(yùn)行代碼,結(jié)果展示

? 圖像轉(zhuǎn)換器

我們知道有大量的圖像文件格式可用于存儲(chǔ)圖形數(shù)據(jù),最流行的便是JPG和PNG。

使用Python中的Tkinter庫和PIL庫,創(chuàng)建一個(gè)將PNG圖像轉(zhuǎn)換為JPG的應(yīng)用程序。

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="圖像轉(zhuǎn)換器", 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="轉(zhuǎn)換PNG成JPG", command=convert, bg='royalblue', fg='white', font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 180, window=saveasbutton)
root.mainloop()

運(yùn)行代碼,選擇圖片,點(diǎn)擊轉(zhuǎn)換按鈕,即可完成圖像格式變換。

? 重量轉(zhuǎn)換器

重量換算是指單位值乘以標(biāo)準(zhǔn)換算值。

使用Python中的Tkinter庫創(chuàng)建一個(gè)重量轉(zhuǎn)換器應(yīng)用程序。

from tkinter import *

# 創(chuàng)建一個(gè)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()

運(yùn)行代碼,出現(xiàn)界面,輸入數(shù)值,點(diǎn)擊轉(zhuǎn)換。

? 年齡和性別檢測(cè)

使用Python編程語言帶你完成使用機(jī)器學(xué)習(xí)進(jìn)行年齡和性別檢測(cè)的任務(wù)。

首先需要編寫用于檢測(cè)人臉的代碼,因?yàn)槿绻麤]有人臉檢測(cè),我們將無法進(jìn)一步完成年齡和性別預(yù)測(cè)的任務(wù)。

下一步是預(yù)測(cè)圖像中人的性別。在這里,我將性別網(wǎng)絡(luò)加載到內(nèi)存中,并將檢測(cè)到的人臉通過網(wǎng)絡(luò)傳輸,用于性別檢測(cè)任務(wù)。

下一個(gè)任務(wù)是預(yù)測(cè)圖像中人類的年齡。這里我將加載網(wǎng)絡(luò)并使用前向傳遞來獲取輸出。由于網(wǎng)絡(luò)架構(gòu)與性別網(wǎng)絡(luò)相似,我們可以充分利用所有輸出來獲得任務(wù)的預(yù)期年齡組來檢測(cè)年齡。

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)
# 性別參數(shù)
genderList = ['Male', 'Female']

# 年齡
ageProto = "age_deploy.prototxt"
ageModel = "age_net.caffemodel"
ageNet = cv.dnn.readNet(ageModel, ageProto)
# 年齡參數(shù)
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)

運(yùn)行代碼,結(jié)果如下。

? 人臉檢測(cè)

構(gòu)建一個(gè)檢測(cè)人臉的程序是開始機(jī)器學(xué)習(xí)計(jì)算機(jī)視覺任務(wù)的好方法。

使用Python的OpenCV庫進(jìn)行人臉檢測(cè)的任務(wù)。

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代碼將圖像轉(zhuǎn)換為鉛筆素描。

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)

結(jié)果如下。

? 文本編輯器

使用Python創(chuàng)建一個(gè)文本編輯器GUI,它可以創(chuàng)建、打開、編輯和保存文本文件。

所有小部件的排列方式應(yīng)使按鈕小部件位于窗口布局的左側(cè),而文本框小部件位于右側(cè)。

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()

結(jié)果如下。

? 圖像分割

圖像分割是機(jī)器視覺應(yīng)用中將數(shù)字圖像劃分為一組像素的關(guān)鍵過程之一。

看看下面的圖片,糖果按特定順序排列形成一個(gè)詞。

如果具有視覺的機(jī)器人是按顏色來計(jì)算糖果的數(shù)量,那么了解糖果之間的界限對(duì)它來說就很重要。

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轉(zhuǎn)為L(zhǎng)AB
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

# 創(chuàng)建數(shù)據(jù)
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()

我們可以使用散點(diǎn)圖,根據(jù)糖果的顏色對(duì)圖像進(jìn)行分割。

最后我們可以根據(jù)顏色,正確地分割圖像中的糖果。

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()


? 模擬時(shí)鐘

使用Tkinter制作一個(gè)簡(jiǎn)單的模擬時(shí)鐘GUI應(yīng)用程序。

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  # 中心點(diǎn)x坐標(biāo)
        self.y = 150  # 中心點(diǎn)y坐標(biāo)
        self.length = 50
        self.creating_all_function_trigger()

    # 觸發(fā)器
    def creating_all_function_trigger(self):
        self.create_canvas_for_shapes()
        self.creating_background_()
        self.creating_sticks()
        return

    # 創(chuàng)建背景
    def creating_background_(self):
        self.image = Tkinter.PhotoImage(file='clock.gif')
        self.canvas.create_image(150, 150, image=self.image)
        return

    # 創(chuàng)建畫布
    def create_canvas_for_shapes(self):
        self.canvas = Tkinter.Canvas(self, bg='black')
        self.canvas.pack(expand='yes', fill='both')
        return

    # 創(chuàng)建移動(dòng)的線條
    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)
        # 改變坐標(biāo)
        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()

結(jié)果如下。

總結(jié)

好了,以上就是今天分享的內(nèi)容,大家可以自行去動(dòng)手練習(xí)。

到此這篇關(guān)于精選20個(gè)好玩又實(shí)用的的Python實(shí)戰(zhàn)項(xiàng)目(有圖文代碼)的文章就介紹到這了,更多相關(guān)20個(gè)好玩又實(shí)用的的Python項(xiàng)目?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python asyncio常用函數(shù)使用詳解

    Python asyncio常用函數(shù)使用詳解

    Asyncio在經(jīng)過一段時(shí)間的發(fā)展以及獲取Curio等第三方庫的經(jīng)驗(yàn)來提供更多的功能,目前高級(jí)功能也基本完善,但是相對(duì)于其他語言,Python的Asyncio高級(jí)功能還是不夠的,但好在Asyncio的低級(jí)API也比較完善
    2023-03-03
  • python 去除二維數(shù)組/二維列表中的重復(fù)行方法

    python 去除二維數(shù)組/二維列表中的重復(fù)行方法

    今天小編就為大家分享一篇python 去除二維數(shù)組/二維列表中的重復(fù)行方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • python geemap的安裝步驟及環(huán)境配置

    python geemap的安裝步驟及環(huán)境配置

    geemap是基于GEE由吳秋生老師二次開發(fā)的一個(gè)包,geemap主要使用python來進(jìn)行實(shí)現(xiàn)相關(guān)功能,這篇文章主要介紹了geemap的詳細(xì)安裝步驟及環(huán)境配置,需要的朋友可以參考下
    2022-08-08
  • Python中關(guān)鍵字nonlocal和global的聲明與解析

    Python中關(guān)鍵字nonlocal和global的聲明與解析

    這篇文章主要給大家介紹了關(guān)于Python中關(guān)鍵字nonlocal和global的聲明與解析的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來一起看看吧。
    2017-03-03
  • pytorch 輸出中間層特征的實(shí)例

    pytorch 輸出中間層特征的實(shí)例

    今天小編就為大家分享一篇pytorch 輸出中間層特征的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Django重設(shè)Admin密碼過程解析

    Django重設(shè)Admin密碼過程解析

    這篇文章主要介紹了Django重設(shè)Admin密碼過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-02-02
  • 定位python內(nèi)存泄漏問題及解決

    定位python內(nèi)存泄漏問題及解決

    這篇文章主要介紹了定位python內(nèi)存泄漏問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • Python入門之pip永久鏡像源的配置方法

    Python入門之pip永久鏡像源的配置方法

    這篇文章主要為大家詳細(xì)介紹了國內(nèi)幾個(gè)好用的Python鏡像服務(wù)器地址,如清華,阿里云等,還說明了臨時(shí)和永久鏡像源的配置方法,希望對(duì)大家有一定的幫助
    2025-05-05
  • 使用Python開發(fā)Markdown兼容公式格式轉(zhuǎn)換工具

    使用Python開發(fā)Markdown兼容公式格式轉(zhuǎn)換工具

    在技術(shù)寫作中我們經(jīng)常遇到公式格式問題,例如MathML無法顯示,LaTeX格式錯(cuò)亂等,所以本文我們將使用Python開發(fā)Markdown兼容公式格式轉(zhuǎn)換工具,有需要的小伙伴可以了解下
    2025-05-05
  • python驗(yàn)證碼識(shí)別教程之滑動(dòng)驗(yàn)證碼

    python驗(yàn)證碼識(shí)別教程之滑動(dòng)驗(yàn)證碼

    這篇文章主要給大家介紹了關(guān)于python驗(yàn)證碼識(shí)別教程之滑動(dòng)驗(yàn)證碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-06-06

最新評(píng)論