• opencv实现模块化图像处理管道


    还是搬运来的 为了自己学习 大佬勿怪啊~~ 

    图像处理管道是一组按预定义顺序执行的任务,用于将图像转换为所需的结果或提取一些有趣的特征。

    任务示例可以是:

    • 图像转换,如平移、旋转、调整大小、翻转和裁剪,

    • 图像的增强,

    • 提取感兴趣区域(ROI),

    • 计算特征描述符,

    • 图像或对象分类,

    • 物体检测,

    • 用于机器学习的图像注释,

    最终结果可能是一个新图像,或者只是一个包含一些图像信息的JSON文件。

    假设我们在一个目录中有大量图像,并且想要检测其中的人脸并将每个人脸写入单独的文件。此外,我们希望有一些 JSON 摘要文件,它告诉我们在何处找到人脸以及在哪个文件中找到人脸。我们的人脸检测流程如下所示:

    人脸检测流程

    这是一个非常简单的例子,可以用以下代码总结:

    1. import cv2
    2. import os
    3. import json
    4. import numpy as np
    5. def parse_args():
    6. import argparse
    7. # Parse command line arguments
    8. ap = argparse.ArgumentParser(description="Image processing pipeline")
    9. ap.add_argument("-i", "--input", required=True,
    10. help="path to input image files")
    11. ap.add_argument("-o", "--output", default="output",
    12. help="path to output directory")
    13. ap.add_argument("-os", "--out-summary", default=None,
    14. help="output JSON summary file name")
    15. ap.add_argument("-c", "--classifier", default="models/haarcascade/haarcascade_frontalface_default.xml",
    16. help="path to where the face cascade resides")
    17. return vars(ap.parse_args())
    18. def list_images(path, valid_exts=None):
    19. image_files = []
    20. # Loop over the input directory structure
    21. for (root_dir, dir_names, filenames) in os.walk(path):
    22. for filename in sorted(filenames):
    23. # Determine the file extension of the current file
    24. ext = filename[filename.rfind("."):].lower()
    25. if valid_exts and ext.endswith(valid_exts):
    26. # Construct the path to the file and yield it
    27. file = os.path.join(root_dir, filename)
    28. image_files.append(file)
    29. return image_files
    30. def main(args):
    31. os.makedirs(args["output"], exist_ok=True)
    32. # load the face detector
    33. detector = cv2.CascadeClassifier(args["classifier"])
    34. # list images from input directory
    35. input_image_files = list_images(args["input"], (".jpg", ".png"))
    36. # Storage for JSON summary
    37. summary = {}
    38. # Loop over the image paths
    39. for image_file in input_image_files:
    40. # Load the image and convert it to grayscale
    41. image = cv2.imread(image_file)
    42. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    43. # Detect faces
    44. face_rects = detector.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5,
    45. minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
    46. summary[image_file] = {}
    47. # Loop over all detected faces
    48. for i, (x, y, w, h) in enumerate(face_rects):
    49. face = image[y:y+w, x:x+h]
    50. # Prepare output directory for faces
    51. output = os.path.join(*(image_file.split(os.path.sep)[1:]))
    52. output = os.path.join(args["output"], output)
    53. os.makedirs(output, exist_ok=True)
    54. # Save faces
    55. face_file = os.path.join(output, f"{i:05d}.jpg")
    56. cv2.imwrite(face_file, face)
    57. # Store summary data
    58. summary[image_file][face_file] = np.array([x, y, w, h], dtype=int).tolist()
    59. # Display summary
    60. print(f"[INFO] {image_file}: face detections {len(face_rects)}")
    61. # Save summary data
    62. if args["out_summary"]:
    63. summary_file = os.path.join(args["output"], args["out_summary"])
    64. print(f"[INFO] Saving summary to {summary_file}...")
    65. with open(summary_file, 'w') as json_file:
    66. json_file.write(json.dumps(summary))
    67. if __name__ == '__main__':
    68. args = parse_args()
    69. main(args)

    用于人脸检测和提取的简单图像处理脚本

    代码中的注释也很有探索性,让我们来深入研究一下。首先,我们定义命令行参数解析器(第 6-20 行)以接受以下参数:

    --input:这是包含我们图像的目录的路径(可以是子目录),这是唯一的强制性参数。

    --output: 保存管道结果的输出目录。

    --out-summary:如果我们想要一个 JSON 摘要,只需提供它的名称(例如 output.json)。

    --classifier:用于人脸检测的预训练 Haar 级联的路径

    接下来,我们定义list_images函数(第 22-34 行),它将帮助我们遍历输入目录结构以获取图像路径。对于人脸检测,我们使用称为Haar级联(第 40 行)的 Viola-Jones 算法,在深度学习和容易出现误报(在没有人脸的地方报告人脸)的时代,这是一种相当古老的算法。

    来自电影“老友记”的示例图像,其中存在一些误报

    主要处理循环如下:我们遍历图像文件(第 49行),逐个读取它们(第 51 行),检测人脸(第 55 行),将它们保存到准备好的目录(第 59-72 行)并保存带有人脸坐标的摘要报告(第 78-82 行)。

    准备项目环境:

    1. $ git clone git://github.com/jagin/image-processing-pipeline.git
    2. $ cd image-processing-pipeline
    3. $ git checkout 77c19422f0d7a90f1541ff81782948e9a12d2519
    4. $ conda env create -f environment.yml
    5. $ conda activate pipeline

    为了确保你们的代码能够正常运行,请检查你们的切换分支命令是否正确:
    77c19422f0d7a90f1541ff81782948e9a12d2519

    让我们运行它:$ python process\_images.py --input assets/images -os output.json 我们得到了一个很好的总结:

    [INFO] assets/images/friends/friends\_01.jpg: face detections 2

    [INFO] assets/images/friends/friends\_02.jpg: face detections 3

    [INFO] assets/images/friends/friends\_03.jpg: face detections 5

    [INFO] assets/images/friends/friends\_04.jpg: face detections 14

    [INFO] assets/images/landscapes/landscape\_01.jpg: face detections 0

    [INFO] assets/images/landscapes/landscape\_02.jpg: face detections 0

    [INFO] Saving summary to output/output.json...

    每个图像的人脸图像(也有误报)存储在单独的目录中。

    1. output
    2. ├── images
    3. │ └── friends
    4. │ ├── friends_01.jpg
    5. │ │ ├── 00000.jpg
    6. │ │ └── 00001.jpg
    7. │ ├── friends_02.jpg
    8. │ │ ├── 00000.jpg
    9. │ │ ├── 00001.jpg
    10. │ │ └── 00002.jpg
    11. │ ├── friends_03.jpg
    12. │ │ ├── 00000.jpg
    13. │ │ ├── 00001.jpg
    14. │ │ ├── 00002.jpg
    15. │ │ ├── 00003.jpg
    16. │ │ └── 00004.jpg
    17. │ └── friends_04.jpg
    18. │ ├── 00000.jpg
    19. │ ├── 00001.jpg
    20. │ ├── 00002.jpg
    21. │ ├── 00003.jpg
    22. │ ├── 00004.jpg
    23. │ ├── 00005.jpg
    24. │ ├── 00006.jpg
    25. │ ├── 00007.jpg
    26. │ ├── 00008.jpg
    27. │ ├── 00009.jpg
    28. │ ├── 00010.jpg
    29. │ ├── 00011.jpg
    30. │ ├── 00012.jpg
    31. │ └── 00013.jpg
    32. └── output.json

      whaosoft aiot http://143ai.com 

  • 相关阅读:
    Flask——基于python完整实现客户端和服务器后端流式请求及响应
    socket编程详解(一)——服务器端
    十、阶段实践练习
    十三)Stable Diffussion使用教程:Lora训练
    UrlBasedViewResolver类简介说明
    目标检测算法——自动驾驶开源数据集汇总(附下载链接)
    DTC趋势 | 2022年值得关注的10个DTC趋势
    达梦数据库(十) -------- mybatis-plus 整合达梦时,自动生成的 sql 语句报错
    类与对象(中)
    【牛客 - 剑指offer】JZ10 斐波那契数列(入门难度)三种方案 Java实现
  • 原文地址:https://blog.csdn.net/qq_29788741/article/details/126830856