数据处理专题(十三)

学会基本的图像处理技术。‍

OpenCV 基础

实践:使用 OpenCV 进行图像读取、显示和基本处理‍

03

代码示例

  1. 导入必要的库

    import cv2import numpy as npimport matplotlib.pyplot as plt

  2. 图像读取

    读取图像image_path = 'path_to_your_image.jpg' # 替换为你的图像路径image = cv2.imread(image_path)# 检查图像是否成功读取if image is None: print("图像读取失败,请检查路径是否正确。")else: print("图像读取成功!")

  3. 图像显示

    使用 OpenCV 显示图像cv2.imshow('原图', image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示图像plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))plt.title('原图')plt.axis('off')plt.show()

  4. 图像基本信息

    获取图像的基本信息height, width, channels = image.shapeprint(f"图像高度: {height} 像素")print(f"图像宽度: {width} 像素")print(f"图像通道数: {channels}")

  5. 图像灰度化​​​​​​​

    将图像转换为灰度图像gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# 显示灰度图像cv2.imshow('灰度图', gray_image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示灰度图像plt.imshow(gray_image, cmap='gray')plt.title('灰度图')plt.axis('off')plt.show()

  6. 图像裁剪​​​​​​​

    裁剪图像cropped_image = image[100:400, 100:400]# 显示裁剪后的图像cv2.imshow('裁剪图', cropped_image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示裁剪后的图像plt.imshow(cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB))plt.title('裁剪图')plt.axis('off')plt.show()

  7. 图像缩放​​​​​​​

    缩放图像resized_image = cv2.resize(image, (width // 2, height // 2))# 显示缩放后的图像cv2.imshow('缩放图', resized_image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示缩放后的图像plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))plt.title('缩放图')plt.axis('off')plt.show()

  8. 图像旋转​​​​​​​

    旋转图像center = (width // 2, height // 2)angle = 45scale = 1.0rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))# 显示旋转后的图像cv2.imshow('旋转图', rotated_image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示旋转后的图像plt.imshow(cv2.cvtColor(rotated_image, cv2.COLOR_BGR2RGB))plt.title('旋转图')plt.axis('off')plt.show()

  9. 图像翻转​​​​​​​

    翻转图像flipped_image = cv2.flip(image, 1) # 1 表示水平翻转,0 表示垂直翻转,-1 表示水平和垂直翻转# 显示翻转后的图像cv2.imshow('翻转图', flipped_image)cv2.waitKey(0)cv2.destroyAllWindows()# 使用 Matplotlib 显示翻转后的图像plt.imshow(cv2.cvtColor(flipped_image, cv2.COLOR_BGR2RGB))plt.title('翻转图')plt.axis('off')plt.show()

  10. 图像保存​​​​​​​

    保存处理后的图像output_path = 'processed_image.jpg'cv2.imwrite(output_path, flipped_image)print(f"处理后的图像已保存到 {output_path}")

04

实践​​​​​​​

复制代码
import cv2import numpy as npimport matplotlib.pyplot as plt# 读取图像image_path = 'path_to_your_image.jpg'  # 替换为你的图像路径image = cv2.imread(image_path)# 检查图像是否成功读取if image is None:    print("图像读取失败,请检查路径是否正确。")else:    print("图像读取成功!")    # 使用 OpenCV 显示图像    cv2.imshow('原图', image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示图像    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))    plt.title('原图')    plt.axis('off')    plt.show()    # 获取图像的基本信息    height, width, channels = image.shape    print(f"图像高度: {height} 像素")    print(f"图像宽度: {width} 像素")    print(f"图像通道数: {channels}")    # 将图像转换为灰度图像    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)    # 显示灰度图像    cv2.imshow('灰度图', gray_image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示灰度图像    plt.imshow(gray_image, cmap='gray')    plt.title('灰度图')    plt.axis('off')    plt.show()    # 裁剪图像    cropped_image = image[100:400, 100:400]    # 显示裁剪后的图像    cv2.imshow('裁剪图', cropped_image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示裁剪后的图像    plt.imshow(cv2.cvtColor(cropped_image, cv2.COLOR_BGR2RGB))    plt.title('裁剪图')    plt.axis('off')    plt.show()    # 缩放图像    resized_image = cv2.resize(image, (width // 2, height // 2))    # 显示缩放后的图像    cv2.imshow('缩放图', resized_image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示缩放后的图像    plt.imshow(cv2.cvtColor(resized_image, cv2.COLOR_BGR2RGB))    plt.title('缩放图')    plt.axis('off')    plt.show()    # 旋转图像    center = (width // 2, height // 2)    angle = 45    scale = 1.0    rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)    rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))    # 显示旋转后的图像    cv2.imshow('旋转图', rotated_image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示旋转后的图像    plt.imshow(cv2.cvtColor(rotated_image, cv2.COLOR_BGR2RGB))    plt.title('旋转图')    plt.axis('off')    plt.show()    # 翻转图像    flipped_image = cv2.flip(image, 1)  # 1 表示水平翻转,0 表示垂直翻转,-1 表示水平和垂直翻转    # 显示翻转后的图像    cv2.imshow('翻转图', flipped_image)    cv2.waitKey(0)    cv2.destroyAllWindows()    # 使用 Matplotlib 显示翻转后的图像    plt.imshow(cv2.cvtColor(flipped_image, cv2.COLOR_BGR2RGB))    plt.title('翻转图')    plt.axis('off')    plt.show()    # 保存处理后的图像    output_path = 'processed_image.jpg'    cv2.imwrite(output_path, flipped_image)    print(f"处理后的图像已保存到 {output_path}")

05

总结

通过今天的练习,你应该已经学会了如何使用 OpenCV 进行基本的图像处理,包括图像读取、显示、灰度化、裁剪、缩放、旋转和翻转

数据管道

学会安装和配置 Apache Airflow

使用 Airflow 构建一个简单的数据处理管道

调度和监控任务‍

01

目标

学会安装和配置 Apache Airflow

使用 Airflow 构建一个简单的数据处理管道

调度和监控任务‍

02

步骤

  1. 安装 Apache Airflow

首先,我们需要安装 Apache Airflow。可以使用 pip 来安装:

复制代码
pip install apache-airflow
  1. 初始化 Airflow

初始化 Airflow 的数据库和配置文件:

复制代码
airflow db init
  1. 启动 Airflow Web 服务器

启动 Airflow 的 Web 服务器,这样我们可以在浏览器中监控和管理任务:

复制代码
airflow webserver --port 8080
  1. 启动 Airflow Scheduler

启动 Airflow 的调度器,它负责调度任务:

复制代码
airflow scheduler
  1. 创建 DAG 文件

DAG(Directed Acyclic Graph)是 Airflow 中的核心概念,表示一系列任务的依赖关系。我们将在 dags 目录下创建一个 Python 文件来定义我们的 DAG。

假设我们有一个简单的数据处理管道,包括以下几个任务:

从 CSV 文件中读取数据

清洗数据(处理缺失值和重复行)

按部门分组并计算每组的销售额均值

将结果保存到新的 CSV 文件

创建一个名为 simple_data_pipeline.py 的文件,内容如下:​​​​​​​

复制代码
from airflow import DAGfrom airflow.operators.python_operator import PythonOperatorfrom datetime import datetime, timedeltaimport pandas as pdimport os# 定义默认参数default_args = {    'owner': 'airflow',    'depends_on_past': False,    'start_date': datetime(2023, 1, 1),    'retries': 1,    'retry_delay': timedelta(minutes=5),}# 创建 DAGdag = DAG(    'simple_data_pipeline',    default_args=default_args,    description='一个简单的数据处理管道',    schedule_interval=timedelta(days=1),)# 定义任务函数def read_csv_file():    """从 CSV 文件中读取数据"""    file_path = '/path/to/sales_data.csv'    df = pd.read_csv(file_path, encoding='utf-8-sig')    print(f"原始数据集: \n{df.head()}")    return dfdef clean_data(**context):    """清洗数据(处理缺失值和重复行)"""    df = context['ti'].xcom_pull(task_ids='read_csv_file')    # 检查每列的缺失值数量    missing_values = df.isnull().sum()    print(f"每列的缺失值数量: \n{missing_values}")    # 删除含有缺失值的行    df_cleaned = df.dropna()    print(f"删除缺失值后的数据集: \n{df_cleaned.head()}")    # 检查重复行    duplicates = df_cleaned.duplicated()    print(f"重复行: \n{duplicates}")    # 删除重复行    df_no_duplicates = df_cleaned.drop_duplicates()    print(f"删除重复行后的数据集: \n{df_no_duplicates.head()}")    return df_no_duplicatesdef group_and_calculate_mean(**context):    """按部门分组并计算每组的销售额均值"""    df = context['ti'].xcom_pull(task_ids='clean_data')    # 按 '部门' 列分组    grouped_by_department = df.groupby('部门')    # 计算每组的销售额均值    mean_sales_by_department = grouped_by_department['总价'].mean()    print(f"按 '部门' 列分组后,每组的销售额均值: \n{mean_sales_by_department}")    return mean_sales_by_departmentdef save_results(**context):    """将结果保存到新的 CSV 文件"""    mean_sales_by_department = context['ti'].xcom_pull(task_ids='group_and_calculate_mean')    result_path = '/path/to/mean_sales_by_department.csv'    mean_sales_by_department.to_csv(result_path, encoding='utf-8-sig')    print(f"结果已保存到 {result_path}")# 定义任务read_csv_task = PythonOperator(    task_id='read_csv_file',    python_callable=read_csv_file,    dag=dag,)clean_data_task = PythonOperator(    task_id='clean_data',    python_callable=clean_data,    provide_context=True,    dag=dag,)group_and_calculate_mean_task = PythonOperator(    task_id='group_and_calculate_mean',    python_callable=group_and_calculate_mean,    provide_context=True,    dag=dag,)save_results_task = PythonOperator(    task_id='save_results',    python_callable=save_results,    provide_context=True,    dag=dag,)# 设置任务依赖关系read_csv_task >> clean_data_task >> group_and_calculate_mean_task >> save_results_task
  1. 配置 Airflow

确保 dags 目录在 Airflow 的配置文件中正确设置。通常情况下,Airflow 会自动检测 dags 目录下的 DAG 文件。

  1. 运行和监控任务

打开浏览器,访问 http://localhost:8080,登录 Airflow 的 Web 界面。

在 DAG 列表中找到 simple_data_pipeline,点击进入详细页面。

点击 "Trigger Dag" 按钮手动触发任务,或者等待调度器自动运行任务。

在任务详情页面中,可以查看每个任务的运行状态和日志。‍

03

总结

通过今天的实践,你应该已经学会了如何使用 Apache Airflow 构建一个简单的数据处理管道。这个管道包括从 CSV 文件中读取数据、清洗数据、按部门分组计算销售额均值,并将结果保存到新的 CSV 文件。

相关推荐
嘀咕博客2 天前
Zulu - 百度文心快码推出的自动编程智能体
百度·ai工具
华新嘉华DTC创新营销2 天前
华新嘉华:AI搜索优化重塑本地生活行业:智能推荐正取代“关键词匹配”
人工智能·百度·生活
程思扬2 天前
利用JSONCrack与cpolar提升数据可视化及跨团队协作效率
网络·人工智能·经验分享·docker·信息可视化·容器·架构
月阳羊3 天前
【硬件-笔试面试题-95】硬件/电子工程师,笔试面试题(知识点:RC电路中的时间常数)
java·经验分享·单片机·嵌入式硬件·面试
嘀咕博客3 天前
文心快码Comate - 百度推出的AI编码助手
人工智能·百度·ai工具
智者知已应修善业3 天前
【矩阵找最大小所在位置】2022-11-13
c语言·c++·经验分享·笔记·算法·矩阵
semantist@语校3 天前
第二十篇|SAMU教育学院的教育数据剖析:制度阈值、能力矩阵与升学网络
大数据·数据库·人工智能·百度·语言模型·矩阵·prompt
SccTsAxR3 天前
[C语言]常见排序算法①
c语言·开发语言·经验分享·笔记·其他·排序算法
智者知已应修善业3 天前
【51单片机单按键控制2个LED循环闪烁】2022-12-7
c语言·经验分享·笔记·嵌入式硬件·51单片机
艾莉丝努力练剑3 天前
【C++】类和对象(下):初始化列表、类型转换、Static、友元、内部类、匿名对象/有名对象、优化
linux·运维·c++·经验分享