分类 python相关 下的文章

Ubuntu下有多种Python虚拟环境管理软件,常见的有以下几种:

  • venv:Python 3.3及以上版本内置的官方模块,无需额外安装。使用简单,通过 python3 -m venv <环境名称> 即可创建虚拟环境,激活后可独立安装包,不影响系统全局环境。
  • virtualenv:功能更强大灵活的第三方库,需使用 pip3 install virtualenv 安装。它支持创建不同Python版本的虚拟环境,创建命令如 virtualenv --no - site - packages <环境名称> 。
  • pipenv:集成了pip和virtualenv功能的命令行工具,通过 pip3 install pipenv 安装。它能自动创建和管理虚拟环境,通过Pipfile和Pipfile.lock文件锁定包版本和依赖信息,适合管理复杂项目依赖。
  • uv:基于Rust编写,不仅支持虚拟环境管理,还能进行包管理、多Python版本管理等。可使用 sudo pip3 install uv 安装,功能较为全面。
  • conda:Anaconda发行版中的环境管理工具,适合数据科学项目,可创建、删除、切换虚拟环境,还能管理包依赖,通过 conda create 等命令操作。

Anaconda有Ubuntu下的版本。可从Anaconda官网下载适用于Ubuntu的64位安装包,通常为.sh格式脚本文件,下载后通过 bash <安装包名称>.sh 命令进行安装。

在Ubuntu下有许多免费好用的Python编辑软件,以下是一些推荐:

  • PyCharm社区版:由JetBrains开发,是一款专业的Python IDE。它提供代码自动补全、调试、版本控制集成等功能,还支持远程开发与Web框架集成。社区版免费,适合基础开发,能满足大多数Python开发者的日常需求,安装命令为“sudo snap install pycharm-community --classic”。
  • Visual Studio Code:轻量级编辑器,通过安装Python扩展后,可支持智能提示、调试、Jupyter Notebook集成等功能,资源消耗低。其插件生态丰富,能通过Python、Jupyter、Pylance等插件构建完整开发环境,适合Web与数据科学等多种场景,可从官网下载deb包安装。
  • Spyder:专为科学计算设计,集成了变量查看器、交互式控制台,具有MATLAB风格界面,对NumPy/SciPy生态支持良好,适合从事科学计算、数据分析相关工作的人员使用,可以通过Ubuntu软件中心或命令行安装。
  • Thonny:界面简洁直观,内置简单调试器与包管理工具,主要面向Python新手,适合教学与快速原型开发,对于初学者快速上手Python编程非常友好,可在Ubuntu中通过包管理工具安装。
  • Geany:资源占用低,支持多语言,适合在服务器端或老旧设备上进行轻量开发,如果你需要在配置较低的设备上进行Python编程,Geany是一个不错的选择,可通过命令行安装,如“sudo apt - get install geany”。

即使安装了系统依赖,pygobject 在 ARM 系统上可能还是会出问题。让我们直接使用更简单可靠的解决方案:

方案 1: 使用 pygame (最推荐)

bash

pip install pygame

python

import pygame
import time

def play_audio(file_path, duration_ms):

try:
    # 初始化 pygame 混音器
    pygame.mixer.init()
    
    # 加载并播放文件
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play()
    
    print(f"正在播放: {file_path}, 时长: {duration_ms}ms")
    
    # 等待指定时长
    start_time = time.time()
    while (time.time() - start_time) * 1000 < duration_ms:
        if not pygame.mixer.music.get_busy():
            break  # 如果播放提前结束就退出
        time.sleep(0.1)
        
    print("播放完成")
    
except Exception as e:
    print(f"播放音频出错: {e}")
finally:
    # 确保停止播放并清理资源
    if pygame.mixer.get_init():
        pygame.mixer.music.stop()
        pygame.mixer.quit()

使用示例

play_audio("/mnt/sda/music/chanfu.mp4", 1000)

方案 2: 使用系统音频播放器 (最稳定)

bash

安装 mpg123 (支持 MP3/MP4)

sudo apt install mpg123

或者安装 ffmpeg (功能更全面)

sudo apt install ffmpeg

python

import subprocess
import time
import os

def play_audio(file_path, duration_ms):

