汕頭百度網(wǎng)站建設(shè)成都網(wǎng)絡(luò)營銷品牌代理機(jī)構(gòu)
基于WIN10的64位系統(tǒng)演示
一、寫在前面
本期開始,我們學(xué)習(xí)深度學(xué)習(xí)圖像目標(biāo)檢測系列。
深度學(xué)習(xí)圖像目標(biāo)檢測是計(jì)算機(jī)視覺領(lǐng)域的一個(gè)重要子領(lǐng)域,它的核心目標(biāo)是利用深度學(xué)習(xí)模型來識別并定位圖像中的特定目標(biāo)。這些目標(biāo)可以是物體、人、動(dòng)物或其他可識別的實(shí)體。與傳統(tǒng)的圖像分類任務(wù)不同,目標(biāo)檢測不僅要確定圖像中存在哪些類別的目標(biāo),還要確定它們的確切位置和尺寸。這通常是通過在圖像上繪制一個(gè)或多個(gè)邊界框來實(shí)現(xiàn)的,這些邊界框精確地標(biāo)出了目標(biāo)的位置和范圍。
二、Faster R-CNN簡介
Faster R-CNN 是一種流行的深度學(xué)習(xí)圖像目標(biāo)檢測算法,由 Shaoqing Ren, Kaiming He, Ross Girshick 和 Jian Sun 在 2015 年提出。它是 R-CNN 系列模型中的一個(gè)重要里程碑,因?yàn)樗岣吡藱z測速度,同時(shí)保持了高精度。以下是 Faster R-CNN 的主要特點(diǎn)和組件:
(1)區(qū)域提議網(wǎng)絡(luò) (RPN):
Faster R-CNN 的核心創(chuàng)新是引入了一個(gè)叫做區(qū)域提議網(wǎng)絡(luò) (RPN) 的組件。RPN 能夠在卷積特征圖上直接生成目標(biāo)的邊界框提議,這大大減少了提議的計(jì)算時(shí)間。RPN 使用了一組固定大小和比例的錨框(anchors),對每一個(gè)錨框預(yù)測偏移量和目標(biāo)存在的概率。
(2)共享卷積特征:
與其前任 Fast R-CNN 不同,Faster R-CNN 的 RPN 和最終的目標(biāo)檢測都共享相同的卷積特征。這意味著圖像只需要進(jìn)行一次前向傳播,從而大大提高了計(jì)算效率。
(3)ROI Pooling:
一旦得到了區(qū)域提議,Faster R-CNN 使用?ROI (Region of Interest) Pooling 技術(shù)來從每個(gè)提議中提取固定大小的特征。這確保無論提議的大小如何,都可以輸入到一個(gè)固定大小的全連接網(wǎng)絡(luò)中進(jìn)行分類和邊界框回歸。
(4)雙任務(wù)損失:
RPN 被訓(xùn)練為一個(gè)雙任務(wù)問題:分類(目標(biāo) vs. 非目標(biāo))和邊界框回歸。這種雙任務(wù)損失結(jié)構(gòu)確保了 RPN 在生成提議時(shí)既考慮了準(zhǔn)確性也考慮了定位。
總之,Faster R-CNN 通過引入?yún)^(qū)域提議網(wǎng)絡(luò)和共享卷積特征,大大提高了目標(biāo)檢測的速度和精度,為后續(xù)的研究和應(yīng)用打下了堅(jiān)實(shí)的基礎(chǔ)。
三、數(shù)據(jù)源
來源于公共數(shù)據(jù),文件設(shè)置如下:
大概的任務(wù)就是:用一個(gè)框框標(biāo)記出MTB的位置。
四、Faster R-CNN實(shí)戰(zhàn)
直接上代碼:
import os
import random
import torch
import torchvision
from torchvision.models.detection import fasterrcnn_resnet50_fpn
from torchvision.transforms import functional as F
from PIL import Image
from torch.utils.data import DataLoader
import xml.etree.ElementTree as ET
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import matplotlib.pyplot as plt
from torchvision import transforms
import albumentations as A
from albumentations.pytorch import ToTensorV2
import numpy as np# Function to parse XML annotations
def parse_xml(xml_path):tree = ET.parse(xml_path)root = tree.getroot()boxes = []for obj in root.findall("object"):bndbox = obj.find("bndbox")xmin = int(bndbox.find("xmin").text)ymin = int(bndbox.find("ymin").text)xmax = int(bndbox.find("xmax").text)ymax = int(bndbox.find("ymax").text)# Check if the bounding box is validif xmin < xmax and ymin < ymax:boxes.append((xmin, ymin, xmax, ymax))else:print(f"Warning: Ignored invalid box in {xml_path} - ({xmin}, {ymin}, {xmax}, {ymax})")return boxes# Function to split data into training and validation sets
def split_data(image_dir, split_ratio=0.8):all_images = [f for f in os.listdir(image_dir) if f.endswith(".jpg")]random.shuffle(all_images)split_idx = int(len(all_images) * split_ratio)train_images = all_images[:split_idx]val_images = all_images[split_idx:]return train_images, val_images# Dataset class for the Tuberculosis dataset
class TuberculosisDataset(torch.utils.data.Dataset):def __init__(self, image_dir, annotation_dir, image_list, transform=None):self.image_dir = image_dirself.annotation_dir = annotation_dirself.image_list = image_listself.transform = transformdef __len__(self):return len(self.image_list)def __getitem__(self, idx):image_path = os.path.join(self.image_dir, self.image_list[idx])image = Image.open(image_path).convert("RGB")xml_path = os.path.join(self.annotation_dir, self.image_list[idx].replace(".jpg", ".xml"))boxes = parse_xml(xml_path)# Check for empty bounding boxes and return Noneif len(boxes) == 0:return Noneboxes = torch.as_tensor(boxes, dtype=torch.float32)labels = torch.ones((len(boxes),), dtype=torch.int64)iscrowd = torch.zeros((len(boxes),), dtype=torch.int64)target = {}target["boxes"] = boxestarget["labels"] = labelstarget["image_id"] = torch.tensor([idx])target["iscrowd"] = iscrowd# Apply transformationsif self.transform:image = self.transform(image)return image, target# Define the transformations using torchvision
data_transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(), # Convert PIL image to tensortorchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # Normalize the images
])# Adjusting the DataLoader collate function to handle None values
def collate_fn(batch):batch = list(filter(lambda x: x is not None, batch))return tuple(zip(*batch))# Function to get the Mask R-CNN model
def get_model(num_classes):model = fasterrcnn_resnet50_fpn(pretrained=True)in_features = model.roi_heads.box_predictor.cls_score.in_featuresmodel.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)return model# Function to save the model
def save_model(model, path="mmaskrcnn_mtb.pth", save_full_model=False):if save_full_model:torch.save(model, path)else:torch.save(model.state_dict(), path)print(f"Model saved to {path}")# Function to compute Intersection over Union
def compute_iou(boxA, boxB):xA = max(boxA[0], boxB[0])yA = max(boxA[1], boxB[1])xB = min(boxA[2], boxB[2])yB = min(boxA[3], boxB[3])interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)iou = interArea / float(boxAArea + boxBArea - interArea)return iou# Adjusting the DataLoader collate function to handle None values and entirely empty batches
def collate_fn(batch):batch = list(filter(lambda x: x is not None, batch))if len(batch) == 0:# Return placeholder batch if entirely emptyreturn [torch.zeros(1, 3, 224, 224)], [{}]return tuple(zip(*batch))#Training function with modifications for collecting IoU and loss
def train_model(model, train_loader, optimizer, device, num_epochs=10):model.train()model.to(device)loss_values = []iou_values = []for epoch in range(num_epochs):epoch_loss = 0.0total_ious = 0num_boxes = 0for images, targets in train_loader:# Skip batches with placeholder dataif len(targets) == 1 and not targets[0]:continue# Skip batches with empty targetsif any(len(target["boxes"]) == 0 for target in targets):continueimages = [image.to(device) for image in images]targets = [{k: v.to(device) for k, v in t.items()} for t in targets]loss_dict = model(images, targets)losses = sum(loss for loss in loss_dict.values())optimizer.zero_grad()losses.backward()optimizer.step()epoch_loss += losses.item()# Compute IoU for evaluationwith torch.no_grad():model.eval()predictions = model(images)for i, prediction in enumerate(predictions):pred_boxes = prediction["boxes"].cpu().numpy()true_boxes = targets[i]["boxes"].cpu().numpy()for pred_box in pred_boxes:for true_box in true_boxes:iou = compute_iou(pred_box, true_box)total_ious += iounum_boxes += 1model.train()avg_loss = epoch_loss / len(train_loader)avg_iou = total_ious / num_boxesloss_values.append(avg_loss)iou_values.append(avg_iou)print(f"Epoch {epoch+1}/{num_epochs} Loss: {avg_loss} Avg IoU: {avg_iou}")# Plotting loss and IoU valuesplt.figure(figsize=(12, 5))plt.subplot(1, 2, 1)plt.plot(loss_values, label="Training Loss")plt.title("Training Loss across Epochs")plt.xlabel("Epochs")plt.ylabel("Loss")plt.subplot(1, 2, 2)plt.plot(iou_values, label="IoU")plt.title("IoU across Epochs")plt.xlabel("Epochs")plt.ylabel("IoU")plt.show()# Save model after trainingsave_model(model)# Validation function
def validate_model(model, val_loader, device):model.eval()model.to(device)with torch.no_grad():for images, targets in val_loader:images = [image.to(device) for image in images]targets = [{k: v.to(device) for k, v in t.items()} for t in targets]model(images)# Paths to your data
image_dir = "tuberculosis-phonecamera"
annotation_dir = "tuberculosis-phonecamera"# Split data
train_images, val_images = split_data(image_dir)# Create datasets and dataloaders
train_dataset = TuberculosisDataset(image_dir, annotation_dir, train_images, transform=data_transform)
val_dataset = TuberculosisDataset(image_dir, annotation_dir, val_images, transform=data_transform)# Updated DataLoader with new collate function
train_loader = DataLoader(train_dataset, batch_size=4, shuffle=True, collate_fn=collate_fn)
val_loader = DataLoader(val_dataset, batch_size=4, shuffle=False, collate_fn=collate_fn)# Model and optimizer
model = get_model(2)
optimizer = torch.optim.SGD(model.parameters(), lr=0.005, momentum=0.9, weight_decay=0.0005)# Train and validate
train_model(model, train_loader, optimizer, device="cuda", num_epochs=100)
validate_model(model, val_loader, device="cuda")#######################################Print Metrics######################################
def calculate_metrics(predictions, ground_truths, iou_threshold=0.5):TP = 0 # True PositivesFP = 0 # False PositivesFN = 0 # False Negativestotal_iou = 0 # to calculate mean IoUfor pred, gt in zip(predictions, ground_truths):pred_boxes = pred["boxes"].cpu().numpy()gt_boxes = gt["boxes"].cpu().numpy()# Match predicted boxes to ground truth boxesfor pred_box in pred_boxes:max_iou = 0matched = Falsefor gt_box in gt_boxes:iou = compute_iou(pred_box, gt_box)if iou > max_iou:max_iou = iouif iou > iou_threshold:matched = Truetotal_iou += max_iouif matched:TP += 1else:FP += 1FN += len(gt_boxes) - TPprecision = TP / (TP + FP) if (TP + FP) != 0 else 0recall = TP / (TP + FN) if (TP + FN) != 0 else 0f1_score = (2 * precision * recall) / (precision + recall) if (precision + recall) != 0 else 0mean_iou = total_iou / (TP + FP)return precision, recall, f1_score, mean_ioudef evaluate_model(model, dataloader, device):model.eval()model.to(device)all_predictions = []all_ground_truths = []with torch.no_grad():for images, targets in dataloader:images = [image.to(device) for image in images]predictions = model(images)all_predictions.extend(predictions)all_ground_truths.extend(targets)precision, recall, f1_score, mean_iou = calculate_metrics(all_predictions, all_ground_truths)return precision, recall, f1_score, mean_ioutrain_precision, train_recall, train_f1, train_iou = evaluate_model(model, train_loader, "cuda")
val_precision, val_recall, val_f1, val_iou = evaluate_model(model, val_loader, "cuda")print("Training Set Metrics:")
print(f"Precision: {train_precision:.4f}, Recall: {train_recall:.4f}, F1 Score: {train_f1:.4f}, Mean IoU: {train_iou:.4f}")print("\nValidation Set Metrics:")
print(f"Precision: {val_precision:.4f}, Recall: {val_recall:.4f}, F1 Score: {val_f1:.4f}, Mean IoU: {val_iou:.4f}")#sheet
header = "| Metric | Training Set | Validation Set |"
divider = "+----------+--------------+----------------+"train_metrics = f"| Precision | {train_precision:.4f} | {val_precision:.4f} |"
recall_metrics = f"| Recall | {train_recall:.4f} | {val_recall:.4f} |"
f1_metrics = f"| F1 Score | {train_f1:.4f} | {val_f1:.4f} |"
iou_metrics = f"| Mean IoU | {train_iou:.4f} | {val_iou:.4f} |"print(header)
print(divider)
print(train_metrics)
print(recall_metrics)
print(f1_metrics)
print(iou_metrics)
print(divider)#######################################Train Set######################################
import numpy as np
import matplotlib.pyplot as pltdef plot_predictions_on_image(model, dataset, device, title):# Select a random image from the datasetidx = np.random.randint(50, len(dataset))image, target = dataset[idx]img_tensor = image.clone().detach().to(device).unsqueeze(0)# Use the model to make predictionsmodel.eval()with torch.no_grad():prediction = model(img_tensor)# Inverse normalization for visualizationinv_normalize = transforms.Normalize(mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],std=[1/0.229, 1/0.224, 1/0.225])image = inv_normalize(image)image = torch.clamp(image, 0, 1)image = F.to_pil_image(image)# Plot the image with ground truth boxesplt.figure(figsize=(10, 6))plt.title(title + " with Ground Truth Boxes")plt.imshow(image)ax = plt.gca()# Draw the ground truth boxes in bluefor box in target["boxes"]:rect = plt.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1],fill=False, color='blue', linewidth=2)ax.add_patch(rect)plt.show()# Plot the image with predicted boxesplt.figure(figsize=(10, 6))plt.title(title + " with Predicted Boxes")plt.imshow(image)ax = plt.gca()# Draw the predicted boxes in redfor box in prediction[0]["boxes"].cpu():rect = plt.Rectangle((box[0], box[1]), box[2]-box[0], box[3]-box[1],fill=False, color='red', linewidth=2)ax.add_patch(rect)plt.show()# Call the function for a random image from the train dataset
plot_predictions_on_image(model, train_dataset, "cuda", "Selected from Training Set")#######################################Val Set####################################### Call the function for a random image from the validation dataset
plot_predictions_on_image(model, val_dataset, "cuda", "Selected from Validation Set")
不解讀了,給出GPT的咒語參考:
咒語:我有一批數(shù)據(jù),存在“tuberculosis-phonecamera”文件夾中,包括兩部分:
一部分是MTB的痰涂片抗酸染色圖片,為jpg格式,命名為“tuberculosis-phone-0001.jpg”、“tuberculosis-phone-0002.jpg”等;
一部分是MTB的痰涂片抗酸染色圖片對應(yīng)的注釋文件,主要內(nèi)容是標(biāo)注MTB的痰涂片抗酸染色圖片中MTB的具體位置,是若干個(gè)紅色框,為XML格式,命名為“tuberculosis-phone-0001.xml”、“tuberculosis-phone-0002.xml”等,我上傳一個(gè)xml文件給你做例子;
我需要基于上面的數(shù)據(jù),使用pytorch建立一個(gè)Mask R-CNN目標(biāo)識別模型,去識別MTB的痰涂片抗酸染色圖片中的MTB,并使用紅色框標(biāo)注出來。數(shù)據(jù)需要隨機(jī)分為訓(xùn)練集(80%)和驗(yàn)證集(20%)。
看看結(jié)果:
(1)loss曲線圖:
(2)性能指標(biāo):
(3)訓(xùn)練的圖片測試結(jié)果:
(4)驗(yàn)證集的圖片測試結(jié)果:
五、寫在后面
直接使用預(yù)訓(xùn)練模型,而且模型并沒有調(diào)參。但是訓(xùn)練集的準(zhǔn)確率還是挺高的,驗(yàn)證集就差點(diǎn)意思了。需要更高的性能,還得認(rèn)真研究如何調(diào)參。