Rolla‘s homework:Image Processing with Python Final Project

news2024/9/22 7:37:43

对比学习Yolo 和 faster rcnn 两种目标检测

要求

Image Processing with Python Final Project

Derek TanLoad several useful packages that are used in this notebook:Image Processing with Python Final Project Project Goals: • Gain an understanding of the object detection pipeline. • Learn to develop anchor-based single-stage object detectors. • Learn to develop a two-stage object detector that combines a region proposal network with a recognition network. Coding:

Q1: The notebook single_stage_detector_yolo. ipynb will guide you through the implementation of a fully-convolutional single-stage object detector similar to YOLO (Redmon et al, CVPR 2016). You will train and evaluate your detector on the PASCAL VOC 2007 object detection dataset.

Q2: The notebook two_stage_detector_faster_rcnn. ipynb will guide you through the implementation of a two-stage object detector similar to Faster R-CNN (Ren et al, NeurIPS 2015). This will combine a fully-convolutional Region Proposal Network (RPN) and a second-stage recognition network.

Steps:

  1. Unzip the P24 file. You will find three *.py files, two *. ipynb files, and an ip24 folder which includes seven *.py files.
  2. Carefully read the two *. ipynb notebooks.
  3. Write the code in the *.py files as indicated. The Python files have clearly marked blocks where you are expected to write code. Do not write or modify any code outside of these blocks. You may only be allowed to ADD one block of code to save the final results. You will only get credit for code that has been run.
  4. Evaluate your implementation. When you are done, save single_stage_detector.py, two_stage_detector.py, and all the outputs (folder Results) in one folder called Coding. Writing: Write a comparative analysis paper comparing the two object detection algorithms

Steps:

  1.    Your paper should be written in English and should be clear and concise, with proper structure and formatting.
    
  2.    Include images, graphs, and tables as necessary to support your analysis.
    
  3.    Avoid extensive use of AI-generated content and plagiarism or copying from classmates.
    
  4.    Save your final paper and the references that you used in one folder called Writing.
    
  5.    The paper should be no less than 5 pages, and you will follow the template from (CVPR 2024), which can be found in PaperForReview.docx.
      Paper Structure:
      • Title,
      Abstract,
      Introduction
      • Methodology: •
      Description of YOLO-based single-stage object detector implementation.
      • Description of Faster R-CNN-based two-stage object detector implementation.
      • Experimental Setup: • Description of dataset: PASCAL VOC 2007 object detection dataset.        • Evaluation metrics: mAP, inference speed, training time.
      • Results and Discussion: • Performance comparison between YOLO and Faster R-CNN.        • Analysis of detection accuracy.
      • Conclusion, References Grading Criteria:
    
  6.    Implementation of object detection algorithms (40%).
    
  7.    Clarity and coherence of comparative analysis paper (30%).
    
  8.    Depth of analysis and insights provided (20%).
    
  9.    Presentation, formatting, and adherence to submission requirements (10%).
      Final Submission: 1.        Zip file that should include the Coding folder and the Writing folder.        The zip file should be named using your Chinese name and the English name.        2.        No late submissions.        Deadline: 1 June 2024, 8 p.m.
    

可以看到上面内容是英文。。。《Python图像处理》,一做一个不吱声。

下面只是我+AI的一个参考,并不是正确答案,毕竟也找不到正确答案,而且感觉这个代码好多年了,不仅不知道哪里少代码,还有几个版本上的问题。

关键都是英文,看起来不是很方便,为了方便,下面的介绍就中英结合了。

首先下载作业,压缩包。

Ⅰ [可选] 下载数据集

If you download the datasets yourself.

Datasets from VOC2007.

The PASCAL Visual Object Classes Challenge 2007 (VOC2007) (ox.ac.uk)

在这里插入图片描述

Unzip to a your local DIR.

Example: E:\datasets\voc

Then create a empty TXT file in this DIR.

Because it’s in the a5_helper.py has function get_pascal_voc2007_data()

def get_pascal_voc2007_data(image_root, split='train'):
  """
  Use torchvision.datasets
  https://pytorch.org/docs/stable/torchvision/datasets.html#torchvision.datasets.VOCDetection
  """
  check_file = os.path.join(image_root, "extracted.txt")
  download = not os.path.exists(check_file)

  train_dataset = datasets.VOCDetection(image_root, year='2007', image_set=split,
                                    download=download)

  open(check_file, 'a').close()
  return train_dataset

在这里插入图片描述

Ⅱ 使用Pycharm 打开代码

此处省略1万字。。。