"""使用系统音频播放器"""
if not os.path.exists(file_path):
    print(f"文件不存在: {file_path}")
    return False
    
try:
    duration_sec = duration_ms / 1000
    
    # 检查可用的播放器
    players = [
        ('mpg123', ['mpg123', '-q', file_path]),
        ('ffplay', ['ffplay', '-nodisp', '-autoexit', file_path]),
        ('mplayer', ['mplayer', file_path])
    ]
    
    for player_name, cmd in players:
        try:
            # 检查播放器是否可用
            subprocess.run(['which', player_name], check=True, capture_output=True)
            print(f"使用 {player_name} 播放音频...")
            
            # 启动播放进程
            process = subprocess.Popen(cmd)
            
            # 等待指定时长
            time.sleep(duration_sec)
            
            # 停止播放
            process.terminate()
            process.wait(timeout=2)
            
            print("播放完成")
            return True
            
        except subprocess.CalledProcessError:
            continue  # 播放器不可用,尝试下一个
        except subprocess.TimeoutExpired:
            process.kill()  # 强制结束
            process.wait()
            
    print("没有找到可用的音频播放器,请安装 mpg123 或 ffmpeg")
    return False
    
except Exception as e:
    print(f"播放音频出错: {e}")
    return False

使用示例

play_audio("/mnt/sda/music/chanfu.mp4", 1000)

方案 3: 使用 pydub + simpleaudio

bash

安装必要的包

sudo apt install ffmpeg
pip install pydub simpleaudio

python

from pydub import AudioSegment
from pydub.playback import play
import time

def play_audio(file_path, duration_ms):

try:
    # 加载音频文件
    print(f"加载音频文件: {file_path}")
    audio = AudioSegment.from_file(file_path)
    
    # 如果音频长度超过指定时长,进行裁剪
    if len(audio) > duration_ms:
        audio = audio[:duration_ms]
        print(f"音频已裁剪至 {duration_ms}ms")
    
    print("开始播放...")
    # 播放音频
    play(audio)
    print("播放完成")
    
except Exception as e:
    print(f"播放音频出错: {e}")

使用示例

play_audio("/mnt/sda/music/chanfu.mp4", 1000)

方案 4: 使用 vlc (功能强大)

bash

pip install python-vlc

python

import vlc
import time

def play_audio(file_path, duration_ms):

try:
    # 创建 VLC 实例
    instance = vlc.Instance('--no-xlib --quiet')  # 禁用图形界面
    player = instance.media_player_new()
    
    # 设置媒体文件
    media = instance.media_new(file_path)
    player.set_media(media)
    
    print(f"开始播放: {file_path}")
    # 开始播放
    player.play()
    
    # 等待播放开始
    time.sleep(0.5)
    
    # 等待指定时长
    time.sleep(duration_ms / 1000)
    
    # 停止播放
    player.stop()
    print("播放完成")
    
except Exception as e:
    print(f"播放音频出错: {e}")

使用示例

play_audio("/mnt/sda/music/chanfu.mp4", 1000)

快速测试脚本
python

def test_all_methods():

"""测试所有可用的音频播放方法"""
file_path = "/mnt/sda/music/chanfu.mp4"
duration_ms = 1000

methods = [
    ("pygame", play_audio_pygame),
    ("system_player", play_audio_system),
    ("pydub", play_audio_pydub),
    ("vlc", play_audio_vlc)
]

for name, method in methods:
    print(f"\n=== 测试 {name} ===")
    try:
        method(file_path, duration_ms)
        print(f"✓ {name} 工作正常")
    except Exception as e:
        print(f"✗ {name} 失败: {e}")

运行测试

test_all_methods()

我的建议

直接使用方案 1 (pygame),因为:

安装简单:pip install pygame

跨平台兼容性好

不需要复杂的系统依赖

代码简洁易用

如果 pygame 不工作,使用方案 2 (系统播放器),安装 mpg123 或 ffmpeg 即可。

不要再折腾 pygobject 了,它在 ARM 系统上依赖太多,容易出问题。

将本地项目首次推送到 GitHub 的过程分为两个主要部分:本地初始化 Git 仓库 和 连接到远程 GitHub 仓库。

以下是完整的命令行步骤:

