Rolla‘s homework:Image Processing with Python Final Project

對比學習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.datasetshttps://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_datasettrain_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 osdef 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 pickleimport osimport numpy as np
import matplotlib.pyplot as plt
import torchfrom 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_evaldef 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 categoryaps = []for i, cls in enumerate(class_to_idx):print(i, cls)if cls == '__background__':continuerec, 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 mAPmAP = np.mean(aps)return mAPdef 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.pswp.cn/web/15467.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/15467.shtml
英文地址,請注明出處:http://en.pswp.cn/web/15467.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 1049.最后一塊石頭的重量II

思路:01背包 其實這道題我們可以轉化一下,乍一看有點像區間dp,很像區間合并那種類型。 但是,后來發現,這道題的精髓在于你如何轉成背包問題。我們可以把這個石頭分成兩堆,然后求出來這兩堆的最小差值就行…

使用git生成SSH公鑰,并設置SSH公鑰

1、在git命令行里輸入以下命令 ssh-keygen -t rsa 2、按回車,然后會看到以下字眼 Generating public/private rsa key pair. Enter file in which to save the key (/c/Users/xxx/.ssh/id_rsa) 例: 3、繼續回車,然后會看到以下字眼 Enter…

【面試干貨】數據庫樂觀鎖,悲觀鎖的區別,怎么實現