Ⅲ 安装 Jupyter lab

这个主要是为了执行笔记本文件.ipynb。这个也不介绍,省略。

Ⅳ 开始修改代码

  1. IP24目录下所有导入eecs598都删掉。

    删除所有的 import eecs598

  2. 修改single_stage_detector.py

    Edit single_stage_detector.py

    在这里插入图片描述

    This code is long long, you can typing code yourself or get in my CSDN resource: 1. single-stage-detector.py. 看文章最后。

    Note: It’s best to write your own code for this part. Mine is just a reference code.

    简单介绍一下几个函数的实现:AI 解释哈。

    single_stage_detector.py

    def GenerateAnchor(anc, grid):
    为每个图像生成所有锚框(anchor boxes)的坐标,它们是在图像的不同位置和尺度上预定义的边界框,用于预测目标的位置和大小。
    
    输入:
    anc: 一个形状为 (A, 2) 的张量,表示要考虑的每个网格点上的锚框形状。anc[a] = (w, h) 给出第 a 个锚框形状的宽度和高度。
    grid: 一个形状为 (B, H', W', 2) 的张量,给出从主干特征图中每个特征的中心坐标 (x, y)。这是从 GenerateGrid 函数返回的张量。
    输出:
    anchors: 一个形状为 (B, A, H', W', 4) 的张量,给出整个图像的所有锚框的位置。anchors[b, a, h, w] 是一个中心位于 grid[b, h, w] 的锚框,其形状由 anc[a] 给出。锚框参数化为 (x_tl, y_tl, x_br, y_br),其中 (x_tl, y_tl)(x_br, y_br) 分别给出框的左上角和右下角的 xy 坐标。
    
    实现:
    代码获取输入张量 grid 和 anc 的形状信息,分别存储在 B, H, W 和 A 变量中。
    然后,创建一个形状为 (B, A, H, W, 4) 的全零张量 anchors,用于存储所有锚框的坐标。这里假设使用 CUDA 设备进行计算。
    使用四重嵌套循环遍历每个批次、每个锚框、每个高度和宽度。
    在循环内部,计算每个锚框的左上角和右下角坐标:
    x_tl = grid[b, h, w, 0] - anc[a, 0] / 2:锚框左上角的 x 坐标,从网格中心的 x 坐标减去锚框宽度的一半。
    y_tl = grid[b, h, w, 1] - anc[a, 1] / 2:锚框左上角的 y 坐标,从网格中心的 y 坐标减去锚框高度的一半。
    x_br = grid[b, h, w, 0] + anc[a, 0] / 2:锚框右下角的 x 坐标,从网格中心的 x 坐标加上锚框宽度的一半。
    y_br = grid[b, h, w, 1] + anc[a, 1] / 2:锚框右下角的 y 坐标,从网格中心的 y 坐标加上锚框高度的一半。
    将计算出的坐标存储在 anchors 张量中。
    
    返回计算出的所有锚框的坐标张量 anchors。
    
    
    def GenerateProposal(anchors, offsets, method='YOLO'):
    
    用于根据给定的锚框(anchors)和偏移量(offsets)生成区域提议(proposals)。这个函数支持两种不同的转换方法:'YOLO''FasterRCNN'。
    
    输入:
    anchors: 一个形状为 (B, A, H', W', 4) 的张量,表示锚框的位置,其中 B 是批次大小,A 是锚框的数量,H' 和 W' 是特征图的高度和宽度,4 表示每个锚框由左上角和右下角坐标组成。
    offsets: 一个形状为 (B, A, H', W', 4) 的张量,表示应用于每个锚框的偏移量。对于每个锚框,偏移量包括 (tx, ty, tw, th),分别表示中心点 x 和 y 的偏移以及宽度和高度的缩放因子。
    method: 一个字符串,指定使用的转换方法,可以是 'YOLO''FasterRCNN'。
    
    输出:
    proposals: 一个形状为 (B, A, H', W', 4) 的张量,表示转换后的区域提议。
    
    代码实现:
    首先,代码检查 method 是否为 'YOLO''FasterRCNN',并初始化 proposals 张量为零。
    使用四重嵌套循环遍历每个批次、每个锚框、每个高度和宽度。
    在循环内部,从 anchors 和 offsets 中提取相应的坐标和偏移量。
    根据 method 的不同,应用不同的转换公式:
    对于 'FasterRCNN',中心点的偏移量 tx 和 ty 是相对于锚框原始宽度和高度的比例。
    对于 'YOLO',中心点的偏移量 tx 和 ty 是直接加到锚框的中心点上。
    计算新的宽度和高度,使用 torch.exp(tw) 和 torch.exp(th) 来确保宽度和高度始终为正。
    计算新的左上角和右下角坐标,并将它们存储在 proposals 张量中。
    
    返回值:
    函数返回计算出的所有区域提议的坐标张量 proposals。
    
  3. 开始修改运行文件single_stage_detector_yolo.ipynb

    You can also write them together in main.py.

    # 这里导入了包
    import torch
    from a5_helper import *
    
    # 设置了路径
    train_dataset = r"E:\datasets\voc"
    val_dataset = train_dataset
    
    train_dataset = get_pascal_voc2007_data(train_dataset, 'train')
    # val_dataset = get_pascal_voc2007_data(train_dataset, 'val')
    
    train_dataset = torch.utils.data.Subset(train_dataset, torch.arange(0, 2500)) # use 2500 samples for training
    train_loader = pascal_voc2007_loader(train_dataset, 10)
    val_loader = pascal_voc2007_loader(train_dataset, 10) 
    print("加载完成!")
    
    # 创建迭代器
    train_loader_iter = iter(train_loader)
    
    # 获取下一个批次
    img, ann, _, _, _ = train_loader_iter.__next__()
    
    print('img has shape: ', img.shape)
    print('ann has shape: ', ann.shape)
    
    print('Image 1 has only two annotated objects, so ann[1] is padded with -1:')
    print(ann[1])
    
    print('\nImage 2 has six annotated objects:, so ann[2] is not padded:')
    print(ann[2])
    
    print('\nEach row in the annotation tensor indicates (x_tl, y_tl, x_br, y_br, class).')
    

    ……