第 1 步:在 GitHub 上创建新的远程仓库

首先,你需要一个空的 GitHub 仓库来接收你的本地代码。

登录 GitHub 账户。

点击右上角的 “+”号,选择 “New repository”(新建仓库)。

填写仓库信息:

Repository name(仓库名): 填写你的项目名称(例如:publicdouyin)。

Description (Optional)(描述): 简要描述你的项目。

Public/Private(公开/私有): 根据需要选择。

重要提示: 在创建时,不要 勾选初始化 README、.gitignore 或 License 文件的选项。你需要创建一个完全空的仓库,以便后续推送本地内容。

点击 “Create repository”(创建仓库)。

创建成功后,GitHub 页面会显示一系列快速设置的命令,你需要复制其中的远程仓库 URL(通常以 .git 结尾)。

第 2 步:在本地项目目录中初始化 Git

现在,切换到你的本地项目目录 (D:\PythonProject\publicdouyin),并使用 Git 初始化项目。

打开终端/命令行工具 (Git Bash, CMD, 或 PowerShell)。

进入项目目录:

Bash

cd D:\PythonProject\publicdouyin
初始化 Git 仓库:

Bash

git init
这会在你的项目目录中创建一个 .git 隐藏文件夹。

添加所有文件到暂存区:

Bash

git add .
提交更改:

Bash

git commit -m "Initial commit of the project"
这是你项目历史中的第一个记录点。

第 3 步:关联远程仓库并推送

现在本地仓库已经准备好了,将其连接到你在 GitHub 上创建的空仓库。

关联远程仓库:
使用你在第 1 步中复制的 GitHub 仓库 URL 替换下面的 <远程仓库URL>。

Bash

git remote add origin <远程仓库URL>
示例: git remote add origin https://github.com/qianlongzaiyuan76/publicdouyin.git
origin 是这个远程仓库的默认别名。

设置分支名称(如果需要):
如果你的本地分支名称是 master,但你想推送到 main (GitHub 默认),请重命名你的本地分支:

Bash

git branch -M main
如果你在初始化时就使用了较新版本的 Git,你的分支可能已经是 main。

推送项目到 GitHub:
执行推送操作,-u (或 --set-upstream) 参数会记住你本地的 main 分支应该追踪远程的 origin/main 分支。

Bash

git push -u origin main
成功!
如果一切顺利,命令行会提示推送成功。此时,刷新你的 GitHub 仓库页面,你将看到本地项目的所有文件。

注意: 首次推送时,Git 可能会要求你输入 GitHub 用户名和密码,或者使用 Personal Access Token (PAT)。如果你遇到身份验证问题,建议使用 PAT。

常见问题

如果在github上在创建时,勾选了初始化 README、.gitignore 或 License 文件的选项。会提示出错,该问题应该如下解决
你正在按正确的步骤操作,但你的 Git 流程中出现了一个新的问题,这与你之前遇到的问题类似,但原因稍有不同。

错误分析 🔎

你遇到的最新错误是:

! [rejected] main -> main (non-fast-forward)

原因:

这个错误意味着你的本地 main 分支落后于远程的 main 分支。通常发生在以下两种情况:

远程仓库不是完全空的。 你可能在 GitHub 上创建仓库时勾选了 初始化 README、.gitignore 或 License 文件。这导致远程仓库有了第一次提交,而你的本地仓库没有。

你或其他人在上次操作后直接在 GitHub 网页上修改了文件。

无论是哪种情况,你的本地历史记录(Initial commit)和远程历史记录(Initial commit + README)现在是分叉的。Git 拒绝你的推送,因为它会覆盖远程的提交。

解决方案 🛠️

你仍然需要先拉取(pull)远程的更改,然后才能推送你的本地提交。

步骤 1: 拉取并合并远程更改

使用 git pull 命令来获取远程的 main 分支,并将其与你的本地 main 分支合并。

Bash

git pull origin main --allow-unrelated-histories
为什么要加 --allow-unrelated-histories?
因为你的本地仓库和远程仓库是独立创建的(一个是你本地的 git init,一个是 GitHub 上的初始化提交),它们的历史记录起点不同。Git 默认会阻止这种合并,但在这个首次推送的场景中,你需要明确告诉 Git 允许将这两个不相关的历史记录合并在一起。

