1. Pillow 图像处理与可视化
1.1. 数据可视化基础:matplotlib入门
常用图表类型:折线图、柱状图、饼图、散点图等
自定义设置:标题、标签、图例、颜色、字体等
图表保存:支持多种格式(PNG、JPG、SVG等)
中文支持:通过设置字体确保中文正常显示
1.2. Pillow库基础
图像基本操作:创建、打开、编辑、保存
绘图功能:绘制直线、矩形、圆形、文本等
图像处理:调整大小、裁剪、颜色转换、滤镜等
字体处理:支持自定义字体,确保中文正常显示
1.3. 情感分析结果图表
饼图:展示情感分布比例(积极/消极/中性)
折线图:展示情感趋势变化
组合图表:将多个图表组合成综合报告
1.4. 词云图生成
文本预处理:分词、去除停用词
词频统计:使用Counter统计高频词汇
词云定制:自定义形状、颜色、字体等
中文支持:指定中文字体路径确保中文正常显示
1.5. 自定义图像样式与布局
图像组合:将多个图表组合成一个复合图像
文字标注:添加标题、说明文字等
布局设计:合理安排各个图像的位置和大小
输出报告:生成完整的可视化分析报告
1.6. 运行说明
运行前请确保安装了必要的库:pip install matplotlib numpy pillow jieba wordcloud
1.7. 扩展建议
高级可视化:使用seaborn、plotly等库创建更复杂的图表
图像处理:添加滤镜、调整亮度/对比度、图像分割等
交互式图表:使用plotly或bokeh创建可交互的可视化
自动化报告:根据数据分析结果自动生成图文报告
深度学习应用:结合CNN进行图像分类或生成艺术风格图像
2. TODO---上课过程演示
3. 历史演示代码备份
# Pillow图像处理与可视化基础示例
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import jieba
from collections import Counter
from wordcloud import WordCloud
import re
# 设置中文字体支持
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
# ================
# 1. 数据可视化基础:matplotlib入门
# ================
# 1.1 简单折线图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(10, 6)) # 设置图表大小
plt.plot(x, y, label='sin(x)')
plt.title('正弦函数图像')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend() # 显示图例
plt.grid(True) # 显示网格
plt.savefig('sin_wave.png') # 保存图表
plt.close() # 关闭图表
# 1.2 柱状图
categories = ['苹果', '香蕉', '橙子', '葡萄', '草莓']
values = [35, 25, 20, 15, 5]
plt.figure(figsize=(10, 6))
plt.bar(categories, values, color='skyblue')
plt.title('水果销量分布')
plt.xlabel('水果')
plt.ylabel('销量')
plt.savefig('fruit_sales.png')
plt.close()
# 1.3 饼图
plt.figure(figsize=(8, 8))
plt.pie(values, labels=categories, autopct='%1.1f%%', startangle=90)
plt.title('水果销量占比')
plt.savefig('fruit_pie.png')
plt.close()
# ================
# 2. Pillow库基础:图像创建、编辑、保存、绘制
# ================
# 2.1 创建图像
width, height = 400, 300
image = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(image)
# 2.2 绘制图形
# 绘制直线
draw.line([(50, 50), (350, 50)], fill='red', width=2)
# 绘制矩形
draw.rectangle([(100, 100), (300, 200)], outline='blue', width=2)
# 绘制圆形
draw.ellipse([(150, 150), (250, 250)], fill='yellow')
# 绘制文本
try:
# 尝试加载系统字体(Windows)
font = ImageFont.truetype('simhei.ttf', 24)
except IOError:
# 使用默认字体
font = ImageFont.load_default()
draw.text((100, 250), 'Pillow图像处理示例', font=font, fill='black')
# 2.3 保存图像
image.save('pillow_example.png')
# 2.4 打开和编辑现有图像
with Image.open('pillow_example.png') as img:
# 转换为灰度图
gray_img = img.convert('L')
# 调整大小
small_img = gray_img.resize((200, 150))
# 保存修改后的图像
small_img.save('pillow_example_gray.png')
# ================
# 3. 情感分析结果图表
# ================
# 假设这是情感分析结果
sentiment_data = {
'积极': 65,
'消极': 25,
'中性': 10
}
# 绘制情感分布饼图
plt.figure(figsize=(8, 8))
plt.pie(sentiment_data.values(), labels=sentiment_data.keys(), autopct='%1.1f%%',
startangle=90, colors=['lightgreen', 'salmon', 'lightgray'])
plt.title('影评情感分布')
plt.savefig('sentiment_analysis.png')
plt.close()
# 绘制情感趋势图
time_periods = ['1月', '2月', '3月', '4月', '5月', '6月']
positive_trend = [60, 65, 70, 68, 72, 75]
negative_trend = [30, 25, 20, 22, 18, 15]
plt.figure(figsize=(12, 6))
plt.plot(time_periods, positive_trend, 'g-', label='积极情感')
plt.plot(time_periods, negative_trend, 'r-', label='消极情感')
plt.title('情感趋势分析')
plt.xlabel('月份')
plt.ylabel('情感比例 (%)')
plt.legend()
plt.grid(True)
plt.savefig('sentiment_trend.png')
plt.close()
# ================
# 4. 生成词云图展示高频词汇
# ================
# 假设这是影评文本
reviews = [
"电影非常精彩,特效震撼,值得一看!",
"这电影简直是垃圾,浪费钱!",
"剧情紧凑,演员表现出色,强烈推荐!",
"无聊透顶,全程打瞌睡。",
"画面和音乐都很美,剧情一般。",
"太好看了,我看了三遍!",
"什么破电影,逻辑混乱。",
"演技尴尬,剧情老套。",
"超出预期的好,很感动。",
"不值得去电影院看,在家看看就行了。"
]
# 停用词列表
stopwords = set(['的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这', '那', '这个', '那个', '啊', '吧', '吗'])
# 文本预处理和分词
def preprocess_text(text):
text = re.sub(r'[^\w\s]', '', text) # 去除标点符号
words = jieba.cut(text)
words = [word for word in words if word not in stopwords and len(word) > 1]
return words
# 提取所有词汇
all_words = []
for review in reviews:
all_words.extend(preprocess_text(review))
# 统计词频
word_freq = Counter(all_words)
# 生成词云
wordcloud = WordCloud(
font_path='simhei.ttf', # 确保中文字体正确显示
width=800,
height=400,
background_color='white',
max_words=100
).generate_from_frequencies(word_freq)
# 保存词云图
plt.figure(figsize=(10, 6))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('影评高频词汇词云')
plt.savefig('wordcloud.png', dpi=300, bbox_inches='tight')
plt.close()
# ================
# 5. 自定义图像样式与布局
# ================
# 创建复合图像:将情感分析图表和词云组合在一起
def create_composite_image():
# 打开各个图像
sentiment_pie = Image.open('sentiment_analysis.png')
sentiment_trend = Image.open('sentiment_trend.png')
wordcloud_img = Image.open('wordcloud.png')
# 创建一个空白画布
width = 1200
height = 800
composite = Image.new('RGB', (width, height), color='white')
# 调整图像大小
sentiment_pie = sentiment_pie.resize((400, 400))
sentiment_trend = sentiment_trend.resize((700, 350))
wordcloud_img = wordcloud_img.resize((700, 400))
# 粘贴图像到画布上
composite.paste(sentiment_pie, (50, 50))
composite.paste(wordcloud_img, (500, 50))
composite.paste(sentiment_trend, (50, 470))
# 添加标题
draw = ImageDraw.Draw(composite)
try:
title_font = ImageFont.truetype('simhei.ttf', 36)
subtitle_font = ImageFont.truetype('simhei.ttf', 24)
except IOError:
title_font = ImageFont.load_default()
subtitle_font = ImageFont.load_default()
draw.text((400, 20), '影评情感分析报告', font=title_font, fill='black')
draw.text((50, 430), '情感趋势分析', font=subtitle_font, fill='black')
draw.text((500, 20), '影评高频词云', font=subtitle_font, fill='black')
# 保存复合图像
composite.save('composite_report.png')
print("复合图像已保存为 composite_report.png")
# 生成复合图像
create_composite_image()