评估

这部分有问题,我也不懂,反正写出来了,不知道啥问题。ap最后0.19

  1. 将上面的结果转一下格式,用于评估,所有类一样的放在一起
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 #
# @Time    : 2024/5/20 16:47
# @Author  : # @Email   : # @File    : 结果txt转换.py
# @Software: PyCharm
import os

def process_files(directory, outdir):
    # 创建一个字典来保存每个类型的数据
    data_by_type = {}

    # 遍历目录中的所有文件
    for filename in os.listdir(directory):
        if filename.endswith('.txt'):
            with open(os.path.join(directory, filename), 'r') as file:
                for line in file:
                    # 解析每一行,提取类型和数据
                    parts = line.strip().split()
                    if len(parts) == 6:
                        type_name, confidence, x1, y1, x2, y2 = parts
                        # 将数据添加到对应类型的字典中
                        if type_name not in data_by_type:
                            data_by_type[type_name] = []
                        data_by_type[type_name].append(' '.join([filename.split(".txt")[0], confidence, x1, y1, x2, y2]))

    # 将每个类型的数据写入到单独的文件中
    for type_name, data in data_by_type.items():
        print(type_name)
        with open(f'{outdir + type_name}.txt', 'w') as output_file:
            output_file.write('\n'.join(data))

# 使用函数
process_files(r'./mAP/input/detection-results/', r'./mAP/input/detection-results-cls/')

  1. 计算
import pickle

import os

import numpy as np
import matplotlib.pyplot as plt
import torch

from a5_helper import idx_to_class, pascal_voc2007_loader, class_to_idx
from faster_rcnn_pytorch_master.lib.datasets.voc_eval import voc_ap, parse_rec
from faster_rcnn_pytorch_master.lib.datasets.voc_eval import voc_ap, parse_rec, voc_eval

def plot_pr_curve(precisions, recalls):
    plt.figure()
    plt.plot(recalls, precisions, lw=2)
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.title('Precision-Recall Curve')
    plt.savefig('pr_curve.png')
    plt.close()