步骤 2: 再次推送

在拉取并成功合并后,你的本地 main 分支现在包含了所有远程的更改以及你自己的提交。这时你就可以安全地推送了。

Bash

git push -u origin main
关于你的其他命令 📝
git remote add origin ... ➜ error: remote origin already exists.

这是正常的! 在你之前的操作中,你已经成功设置了 origin 这个远程别名,所以 Git 提示你它已经存在,无需再次添加。

git branch -M main 和 git branch

操作正确! 你已经成功地将本地主分支重命名并切换到了标准的 main 分支,这消除了之前可能存在的 master 分支问题。

下一步就是执行上面的拉取和推送步骤。

如果提示错误error: remote origin already exists. 该如何操作?

这个错误信息 error: remote origin already exists. 很好理解,它不是一个严重的问题,而是 Git 在告诉你:

你试图用 git remote add origin ... 命令添加一个名为 origin 的远程仓库,但这个名称的远程仓库已经存在了。

解决方案和解释 💡

1. 为什么会出现这个错误?

在你之前的操作中,你已经通过命令(可能是这次或更早的尝试)将本地仓库关联到了 GitHub 上的远程仓库,并给它起了个别名 origin。

2. 你该怎么做?

你不需要再添加了。你可以跳过这一步,直接进行下一步操作(通常是拉取或推送)。

3. 如何验证 origin 是否正确?

如果你不确定现有的 origin 是否指向了正确的 GitHub 地址,可以使用以下命令查看:

Bash

git remote -v
输出示例(正确的):

origin https://github.com/qianlongzaiyuan76/publicdouyin.git (fetch)
origin https://github.com/qianlongzaiyuan76/publicdouyin.git (push)
如果输出的地址是你想要的,那么你就可以直接使用 git pull 或 git push 命令了。

4. 假如地址是错的怎么办?

如果你发现 origin 指向的地址是错的,你可以使用 git remote set-url 命令来修正它,而不是使用 git remote add:

Bash

修正 origin 的 URL

git remote set-url origin https://github.com/qianlongzaiyuan76/publicdouyin
或者,你也可以选择先删除旧的 origin,再重新添加:

Bash

1. 删除现有的 origin

git remote remove origin

2. 重新添加正确的 origin

git remote add origin https://github.com/qianlongzaiyuan76/publicdouyin

如果上传超时怎么处理?

解决方案 (Solutions) 🛠️

1. 增加 Git 缓冲区大小 (Increase Git Buffer Size)

This is the most common fix for large pushes over HTTPS, as it gives the transfer more time before the server or client times out.

Bash

git config --global http.postBuffer 52428800
Explanation: This sets the HTTP POST buffer to 50 MB (52428800 bytes). Run this command and then try pushing again.

2. 增加 Git 超时时间 (Increase Git Timeout)

You can explicitly tell Git to wait longer for the connection to respond, which might bypass the internal network timeout that's causing the 408 error.

Bash

git config --global http.lowSpeedLimit 0
git config --global http.lowSpeedTime 999999
Explanation: These settings effectively disable the "low speed" timeout, allowing the connection to stay open for a very long time, even if the transfer speed fluctuates, which helps complete large pushes.

3. 切换到 SSH 协议 (Switch to SSH Protocol) 🔑

The HTTPS protocol is often more susceptible to network-level timeouts and proxy/firewall issues. The SSH protocol often provides a more reliable connection for large data transfers.

步骤 A: 设置 SSH Key

If you haven't already, you must generate an SSH key on your computer and add the public key to your GitHub account settings. (This is a one-time setup).

步骤 B: 更改远程 URL

Change the remote URL of your repository from HTTPS to SSH format:

Bash

git remote set-url origin git@github.com:qianlongzaiyuan76/audio2txt.git

步骤 C: 再次推送

Try the push command again:

Bash

git push -u origin main

4. 检查网络和安全软件 (Check Network and Security)

Temporary Network Issues: Wait a few minutes and try the push again.

Firewall/Antivirus: Temporarily disable any local firewall or antivirus/security software that might be monitoring or interrupting the network traffic, then try the push again.

