YOLOv5 分類模型 預處理 OpenCV實現

YOLOv5 分類模型 預處理 OpenCV實現

flyfish

YOLOv5 分類模型 預處理 PIL 實現
YOLOv5 分類模型 OpenCV和PIL兩者實現預處理的差異

YOLOv5 分類模型 數據集加載 1 樣本處理
YOLOv5 分類模型 數據集加載 2 切片處理
YOLOv5 分類模型 數據集加載 3 自定義類別

YOLOv5 分類模型的預處理(1) Resize 和 CenterCrop
YOLOv5 分類模型的預處理(2)ToTensor 和 Normalize

YOLOv5 分類模型 Top 1和Top 5 指標說明
YOLOv5 分類模型 Top 1和Top 5 指標實現

判斷圖像是否是np.ndarray類型和維度

OpenCV讀取一張圖像時,類型類型就是<class 'numpy.ndarray'>,這里判斷圖像是否是np.ndarray類型
dim是dimension維度的縮寫,shape屬性的長度也是它的ndim
灰度圖的shape為HW,二個維度
RGB圖的shape為HWC,三個維度
在這里插入圖片描述

def _is_numpy_image(img):return isinstance(img, np.ndarray) and (img.ndim in {2, 3})

實現ToTensor和Normalize

def totensor_normalize(img):print("preprocess:",img.shape)images = (img/255-mean)/stdimages = images.transpose((2, 0, 1))# HWC to CHWimages = np.ascontiguousarray(images)return images

實現Resize

插值可以是以下參數

# 'nearest': cv2.INTER_NEAREST,
# 'bilinear': cv2.INTER_LINEAR,
# 'area': cv2.INTER_AREA,
# 'bicubic': cv2.INTER_CUBIC,
# 'lanczos': cv2.INTER_LANCZOS4
def resize(img, size, interpolation=cv2.INTER_LINEAR):r"""Resize the input numpy ndarray to the given size.Args:img (numpy ndarray): Image to be resized.size: like pytroch about size interpretation flyfish.interpolation (int, optional): Desired interpolation. Default is``cv2.INTER_LINEAR``  Returns:numpy Image: Resized image.like opencv"""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))if not (isinstance(size, int) or (isinstance(size, collections.abc.Iterable) and len(size) == 2)):raise TypeError('Got inappropriate size arg: {}'.format(size))h, w = img.shape[0], img.shape[1]if isinstance(size, int):if (w <= h and w == size) or (h <= w and h == size):return imgif w < h:ow = sizeoh = int(size * h / w)else:oh = sizeow = int(size * w / h)else:ow, oh = size[1], size[0]output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)if img.shape[2] == 1:return output[:, :, np.newaxis]else:return output

實現CenterCrop

def crop(img, i, j, h, w):"""Crop the given Image flyfish.Args:img (numpy ndarray): Image to be cropped.i: Upper pixel coordinate.j: Left pixel coordinate.h: Height of the cropped image.w: Width of the cropped image.Returns:numpy ndarray: Cropped image."""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))return img[i:i + h, j:j + w, :]def center_crop(img, output_size):if isinstance(output_size, numbers.Number):output_size = (int(output_size), int(output_size))h, w = img.shape[0:2]th, tw = output_sizei = int(round((h - th) / 2.))j = int(round((w - tw) / 2.))return crop(img, i, j, th, tw)

完整