def evaluate_map(output_dir):
    # Compute AP for each category
    aps = []
    for i, cls in enumerate(class_to_idx):
        print(i, cls)
        if cls == '__background__':
            continue
        rec, prec, ap = voc_eval(r'D:\Python\work\python图像处理实践\Coding\mAP\input\detection-results-cls\{:s}.txt',
                                 r"E:\datasets\voc\VOCdevkit\VOC2007\Annotations\{:s}.xml",
                                 r"E:\datasets\voc\VOCdevkit\VOC2007\ImageSets\Main\train.txt", cls,
                                 "./cachedir", ovthresh=0.5, )
        # print(rec, prec, ap)
        print(cls, ap)
        aps += [ap]
        print(('AP for {} = {:.4f}'.format(cls, ap)))
        with open(os.path.join(output_dir, cls + '_pr.pkl'), 'wb') as f:
            pickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)
        plot_pr_curve(prec, rec)

    print(('Mean AP = {:.4f}'.format(np.mean(aps))))
    print('~~~~~~~~')
    # print('Results:')
    # for ap in aps:
    #     print(('{:.3f}'.format(ap)))
    print(('{:.3f}'.format(np.mean(aps))))
    print('~~~~~~~~')
    print('')
    print('--------------------------------------------------------------')
    print('Results computed with the **unofficial** Python eval code.')
    print('Results should be very close to the official MATLAB eval code.')
    print('Recompute with `./tools/reval.py --matlab ...` for your paper.')
    print('-- Thanks, The Management')
    print('--------------------------------------------------------------')

    # Compute mAP
    mAP = np.mean(aps)
    return mAP


def main():
    mAP = evaluate_map('mAP/input')
    print(f'Mean Average Precision (mAP): {mAP}')


if __name__ == '__main__':
    main()

Okay,这个代码真的太长了,不想粘贴了。

果然、训练模型花了十来个小时。。。这是作业?服!

Do you feel bad when you see this?

所有文件

It’s time for a showdown: I should give the attachment, otherwise I may be attacked by the Internet!

VOC2007 训练数据集

VOCtrainval_06-Nov-2007.tar

链接:https://pan.baidu.com/s/19hMEn-fwBjT5ikbWauSIfA?pwd=vapt
提取码:vapt
–来自百度网盘超级会员V6的分享

Yolo 和 Faster R-CNN 目标检测对比学习——作业原压缩包

IPFinal Project.rar

链接:https://pan.baidu.com/s/1h0g2SRsWfBZZ4VHziisGnw?pwd=sdvl
提取码:sdvl
–来自百度网盘超级会员V6的分享

CVPR 2024 word模板

链接:https://pan.baidu.com/s/1OAVuCH35UXTKNidsag4ELg?pwd=nycl
提取码:nycl
–来自百度网盘超级会员V6的分享

训练修改的文件、训练的结果
链接:https://pan.baidu.com/s/1r-dPd9W70LrNVsfeNDvd3A?pwd=li16
提取码:li16
–来自百度网盘超级会员V6的分享

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1696542.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【python】python小区住房数据可视化(源码+数据)【独一无二】

👉博__主👈:米码收割机 👉技__能👈:C/Python语言 👉公众号👈:测试开发自动化【获取源码商业合作】 👉荣__誉👈:阿里云博客专家博主、5…

树莓派4B 有电但无法启动

试过多个SD卡,反复烧系统镜像都无法启动。接HDMI显示器没有信号输出,上电后PWR红灯长亮,ACT绿灯闪一下就不亮了,GPIO几个电源脚有电,芯片会发热,测量多个TP点电压好像都正常。 ……

【电子元件】TL431 电压基准

TL431(C23892)是一种常用的可调节精密电压基准和电压调节器。它广泛应用于电源管理、精密参考电压和稳压电路等领域。以下是TL431的一些关键特点和使用方法: 关键特点 可调输出电压:TL431的输出电压可以通过外部电阻网络在2.495V到36V范围内调整。精度高…

【笔记】Pytorch安装配置

参考视频 安装前建议预留至少10个G的空间,会省下很多麻烦 查看安装是否成功,可以在Anaconda Prompt里输入conda list查看conda环境是否配置了pytorch/torchvision 1.安装anaconda 2.安装 CUDA CUDA在官网直接安装即可,需要先查看自己电脑…

fpga问题整理

1、quartus联合modelsim仿真 无波形 问题: modelsim仿真无波形,打开transcript可以看到警告。 警告: # ** Warning: (vlog-2083) f:/program files/altera/ 13.1/quartus/ eda/sim_lib/ altera_lnsim.sv(22728): Carriage return (0x0D) is…

【前端笔记】Vue项目报错Error: Cannot find module ‘webpack/lib/RuleSet‘

网上搜了下发现原因不止一种,这里仅记录本人遇到的原因和解决办法,仅供参考 原因:因为某种原因导致本地package.json中vue/cli与全局vue/cli版本不同导致冲突。再次提示,这是本人遇到的,可能和大家有所不同&#xff0c…

子线程无法访问父线程中通过ThreadLocal设置的变量