VPN/Proxy: If you are using a VPN or proxy, try disabling it to ensure a direct connection.

After implementing any of the solutions above (especially the first two), try running your push command again:

Bash

git push -u origin main

在 Python 中实现“小图缩放后匹配大图”,核心是用 OpenCV 库,先对小图(模板图)进行多尺度缩放,再用模板匹配算法在大图中寻找最佳匹配位置。

核心步骤(附代码)

1. 读取图像:加载大图(目标图)和小图(模板图),并转为灰度图(减少计算量,提升匹配效率)。

2. 多尺度缩放模板:循环缩小/放大模板图(模拟不同尺寸匹配场景),计算每次缩放后的模板尺寸。

3. 模板匹配:对每个缩放后的模板,用  cv2.matchTemplate()  计算与大图的匹配度,记录最佳匹配的位置和相似度。

4. 绘制匹配结果:在大图上用矩形框标出最佳匹配区域。

完整代码示例

python

import cv2
import numpy as np

# 1. 读取图像(替换为你的图片路径)

big_img = cv2.imread("big_image.jpg") # 大图(目标图)
small_img = cv2.imread("small_image.jpg") # 小图(模板图)

# 转为灰度图(模板匹配需单通道图像)

big_gray = cv2.cvtColor(big_img, cv2.COLOR_BGR2GRAY)
small_gray = cv2.cvtColor(small_img, cv2.COLOR_BGR2GRAY)

# 获取模板图原始尺寸

small_h, small_w = small_gray.shape
best_score = 0 # 最佳匹配相似度(0~1,越高越匹配)
best_loc = (0, 0) # 最佳匹配位置(左上角坐标)
best_scale = 1.0 # 最佳匹配时的模板缩放比例

# 2. 多尺度缩放模板(这里设置缩放范围:0.5~2倍,步长0.1,可根据需求调整)

for scale in np.arange(0.5, 2.1, 0.1):

# 缩放模板图(INTER_LINEAR 适合缩小,INTER_CUBIC 适合放大)
scaled_small = cv2.resize(
    small_gray,
    dsize=(int(small_w * scale), int(small_h * scale)),
    interpolation=cv2.INTER_CUBIC
)
scaled_h, scaled_w = scaled_small.shape

# 跳过比大图还大的缩放模板(避免报错)
if scaled_h > big_gray.shape[0] or scaled_w > big_gray.shape[1]:
    continue

# 3. 模板匹配(TM_CCOEFF_NORMED 输出归一化相关系数,范围[-1,1],1表示完全匹配)
result = cv2.matchTemplate(big_gray, scaled_small, cv2.TM_CCOEFF_NORMED)
# 找到当前缩放模板的最大匹配值和对应位置
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

# 更新最佳匹配(只保留相似度更高的结果)
if max_val > best_score:
    best_score = max_val
    best_loc = max_loc
    best_scale = scale

# 4. 计算最佳匹配区域的右下角坐标

best_h = int(small_h * best_scale)
best_w = int(small_w * best_scale)
top_left = best_loc
bottom_right = (top_left[0] + best_w, top_left[1] + best_h)

# 5. 在大图上绘制匹配框(绿色框,线宽2)

cv2.rectangle(big_img, top_left, bottom_right, (0, 255, 0), 2)

# 添加匹配相似度文字(左上角显示)

cv2.putText(

big_img, f"Score: {best_score:.2f}",
(top_left[0], top_left[1] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1

)

# 显示结果(按任意键关闭窗口)

cv2.imshow("Matching Result", big_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# (可选)保存结果图

cv2.imwrite("matching_result.jpg", big_img)
 

关键说明

  • 匹配算法选择:代码中用  TM_CCOEFF_NORMED (归一化相关系数),适合大多数场景;若小图和大图亮度差异大,可尝试  TM_SQDIFF_NORMED (归一化平方差,值越小越匹配)。
  • 缩放范围:需根据实际场景调整  np.arange(0.5, 2.1, 0.1) ,步长越小匹配越精准,但计算时间越长。
  • 相似度阈值:若需过滤低相似度匹配(如避免误检),可在最后添加判断(例: if best_score > 0.7: 才绘制匹配框 ),阈值需根据图像特点调试。