当前位置: 首页 > news >正文

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

文章目录

  • 1. txt读写
    • 综合案例 日志文件读写
  • 2. excel读写
    • 读取csv
    • 读取xlsx
  • 3. matplotlib 案例
    • 折线图
    • 多个折现图
    • 散点图
    • 柱状图
    • 饼状图
  • 4 opencv 案例
    • 加载与展示图片
    • 缩放图片
    • 旋转图片
    • 保存图片
    • 读取摄像头
    • 视频保存
    • opencv 综合案例
  • 5 pickle 案例

1. txt读写

file.read()
file.readlines()
file.readline()

# # 使用 '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中

import randomepoch = 100
accuracy = 0.5
loss = 0.9with 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 案例

折线图

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数据后画出曲线图

import pandas as pd
import matplotlib.pyplot as pltdata_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()

多个折现图

import pandas as pd
import matplotlib.pyplot as pltfile_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)

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

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

# 使用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()

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

读取摄像头

cv2.VideoCapture


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

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 综合案例

import cv2
import numpy as npdef add_gaussian_noise(image):row, col = image.shapemean = 0sigma = 15gauss = np.random.normal(mean, sigma, (row, col))noisy = image + gaussnoisy_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 案例

# 使用 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)
http://www.lryc.cn/news/351488.html

相关文章:

  • Aware接口作用
  • Docker部署Minio S3第三方存储
  • 听说京东618裁员没?上午还在赶需求,下午就开会通知被裁了~
  • 力扣226. 翻转二叉树(DFS的两种思路)
  • 状态机-非重叠的序列检测
  • Word怎么画图?这5个方法收藏好!
  • qt designer 依赖库 QMessageBox
  • 反序列化漏洞(JBoss、apache log4、apache Shiro、JWT)Weblogic未授权访问、代码执行、任意上传
  • PHP身份证真伪验证、身份证二、三要素核验、身份证ocr接口
  • 【Qt 学习笔记】Qt常用控件 | 布局管理器 | 表单布局Form Layout
  • 数智赋能内涝治理,四信城市排水防涝解决方案保障城市安全运行
  • docker实战之搭建MYSQL8.0主从同步
  • LTD275次升级 | 网页编辑器新增AI翻译 • 文章|产品等内容可导出 • 新增交互数据 • 购物清单可导出• 官微中心app出新版
  • 代码随想录算法训练营第36期DAY36
  • zookeeper安装教程
  • windows2008修改远程桌面端口,如何果断修改远程桌面端口,确保系统安全无忧!
  • 【计算机网络原理】对传输层TCP协议的重点知识的总结
  • mysql实战——半同步复制搭建
  • Leetcode 3152. Special Array II
  • 人工智能与区块链技术:开启未来科技的双引擎
  • Python筑基之旅-MySQL数据库(二)
  • web前端面试题
  • 创建型模式之单例
  • 在 Next.js 应用中创建ContactForm表单提交
  • HTML5 3D图像应用
  • SQL——DML对表中数据的操作
  • 深度学习之基于Matlab卷积神经网络(CNN)手写数字识别
  • 工业4.0 企业级云MES全套源码,支持app、小程序、H5、台后管理端
  • Science| 单体耦合纤维实现无芯片纺织电子(纤维器件/智能织物/柔性可穿戴电子)
  • 前端面试项目细节重难点(已工作|做分享)