学习过ThreadLocal的童鞋都知道,在子线程中,是无法访问父线程通过ThreadLocal设置的变量的。 package thread;/*** author heyunlin* version 1.0*/ public class ThreadLocalExample {public static void main(String[] args) throws InterruptedExcep…

搭建CMS系统

搭建CMS系统 1 介绍 内容管理系统(Content Management System,CMS)是一种用于管理、发布和修改网站内容的系统。开源的CMS系统有WordPress、帝国CMS等,国产的Halo很不错。 WordPress参考地址 # 官网 https://wordpress.org/# …

信号量——多线程

信号量的本质就是一个计数器 在多线程访问临界资源的时候,如果临界资源中又有很多份分好的资源,那么就可以通过信号量来表示里面还有多少份资源,且每份资源只有一个线程可以访问 线程申请信号量成功,就一定有一份资源是你的&…

SAP-技巧篇实现GUI免密码登录

做为上千万的软件怎么会没有免密码登录呢 01 — 背景需求 如何实现SAP GUI免密码登录,不输入密码实现系统自动登录。 免责声明:谨慎设置,因免密登录导致数据泄密,作者概不负责。 02 — 实现 客户端要求:SAP G…

微信小程序毕业设计-学生知识成果展示与交流系统项目开发实战(附源码+演示视频+LW)

大家好!我是程序猿老A,感谢您阅读本文,欢迎一键三连哦。 💞当前专栏:微信小程序毕业设计 精彩专栏推荐👇🏻👇🏻👇🏻 🎀 Python毕业设计…

17.分类问题

机器学习分类问题详解与实战 介绍 在机器学习中,分类问题是一类常见的监督学习任务,其目标是根据输入特征将数据样本划分为预先定义的类别之一。分类问题广泛应用于各个领域,如图像识别、自然语言处理、金融风险评估等。本文将详细介绍机器…

vue3瀑布流示例,左侧菜单根据窗口滚动条进行固定和取消固定,实现瀑布流demo

瀑布流demo的实现效果: 效果说明: 1.使用vue3实现瀑布流效果; 2.瀑布流横向设置5等分,可根据个人需求调整; 3.左侧菜单可根据右侧滚动条滑动时进行固定和取消固定,实现更优的展示效果; 4.瀑…

驱动命令之insmod depmod modprobe rmmod modinfo lsmod

insmod命令 insmod需指定所需加载模块的路径&#xff0c;且只加载所指定的模块&#xff0c;如果所指定的模块依赖于其他模块&#xff0c;insmod不会自动添加&#xff1b; 语法 insmod [-fkmpsvxX][-o <模块名称>][模块文件][符号名称 符号值] 参数说明&#xff1a; -f…

【代码随想录训练营】【Day 29】【回溯-3】| Leetcode 39, 41, 131

【代码随想录训练营】【Day 29】【回溯-3】| Leetcode 39&#xff0c; 41&#xff0c; 131 需强化知识点 startInex作用&#xff1a;一是处理是否可以有重复值&#xff0c;二是实现纵向遍历&#xff08;不能没有&#xff09;去重要在数组有序的前提下进行分割问题 题目 39.…

Comfyui工作流报错:Image scale to side 报错,安装了Derfuu-Nodes仍然没法运行

&#x1f386;问题描述 最近很多朋友在玩comfyui的时候&#xff0c;发现有个图像缩放的节点用不了了&#xff0c;同时报错&#xff1a; When loading the graph, the following node types were not found: Image scale to side Nodes that have failed to load will show as…

数据结构之栈和队列(超详解

目录 一.栈 1.栈的基本概念 2.栈的基本操作 3.栈的储存结构 ①栈的顺序储存 (1)基本概念 (2)代码实现 ②栈的链式储存 (1)基本概念 (2)代码实现 二.队列 1.队列的基本概念 2.队列的基本操作 3.队列的储存结构 ①队列的链式储存 (1)基本概念 ​编辑 (2)代码实现 ②…

C++进阶之路:何为拷贝构造函数,深入理解浅拷贝与深拷贝(类与对象_中篇)

✨✨ 欢迎大家来访Srlua的博文&#xff08;づ&#xffe3;3&#xffe3;&#xff09;づ╭❤&#xff5e;✨✨ &#x1f31f;&#x1f31f; 欢迎各位亲爱的读者&#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢&#xff0c;在这里我会分享我的知识和经验。&am…

Java的线程的使用

一.两种创建线程的方式 1.继承Thread类&#xff08;匿名内部类&#xff09; 创建方式&#xff1a; 1.定义一个子类继承Thread&#xff0c;重写run方法 2.创建子类对象&#xff0c; 3.调用子类对象的start方法&#xff08;启动还是执行的run方法&#xff09; 优缺点&#x…