import time
from models.common import DetectMultiBackend
import os
import os.path
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union
import cv2
import numpy as np
import collections
import torch
import numbersclasses_name=['n02086240', 'n02087394', 'n02088364', 'n02089973', 'n02093754', 'n02096294', 'n02099601', 'n02105641', 'n02111889', 'n02115641']mean=[0.485, 0.456, 0.406]
std=[0.229, 0.224, 0.225]def _is_numpy_image(img):return isinstance(img, np.ndarray) and (img.ndim in {2, 3})def totensor_normalize(img):print("preprocess:",img.shape)images = (img/255-mean)/stdimages = images.transpose((2, 0, 1))# HWC to CHWimages = np.ascontiguousarray(images)return imagesdef resize(img, size, interpolation=cv2.INTER_LINEAR):r"""Resize the input numpy ndarray to the given size.Args:img (numpy ndarray): Image to be resized.size: like pytroch about size interpretation flyfish.interpolation (int, optional): Desired interpolation. Default is``cv2.INTER_LINEAR``  Returns:numpy Image: Resized image.like opencv"""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))if not (isinstance(size, int) or (isinstance(size, collections.abc.Iterable) and len(size) == 2)):raise TypeError('Got inappropriate size arg: {}'.format(size))h, w = img.shape[0], img.shape[1]if isinstance(size, int):if (w <= h and w == size) or (h <= w and h == size):return imgif w < h:ow = sizeoh = int(size * h / w)else:oh = sizeow = int(size * w / h)else:ow, oh = size[1], size[0]output = cv2.resize(img, dsize=(ow, oh), interpolation=interpolation)if img.shape[2] == 1:return output[:, :, np.newaxis]else:return outputdef crop(img, i, j, h, w):"""Crop the given Image flyfish.Args:img (numpy ndarray): Image to be cropped.i: Upper pixel coordinate.j: Left pixel coordinate.h: Height of the cropped image.w: Width of the cropped image.Returns:numpy ndarray: Cropped image."""if not _is_numpy_image(img):raise TypeError('img should be numpy image. Got {}'.format(type(img)))return img[i:i + h, j:j + w, :]def center_crop(img, output_size):if isinstance(output_size, numbers.Number):output_size = (int(output_size), int(output_size))h, w = img.shape[0:2]th, tw = output_sizei = int(round((h - th) / 2.))j = int(round((w - tw) / 2.))return crop(img, i, j, th, tw)class DatasetFolder:def __init__(self,root: str,) -> None:self.root = rootif classes_name is None or not classes_name:classes, class_to_idx = self.find_classes(self.root)print("not classes_name")else:classes = classes_nameclass_to_idx ={cls_name: i for i, cls_name in enumerate(classes)}print("is classes_name")print("classes:",classes)print("class_to_idx:",class_to_idx)samples = self.make_dataset(self.root, class_to_idx)self.classes = classesself.class_to_idx = class_to_idxself.samples = samplesself.targets = [s[1] for s in samples]@staticmethoddef make_dataset(directory: str,class_to_idx: Optional[Dict[str, int]] = None,) -> List[Tuple[str, int]]:directory = os.path.expanduser(directory)if class_to_idx is None:_, class_to_idx = self.find_classes(directory)elif not class_to_idx:raise ValueError("'class_to_index' must have at least one entry to collect any samples.")instances = []available_classes = set()for target_class in sorted(class_to_idx.keys()):class_index = class_to_idx[target_class]target_dir = os.path.join(directory, target_class)if not os.path.isdir(target_dir):continuefor root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):for fname in sorted(fnames):path = os.path.join(root, fname)if 1:  # 驗證:item = path, class_indexinstances.append(item)if target_class not in available_classes:available_classes.add(target_class)empty_classes = set(class_to_idx.keys()) - available_classesif empty_classes:msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "return instancesdef find_classes(self, directory: str) -> Tuple[List[str], Dict[str, int]]:classes = sorted(entry.name for entry in os.scandir(directory) if entry.is_dir())if not classes:raise FileNotFoundError(f"Couldn't find any class folder in {directory}.")class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}return classes, class_to_idxdef __getitem__(self, index: int) -> Tuple[Any, Any]:path, target = self.samples[index]sample = self.loader(path)return sample, targetdef __len__(self) -> int:return len(self.samples)def loader(self, path):print("path:", path)img = cv2.imread(path)  # BGR HWCimg=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)#RGBprint("type:",type(img))return imgdef time_sync():return time.time()dataset = DatasetFolder(root="/media/flyfish/datasets/imagewoof/val")
weights = "/home/classes.pt"
device = "cpu"
model = DetectMultiBackend(weights, device=device, dnn=False, fp16=False)
model.eval()def classify_transforms(img):img=resize(img,224)img=center_crop(img,224)img=totensor_normalize(img)return img;pred, targets, loss, dt = [], [], 0, [0.0, 0.0, 0.0]
# current batch size =1
for i, (images, labels) in enumerate(dataset):print("i:", i)print(images.shape, labels)im = classify_transforms(images)images=torch.from_numpy(im).to(torch.float32) # numpy to tensorimages = images.unsqueeze(0).to("cpu")print(images.shape)t1 = time_sync()images = images.to(device, non_blocking=True)t2 = time_sync()# dt[0] += t2 - t1y = model(images)y=y.numpy()print("y:", y)t3 = time_sync()# dt[1] += t3 - t2tmp1=y.argsort()[:,::-1][:, :5]print("tmp1:", tmp1)pred.append(tmp1)print("labels:", labels)targets.append(labels)print("for pred:", pred)  # listprint("for targets:", targets)  # list# dt[2] += time_sync() - t3pred, targets = np.concatenate(pred), np.array(targets)
print("pred:", pred)
print("pred:", pred.shape)
print("targets:", targets)
print("targets:", targets.shape)
correct = ((targets[:, None] == pred)).astype(np.float32)
print("correct:", correct.shape)
print("correct:", correct)
acc = np.stack((correct[:, 0], correct.max(1)), axis=1)  # (top1, top5) accuracy
print("acc:", acc.shape)
print("acc:", acc)
top = acc.mean(0)
print("top1:", top[0])
print("top5:", top[1])

