【python进阶】txt excel pickle opencv操作demo

文章目录

1. txt读写

file.read()

file.readlines()

file.readline()

python 复制代码
# # 使用 'read' 方法读取文件的所有内容
with open('resources/training_log.txt', 'r') as file:
    content = file.read()
    print(content)


# 使用 'readline' 方法逐行读取文件
with open('.\\resources/training_log.txt', 'r') as file:
    line = file.readline()
    # print(line)
    while line:
        print(line, end='')
        line = file.readline()


# 使用 'readlines' 方法读取文件的所有行
with open('.\\resources/training_log.txt', 'r') as file:
    lines = file.readlines()
    # print(lines)
    for line in lines:
        print(line, end='')

## 写
> f.write()
> f.writelines()

```python
# 使用 'write' 方法写入文件
# with open('resources/example_1.txt', 'w') as file:
#     file.write("Hello, World!")


# 使用 'writelines' 方法写入文件
lines = ["Hello, World!", "Welcome to Python programming."]
with open('resources/example_2.txt', 'w') as file:
    file.writelines(line + '\n' for line in lines)

综合案例 日志文件读写

f.write

写一段代码,模拟生成accuracy逐步上升、loss逐步下降的训练日志,并将日志信息记录到 training_log.txt中

python 复制代码
import random

epoch = 100
accuracy = 0.5
loss = 0.9

with open('training_log.txt', 'w') as f:
    f.write('Epoch\tAccuracy\tLoss\n')

    for epoch_i in range(1, epoch+1):
        accuracy += random.uniform(0, 0.005)
        loss -= random.uniform(0, 0.005)

        accuracy = min(1, accuracy)
        loss = max(0, loss)

        f.write(f'{epoch_i}\t{accuracy:.3f}\t{loss:.3f}\n')

        print(f'Epoch:{epoch_i}, Accuracy:{accuracy}, Loss:{loss}')

2. excel读写

读取csv

pd.read_csv()

读取xlsx

pd.read_excel()

3. matplotlib 案例

折线图

python 复制代码
import numpy as np
import matplotlib.pyplot as plt

# 创建一个x值的数组,从-2π到2π,步长为0.01
x = np.arange(-2 * np.pi, 2 * np.pi, 0.01)

# 计算每个x值对应的sin(x)值
y = np.sin(x)

# 使用matplotlib来绘制图像
plt.figure()  # 创建一个新的图像窗口
plt.plot(x, y)  # 绘制折线图
plt.title('sin(x)')  # 设置图像的标题
plt.xlabel('x')  # 设置x轴的标签
plt.ylabel('sin(x)')  # 设置y轴的标签
plt.grid(True)  # 显示网格
plt.show()  # 显示图像

##读取YOLO数据后画出曲线图

python 复制代码
import pandas as pd
import matplotlib.pyplot as plt

data_loc = r'resources/yolov5s.csv'

data = pd.read_csv(data_loc, index_col=0)

train_bbox_loss = data['      train/box_loss']

x_list = [i for i in range(len(train_bbox_loss))]
plt.plot(x_list, train_bbox_loss)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('YOLOv5s')
plt.show()

多个折现图

python 复制代码
import pandas as pd
import matplotlib.pyplot as plt


file_1_loc = './resources/yolov5l.csv'
file_2_loc = 'C:\WORK\xuxiu\learn\AI\class\【0】源码+PDF课件+电子书\【0】源码+PDF课件+电子书\源码+PDF课件\第3周资料\第三周课程代码\代码\3.matplotlib_demos\resources\yolov5m.csv'
file_3_loc = './resources/yolov5s.csv'

file_1 = pd.read_csv(file_1_loc)
file_2 = pd.read_csv(file_2_loc)
file_3 = pd.read_csv(file_3_loc)

file_1_train_box_loss = file_1['      train/box_loss']
file_2_train_box_loss = file_2['      train/box_loss']
file_3_train_box_loss = file_3['      train/box_loss']

x_list = [i for i in range(len(file_1_train_box_loss))]

plt.plot(x_list, file_1_train_box_loss)
plt.plot(x_list, file_2_train_box_loss)
plt.plot(x_list, file_3_train_box_loss)

plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Train box_loss")
plt.grid()

plt.legend(['yolov5l', 'yolov5m', 'yolov5s'])

plt.show()

散点图

plt.scatter

柱状图

plt.bar

plt.bar(x, values, color='blue', align='center', alpha=0.7)

饼状图

plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

python 复制代码
import matplotlib.pyplot as plt

# 数据
sizes = [15, 30, 45, 10]  # 各部分的大小
labels = ['A', 'B', 'C', 'D']  # 各部分的标签
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']  # 各部分的颜色
explode = (0.1, 0, 0, 0)  # 突出显示第一个部分

# 绘制扇形图
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)

# 设置为等比例,这样扇形图就是一个圆
plt.axis('equal')

# 显示图像
plt.show()

4 opencv 案例

加载与展示图片

cv2.imread()

cv2.imshow()

python 复制代码
import cv2

img_path = r'resources/food.png'

# 以彩色模式读取图片
image_color = cv2.imread(img_path)

# 以灰度模式读取图片
image_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)


# 显示图片
cv2.imshow('Color Image', image_color)
# cv2.imshow('Grayscale Image', image_gray)

# 等待用户按键,然后关闭窗口
cv2.waitKey(0)
cv2.destroyAllWindows()

缩放图片

cv2.resize()

旋转图片

cv2.rotate()

python 复制代码
# 使用cv2.rotate()函数旋转图片
rotated_90 = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)  # 顺时针旋转90度
rotated_180 = cv2.rotate(image, cv2.ROTATE_180)  # 顺时针旋转180度
rotated_270 = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)  # 顺时针旋转270度

保存图片

cv2.imwrite()

python 复制代码
import cv2

# 读取图像
image = cv2.imread('resources/food.png')

# 如果图像不为空,则保存图像
if image is not None:
    cv2.imwrite('output_image.png', image)
else:
    print("无法读取图像")

读取摄像头

cv2.VideoCapture

python 复制代码
import cv2

# 创建一个 VideoCapture 对象,参数 0 表示使用默认的摄像头, 也可以传入一个视频文件的路径
cap = cv2.VideoCapture("resources/piano.mp4")   # resources/piano.mp4

while True:
    # 读取一帧
    ret, frame = cap.read()

    # 如果读取成功,显示这一帧
    if ret:
        cv2.imshow('Frame', frame)

    # 按 'q' 键退出循环
    if cv2.waitKey(15) & 0xFF == ord('q'):
        break

# 释放资源并关闭窗口
cap.release()
cv2.destroyAllWindows()

释放资源并关闭窗口

cap.release()

cv2.destroyAllWindows()

视频保存

cv2.VideoWriter()

python 复制代码
import cv2

# 定义视频捕获对象
cap = cv2.VideoCapture(0)

# 检查是否成功打开摄像头
if not cap.isOpened():
    print("Error: Could not open camera.")
    exit()

# 获取摄像头的帧宽度和帧高度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 定义视频编码器和输出文件
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 或者使用 'XVID'
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (frame_width, frame_height))

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to grab frame.")
        break

    # 将当前帧写入输出视频文件
    out.write(frame)

    # 显示当前帧
    cv2.imshow('frame', frame)

    # 按'q'键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()

opencv 综合案例

python 复制代码
import cv2
import numpy as np


def add_gaussian_noise(image):
    row, col = image.shape
    mean = 0
    sigma = 15
    gauss = np.random.normal(mean, sigma, (row, col))
    noisy = image + gauss
    noisy_img = np.clip(noisy, 0, 255)
    return noisy_img.astype(np.uint8)


# 输入和输出视频文件名
input_video = 'resources/outdoor.mp4'
output_video = 'resources/output.mp4'

# 打开输入视频
cap = cv2.VideoCapture(input_video)

# 获取视频的帧率和帧大小
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 计算新的帧大小 (540p)
new_height = 540
new_width = int((new_height / frame_height) * frame_width)

# 创建视频写入对象
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video, fourcc, fps, (new_width, new_height), isColor=False)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 调整帧大小
    frame = cv2.resize(frame, (new_width, new_height))

    # 转换为灰度图像
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 垂直翻转画面
    frame = cv2.flip(frame, 1)

    # 添加高斯噪声
    frame = add_gaussian_noise(frame)

    # 写入输出视频
    out.write(frame)

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()

5 pickle 案例

python 复制代码
# 使用 pickle 保存数据
with open('data.pkl', 'wb') as file:
    pickle.dump(data, file)

# 使用 pickle 加载数据
with open('data.pkl', 'rb') as file:
    loaded_data = pickle.load(file)
相关推荐
sz66cm21 分钟前
Python基础 -- 使用Python实现ssh终端并实现数据处理与统计功能
开发语言·python·ssh
ac-er88882 小时前
如何在Flask中实现国际化和本地化
后端·python·flask
Adolf_19932 小时前
Flask-WTF的使用
后端·python·flask
空城皆是旧梦2 小时前
python爬虫初体验(一)
爬虫·python
藓类少女2 小时前
正则表达式
数据库·python·mysql·正则表达式
深蓝海拓3 小时前
迭代器和生成器的学习笔记
笔记·python·学习
985小水博一枚呀4 小时前
【深度学习|可视化】如何以图形化的方式展示神经网络的结构、训练过程、模型的中间状态或模型决策的结果??
人工智能·python·深度学习·神经网络·机器学习·计算机视觉·cnn
CyreneSimon5 小时前
使用 LoRA 进行模型微调的步骤
python·transformer
ymchuangke5 小时前
数据清洗-缺失值处理-缺失值可视化图(竖线)
python·算法·数学建模
计算机学姐5 小时前
基于python+django+vue的旅游网站系统
开发语言·vue.js·python·mysql·django·旅游·web3.py