【面試干貨】數據庫樂觀鎖,悲觀鎖的區別,怎么實現 1、樂觀鎖,悲觀鎖的區別2、總結 💖The Begin💖點點關注,收藏不迷路💖 1、樂觀鎖,悲觀鎖的區別 悲觀鎖(Pessimistic Lo…

web前端框架設計第十課-組件

web前端框架設計第十課-組件 一.預習筆記 組件:Vue最強大的功能之一 1.局部組件注冊 注意事項:template標簽中只能有一個根元素 2.全局組件的注冊 注意事項:組件名的大小寫需要注意(實踐) 3.案例(查詢框…

Vivado 使用教程(個人總結)

Vivado 是 Xilinx 公司推出的一款用于 FPGA 設計的集成開發環境 (IDE),提供了從設計輸入到實現、驗證、調試和下載的完整流程。本文將詳細介紹 Vivado 的使用方法,包括項目創建、設計輸入、約束文件、綜合與實現、仿真、調試、下載配置等步驟。 一、創建…

設計模式--責任鏈模式

責任鏈模式是一種行為設計模式,它允許將請求沿著處理者鏈進行發送。請求會沿鏈傳遞,直到某個處理者對象負責處理它。這種模式在許多應用場景中非常有用,例如在處理用戶輸入、過濾請求以及實現多級審核時。 應用場景 處理用戶輸入&#xff1…

kafka之consumer參數auto.offset.reset

Kafka的auto.offset.reset 參數是用于指定消費者在啟動時如何處理偏移量(offset)的。這個參數有三個主要的取值:earliest、latest和none。 earliest: 當各分區下有已提交的offset時,從提交的offset開始消費&#xff1b…

HCIP-VLAN綜合實驗

一、實驗拓撲 二、實驗要求 1、pc1和pc3所在接口為access;屬于vlan 2; PC2/PC4/PC5/PC6處于同一網段’其中PC2可以訪問PC4/PC5/PC6; PC4可以訪問PC6;PC5不能訪問PC6; 2、PC1/PC3與PC2/PC4/PC5/PC6不在同一個網段; 3、所有PC通過DHCP獲取IP…

棧和隊列的應用-計算器實例

‘’‘ (11 3) 2 -5 順序存儲棧來實現 ’‘’ sqstack.h #ifndef SQSTACK_H__ #define SQSTACK_H__ #define MAXSIZE 32 typedef int datatype typedef struct node_st {datatype data[MAXSIZE]; int top;}sqstack;sqstack *st_create(void); int s…

閑話 .NET(5):.NET Core 有什么優勢?

前言 .NET Core 并不是 .NET FrameWork 的升級版,它是一個為滿足新一代的軟件設計要求而從頭重新開發的開發框架和平臺,所以它沒有 .NET FrameWork 的歷史包袱,相對于 .NET FrameWork,它具備很多優勢。 .NET Core 有哪些優勢&am…

智算中心帶寬漫談 -- 開篇

隱秘的角落 帶寬對高性能計算是一個永恒的話題,本質上,帶寬即數據交換的速率,單位時間的傳輸數據越多,帶寬就越高,但對高性能計算來說,對高帶寬的渴求永無止境,好比宏觀現實世界中的車道&#…

QT實現線程的四種方式(QThread、QRunnable和QThreadPool、QObject、QtConcurrent)

在當今高性能計算需求日益增長的背景下,多線程編程已成為提升應用性能的重要手段。Qt框架,作為一個功能全面、跨平臺的C++應用程序開發工具包,為我們提供了多種多線程實現方案。本文將介紹QThread類在Qt多線程編程中的應用,以及如何通過QRunnable和QThreadPool、QObject的m…

C# GDI+ 繪制文字不同的操作系統渲染文字大小不同

一、C# GDI 繪制文字不同的操作系統渲染文字大小不同 原因:使用Font 字體的時候,沒有指定字體渲染的單位。 不同系統的默認字體單位會不同。 二、解決方案: 在指定字體的時候,指定字體大小,同時也要設置字體的單位 …

sqlserver 創建表,列及表,列描述

-- 創建表 CREATE TABLE Employees (EmployeeID INT PRIMARY KEY,EmployeeName NVARCHAR(100),EmployeeEmail NVARCHAR(100) );-- 為表添加描述 EXEC sp_addextendedproperty name NMS_Description, value N員工信息表, level0type NSchema, level0name dbo, level1type N…

springboot整合kkFileView部署,前端使用

前言: 官方文檔:https://kkfileview.keking.cn/zh-cn/docs/production.html docker方式或加入星球獲取發行包直接獲取啟動,無需以下步驟: 拉取鏡像# 網絡環境方便訪問docker中央倉庫 docker pull keking/kkfileview:4.1.0# 網…

pytest框架的代碼如何用vscode進行debug

{"version": "0.2.0","configurations": [{"name": "Python: Run My Module", // 配置名稱,將在調試配置下拉列表中顯示"type": "debugpy", // 調試類型,這里是Python"requ…

二元關系表示

一、二元關系的定義和表示 什么是二元關系?對集合A和B,A\timesB的任意子集R為A到B的一個二元關系。當AB時,A\timesA的任一子集R稱為A上的一個二元關系。在不引起誤解的情況下,二元關系可簡稱關系。 若|A|m,|B|n,則A到…

常用字體映射字典

表格形式 英文字體名稱中文字體名稱SimSun宋體SimHei黑體KaiTi楷體FangSong仿宋YouYuan幼圓LiSu隸書NSimSun新宋體SimSun-ExtB宋體-ExtBFangSong_GB2312仿宋_GB2312KaiTi_GB2312楷體_GB2312Microsoft YaHei微軟雅黑Microsoft JhengHei微軟正黑體STXihei華文細黑STKaiti華文楷體…

手機版AI寫作軟件哪個好用?5款AI寫作軟件分享

在這個快節湊的時代,人們對于高效、便捷的創作方式很是追求。尤其是在人工智能技術發展迅速的今天,AI寫作軟件的出現,讓很多自媒體創作者都會想到在手機上面進內容創作,這樣不僅能提高工作效率,而且工作的自由度會更高…

自動化運維(AIOps): 現代IT管理的革命

在數字化時代,企業的 IT 系統變得愈加復雜。從云計算到大數據,從物聯網到人工智能,技術的飛速發展使得企業面臨前所未有的挑戰。這種復雜性不僅體現在數據量和數據流的增加上,還包括高成本和高錯誤率的運維需求。在此背景下&#…