結果

pred: [[0 3 6 2 1][0 7 2 9 3][0 5 6 2 9]...[9 8 7 6 1][9 3 6 7 0][9 5 0 2 7]]
pred: (3929, 5)
targets: [0 0 0 ... 9 9 9]
targets: (3929,)
correct: (3929, 5)
correct: [[          1           0           0           0           0][          1           0           0           0           0][          1           0           0           0           0]...[          1           0           0           0           0][          1           0           0           0           0][          1           0           0           0           0]]
acc: (3929, 2)
acc: [[          1           1][          1           1][          1           1]...[          1           1][          1           1][          1           1]]
top1: 0.86230594
top5: 0.98167473

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/166454.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/166454.shtml
英文地址,請注明出處:http://en.pswp.cn/news/166454.shtml

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

相關文章

Bin、Hex、ELF、AXF的區別

1.Bin Bin文件是最純粹的二進制機器代碼, 或者說是"順序格式"。按照assembly code順序翻譯成binary machine code&#xff0c;內部沒有地址標記。Bin是直接的內存映象表示&#xff0c;二進制文件大小即為文件所包含的數據的實際大小。 BIN文件就是直接的二進制文件&…

關于python 語音轉字幕,字幕轉語音大雜燴

文字轉語音 Python語音合成之第三方庫gTTs/pyttsx3/speech橫評(內附使用方法)_python_腳本之家 代碼示例 from gtts import gTTStts gTTS(你好你在哪兒&#xff01;,langzh-CN)tts.save(hello.mp3)import pyttsx3engine pyttsx3.init() #創建對象"""語速"…

目前比較好用的護眼臺燈,小學生適合的護眼臺燈推薦

隨著技術的發展&#xff0c;燈光早已成為每家每戶都需要的東西。但是燈光不好可能會對眼睛造成傷害是很多人沒有注意到的。現在隨著護眼燈產品越來越多&#xff0c;市場上臺燈的選擇越來越多樣化&#xff0c;如何選擇一個對眼睛無傷害、無輻射的臺燈成為許多家長首先要考慮的問…

【C++初階】四、類和對象(構造函數、析構函數、拷貝構造函數、賦值運算符重載函數)

相關代碼gitee自取&#xff1a; C語言學習日記: 加油努力 (gitee.com) 接上期&#xff1a; 【C初階】三、類和對象 &#xff08;面向過程、class類、類的訪問限定符和封裝、類的實例化、類對象模型、this指針&#xff09; -CSDN博客 引入&#xff1a;類的六個默認成員函數…

如何使用springboot服務端接口公網遠程調試——實現HTTP服務監聽

&#x1f308;個人主頁&#xff1a;聆風吟 &#x1f525;系列專欄&#xff1a;網絡奇遇記、Cpolar雜談 &#x1f516;少年有夢不應止于心動&#xff0c;更要付諸行動。 文章目錄 &#x1f4cb;前言一. 本地環境搭建1.1 環境參數1.2 搭建springboot服務項目 二. 內網穿透2.1 安裝…

ATA-2042高壓放大器在細胞的剪切應力傳感器研究中的應用

微流控技術是一種通過微小的通道和微型裝置對流體進行精確操控和分析的技術。它是現代醫學技術發展過程中的一種重要的生物醫學工程技術&#xff0c;具有廣泛的應用前景和重要性。它在高通量分析、個性化醫療、細胞篩選等方面有著巨大的潛力&#xff0c;Aigtek安泰電子今天就將…

.Net面試題4

1.請解釋一下泛型&#xff08;Generics&#xff09;在C#中的作用。 泛型是一種將數據類型參數化的機制&#xff0c;使得代碼可以在編譯時具有更強的類型安全性和靈活性。C#中的泛型可以用于類、接口、方法等的定義和實例化。泛型允許在編寫代碼時使用具有不同實參的類型&#x…

HR8833 雙通道H橋電機驅動芯片

HR8833為玩具、打印機和其它電機一T化應用提供一種雙通道電機驅動方案。HR8833提供兩種封裝&#xff0c;一種是帶有L露焊盤的TSSOP-16封裝&#xff0c;能改進散熱性能&#xff0c;且是無鉛產品&#xff0c;引腳框采用100&#xff05;無錫電鍍。另一種封裝為SOP16&#xff0c;不…

智駕芯片全矩陣「曝光」,這家企業的車載品牌正式官宣

隨著汽車智能化加速&#xff0c;智能駕駛芯片格局逐漸清晰。 針對L0-L2&#xff0c;業內基本采用智能前視一體機方案&#xff1b;要實現高速NOA、城市NOA等更為高階的智駕功能等&#xff0c;則基本采用域控制器方案。從前視一體機至域控&#xff0c;再逐步演進到艙駕一體、中央…

python基于DETR(DEtection TRansformer)開發構建鋼鐵產業產品智能自動化檢測識別系統

在前文中我們基于經典的YOLOv5開發構建了鋼鐵產業產品智能自動化檢測識別系統&#xff0c;這里本文的主要目的是想要實踐應用DETR這一端到端的檢測模型來開發構建鋼鐵產業產品智能自動化檢測識別系統。 DETR (DEtection TRansformer) 是一種基于Transformer架構的端到端目標檢…

springboot項目修改項目名稱

參考該文章正確修改項目名稱&#xff1a;SpringBoot項目怎么重命名_springboot修改項目名稱-CSDN博客

【Lodash】 Filter 與Map 的結合使用

用Filter過濾數據之后&#xff0c;想給某個字段重新賦值 在使用 filter() 方法過濾數據后&#xff0c;如果你想給某個字段賦值&#xff0c;你可以使用 map() 方法來修改數組中的元素。map() 方法可以對數組中的每個元素應用一個函數&#xff0c;并返回一個新的數組。 以下是一…

【Django使用】10大章31模塊md文檔,第5篇:Django模板和數據庫使用

當你考慮開發現代化、高效且可擴展的網站和Web應用時&#xff0c;Django是一個強大的選擇。Django是一個流行的開源Python Web框架&#xff0c;它提供了一個堅實的基礎&#xff0c;幫助開發者快速構建功能豐富且高度定制的Web應用 全套Django筆記直接地址&#xff1a; 請移步這…

外匯天眼:多名投資者賬戶被惡意清空,遠離volofinance!

最近&#xff0c;外匯平臺volofinance因有多名投資者投訴&#xff0c;“榮幸”成為外匯天眼黑平臺榜單中的一員&#xff0c;那么volofinance到底做了什么導致投資者前來投訴曝光呢&#xff1f; 起底volofinace 在網絡搜索中&#xff0c;關于volofinance的信息少之又少&#xf…

成為AI產品經理——模型評估指標

目錄 一、模型評估分類 1.在線評估 2.離線評估 二、離線模型評估 1.特征評估 ① 特征自身穩定性 ② 特征來源穩定性 ③ 特征成本 2.模型評估 ① 統計性評估 覆蓋度 最大值、最小值 分布形態 ② 模型性能指標 分類問題 回歸問題 ③ 模型的穩定性 模型評估指標分…

配置mvn打包參數,不同環境使用不同的配置文件

方法一&#xff1a; 首先在/resource目錄下創建各自環境的配置 要在不同的環境中使用不同的配置文件進行Maven打包&#xff0c;可以使用Maven的profiles特性和資源過濾功能。下面是配置Maven打包參數的步驟&#xff1a; 在項目的pom.xml文件中&#xff0c;添加profiles配置…

python 負數 處理

num_negative -4 print(num_negative) num_dec_to_hex hex(num_negative) print(負數轉十六進制&#xff1a; num_dec_to_hex) /---------------------------------------------------------/ -4 負數轉十六進制&#xff1a;-0x4通過上面代碼片段可以看到&#xff0c;python…

第一個Mybatis項目

&#xff08;一&#xff09;為什么要用Mybatis? &#xff08;1&#xff09;Mybatis對比JDBC而言&#xff0c;sql&#xff08;單獨寫在xml的配置文件中&#xff09;和java編碼分開&#xff0c;功能邊界清晰&#xff0c;一個專注業務&#xff0c;一個專注數據。 &#xff08;2&…

【C++】:多態

朋友們、伙計們&#xff0c;我們又見面了&#xff0c;本期來給大家解讀一下有關多態的知識點&#xff0c;如果看完之后對你有一定的啟發&#xff0c;那么請留下你的三連&#xff0c;祝大家心想事成&#xff01; C 語 言 專 欄&#xff1a;C語言&#xff1a;從入門到精通 數據結…

Linux(CentOS7)上安裝mysql

在CentOS中默認安裝有MariaDB&#xff08;MySQL的一個分支&#xff09;&#xff0c;可先移除/卸載MariaDB。 yum remove mariadb // 查看是否存在mariadb rpm -qa|grep -i mariadb // 卸載 mariadb rpm -e --nodeps rpm -qa|grep mariadb yum安裝 下載rpm // 5.6版本 wge…