博客專欄

EEPW首頁 > 博客 > Unet網(wǎng)絡(luò)實現(xiàn)葉子病蟲害圖像分割

Unet網(wǎng)絡(luò)實現(xiàn)葉子病蟲害圖像分割

發(fā)布人:AI科技大本營 時間:2021-08-19 來源:工程師 發(fā)布文章

引言

智能化農(nóng)業(yè)作為人工智能應(yīng)用的重要領(lǐng)域,對較高的圖像處理能力要求較高,其中圖像分割作為圖像處理方法在其中起著重要作用。圖像分割是圖像分析的關(guān)鍵步驟, 在復(fù)雜的自然背景下進(jìn)行圖像分割, 難度較大。

在傳統(tǒng)的病蟲害圖像分割算法中應(yīng)用最多的是基于統(tǒng)計模式識別、K-均值聚類、模糊C-均值聚類、Otsu、levelset、EM等算法。Gui等人提出了一種基于復(fù)雜背景的彩色葉片圖像的大豆葉病檢測系統(tǒng),該系統(tǒng)根據(jù)K均值算法和結(jié)合經(jīng)驗閾值,基于顯著性映射從大豆葉片病害圖像中分割出顯著區(qū)域.Kaur等人提出了一種基于K均值聚類算法的葡萄病害葉片圖像分割方法.Chaudhary等人提出了一種基于圖像處理技術(shù)的植物葉片病斑分割算法,比較了CIELAB、HSI和YCbCr顏色空間在病害檢測過程中的效果.Mohammad等人比較了閾值法、分水嶺法、邊緣檢測法、模糊C-均值聚類法和K-均值聚類法在植物病害檢測中的應(yīng)用,指出它們適合于任務(wù)重疊聚類。

而Unet網(wǎng)絡(luò)作為圖像分割的經(jīng)典深度學(xué)習(xí)算法,在植物葉片病蟲害區(qū)域分割中也起著重要作用。故本項目通過使用python語言搭建Unet圖像分割技術(shù)實現(xiàn)對植物病蟲害區(qū)域的分割。其簡單訓(xùn)練幾輪后的模型效果如下圖可見:

1.png

1.基本介紹

1.1 環(huán)境要求

本次環(huán)境使用的是python3.6.5+windows平臺。主要用的庫有:

opencv模塊。在計算機(jī)視覺項目的開發(fā)中,opencv作為較大眾的開源庫,擁有了豐富的常用圖像處理函數(shù)庫,采用C/C++語言編寫,可以運行在Linux/Windows/Mac等操作系統(tǒng)上,能夠快速的實現(xiàn)一些圖像處理和識別的任務(wù)。

numpy模塊。numpy系統(tǒng)是Python的一種開源的數(shù)值計算擴(kuò)展。這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表結(jié)構(gòu)(nested list structure)要高效得多(該結(jié)構(gòu)也可以用來表示矩陣(matrix))。

pytorch模塊。pytorch是一個基于Torch的Python開源機(jī)器學(xué)習(xí)庫,用于自然語言處理等應(yīng)用程序。它主要由Facebookd的人工智能小組開發(fā),不僅能夠 實現(xiàn)強(qiáng)大的GPU加速,同時還支持動態(tài)神經(jīng)網(wǎng)絡(luò),這一點是現(xiàn)在很多主流框架如TensorFlow都不支持的。PyTorch提供了兩個高級功能:1.具有強(qiáng)大的GPU加速的張量計算(如Numpy) 2.包含自動求導(dǎo)系統(tǒng)的深度神經(jīng)網(wǎng)絡(luò) 除了Facebook之外,Twitter、GMU和Salesforce等機(jī)構(gòu)都采用了pytorch。

visdom模塊。visdom一個靈活的可視化工具,可用來對于 實時,富數(shù)據(jù)的 創(chuàng)建,組織和共享。支持Torch和numpy還有pytorch。visdom 可以實現(xiàn)遠(yuǎn)程數(shù)據(jù)的可視化,對科學(xué)實驗有很大幫助。我們可以遠(yuǎn)程的發(fā)送圖片和數(shù)據(jù),并進(jìn)行在ui界面顯示出來,檢查實驗結(jié)果,或者debug。

1.2 Unet模型介紹

U-Net 網(wǎng)絡(luò)模型是在 2015 年由 Ronneberger 等人提出的。U-Net 基于全卷積網(wǎng)絡(luò) FCN,其網(wǎng)絡(luò)結(jié)構(gòu)與 FCN 相似,都采用了編碼器和****,以及跳躍連接的拓?fù)浣Y(jié)構(gòu),能夠?qū)崿F(xiàn)在少量訓(xùn)練圖像上進(jìn)行更加精準(zhǔn)的分割。但是 U-Net 與 FCN 不同之處在于 U-Net 網(wǎng)絡(luò)是左右對稱的。其左側(cè)是用于捕獲上下文信息的收縮路徑,網(wǎng)絡(luò)右側(cè)是用于精確定位的擴(kuò)張路徑,與收縮路徑對稱,以恢復(fù)圖像大小。編碼器對應(yīng)層的輸出特征圖經(jīng)復(fù)制、裁減后與反卷積后的特征圖通過跳躍連接進(jìn)行特征融合,然后作為下一層的輸入,繼續(xù)上采樣。U-Net 網(wǎng)絡(luò)在上采樣過程中有大量的特征通道,這使得網(wǎng)絡(luò)能夠?qū)⑸舷挛男畔鞯礁叻直媛实膶印?/p>

2.png

2.模型搭建

2.1數(shù)據(jù)集準(zhǔn)備

首先我們使用labelme工具對需要準(zhǔn)備好的數(shù)據(jù)集進(jìn)行處理標(biāo)注。生成對應(yīng)的json文件放置同一目錄即可。其中l(wèi)abelme可以實現(xiàn)對圖像進(jìn)行多邊形,矩形,圓形,多段線,線段,點形式的標(biāo)注(可用于目標(biāo)檢測,圖像分割,等任務(wù))。處理格式如下:

3.png

2.2模型創(chuàng)建

U-Net 網(wǎng)絡(luò)模型結(jié)構(gòu)主要包括編碼器、****和跳躍連接部分。編碼器用于抽象特征、提取信息,****部分使得圖像逐步恢復(fù)原始尺寸,而跳躍連接則將不同層次的特征進(jìn)行了融合。在這里我們使用segmentation_models_pytorch庫實現(xiàn)對unet的直接調(diào)用

其中UNet編****初始化代碼如下:

def __init__(
        self,
        encoder_name: str = "resnet34",
        encoder_depth: int = 5,
        encoder_weights: Optional[str] = "imagenet",
        decoder_use_batchnorm: bool = True,
        decoder_channels: List[int] = (256, 128, 64, 32, 16),
        decoder_attention_type: Optional[str] = None,
        in_channels: int = 3,
        classes: int = 1,
        activation: Optional[Union[str, callable]] = None,
        aux_params: Optional[dict] = None,
    ):
        super().__init__()
        self.encoder = get_encoder(
            encoder_name,
            in_channels=in_channels,
            depth=encoder_depth,
            weights=encoder_weights,
        )
        self.decoder = UnetDecoder(
            encoder_channels=self.encoder.out_channels,
            decoder_channels=decoder_channels,
            n_blocks=encoder_depth,
            use_batchnorm=decoder_use_batchnorm,
            center=True if encoder_name.startswith("vgg") else False,
            attention_type=decoder_attention_type,
        )
        self.segmentation_head = SegmentationHead(
            in_channels=decoder_channels[-1],
            out_channels=classes,
            activation=activation,
            kernel_size=3,
        )

2.3 模型訓(xùn)練

設(shè)置模型基本參數(shù),其中包括學(xué)習(xí)率,batchsize,迭代次數(shù),損失值等初始化。UNet 網(wǎng)絡(luò)及大部分使用 Relu 函數(shù)進(jìn)行激活,能夠有效避免和糾正梯度消失問題。

def __init__(self, model):
    self.num_workers = 0
    self.batch_size = {"train": 8, "val":1}
    self.accumulation_steps = 32 // self.batch_size['train']
    self.lr = 1e-3
    self.num_epochs = 100
    self.best_loss = float("inf")
    self.best_dice = float(0)
    self.phases = ["train", "val"]
    self.device = torch.device("cuda:0")
    torch.set_default_tensor_type("torch.cuda.FloatTensor")
    self.net = model
    self.criterion = nn.BCEWithLogitsLoss()
    self.optimizer = optim.Adam(self.net.parameters(), lr=self.lr)
    self.scheduler = ReduceLROnPlateau(self.optimizer, mode="min", patience=4, verbose=True)
    self.net = self.net.to(self.device)
    cudnn.benchmark = True
    self.dataloaders = {
        phase: provider(
            image_path=image_path,
            phase=phase,
            mean=(0.485, 0.456, 0.406),
            std=(0.229, 0.224, 0.225),
            batch_size=self.batch_size[phase],
            num_workers=self.num_workers,
        )
        for phase in self.phases
    }
    self.losses = {phase: [] for phase in self.phases}
    self.iou_scores = {phase: [] for phase in self.phases}
    self.dice_scores = {phase: [] for phase in self.phases}

4.png

2.4模型評估

損失函數(shù)是神經(jīng)網(wǎng)絡(luò)尋找最優(yōu)權(quán)重參數(shù)的指標(biāo)。常用的損失函數(shù)有均方誤差、交叉熵?fù)p失函數(shù)等。U-Net 網(wǎng)絡(luò)中使用了交叉熵?fù)p失函數(shù)在最后的特征圖上通過像素級的 soft-max進(jìn)行計算。Loss可以通過標(biāo)準(zhǔn)二值交叉熵(binary cross-entropy)和 Dice 損失計算,這是評估圖像分割成功與否的常用性能標(biāo)準(zhǔn)。交并比(IoU) 是基于像素的評價標(biāo)準(zhǔn),通常用于評估分割性能。這里考慮了目標(biāo)矩陣與結(jié)果矩陣之間的不同像素比。這個度量與Dice計算也有關(guān)。

5.png

def __init__(self, phase, epoch):
    self.base_threshold = 0.5 # <<<<<<<<<<< here's the threshold
    self.base_dice_scores = []
    self.dice_neg_scores = []
    self.dice_pos_scores = []
    self.iou_scores = []
def update(self, targets, outputs):
    probs = torch.sigmoid(outputs)
    dice, dice_neg, dice_pos, _, _ = metric(probs, targets, self.base_threshold)
    self.base_dice_scores.append(dice)
    self.dice_pos_scores.append(dice_pos)
    self.dice_neg_scores.append(dice_neg)
    preds = predict(probs, self.base_threshold)
    iou = compute_iou_batch(preds, targets, classes=[1])
    self.iou_scores.append(iou)
def get_metrics(self):
    dice = np.mean(self.base_dice_scores)
    dice_neg = np.mean(self.dice_neg_scores)
    dice_pos = np.mean(self.dice_pos_scores)
    dices = [dice, dice_neg, dice_pos]
    iou = np.nanmean(self.iou_scores)
    return dices, iou

2.5可視化

通過設(shè)置visdom模塊中的provider建立訓(xùn)練過程中的可視化,然后使用命令“python -m visdom.server”實現(xiàn)瀏覽器訪問訓(xùn)練過程。

def provider(image_path, phase, mean=None, std=None, batch_size=4, num_workers=0,
):
    image_list = glob(os.path.join(image_path, "*"))
    train_idx, val_idx = train_test_split(range(len(image_list)), random_state=4396, test_size=0.1)
    index = train_idx if phase == "train" else val_idx
    dataset = CatDataset(index, image_list, phase=phase)
    dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=True,)
    return dataloader

6.png

完整代碼:

鏈接:https://pan.baidu.com/s/11quQOLw7uIP-JJ8LPBIIuQ

提取碼:dyrt

作者簡介:

李秋鍵,CSDN博客專家,CSDN達(dá)人課作者。碩士在讀于中國礦業(yè)大學(xué),開發(fā)有taptap競賽獲獎等。

*博客內(nèi)容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點,如有侵權(quán)請聯(lián)系工作人員刪除。

汽車防盜機(jī)相關(guān)文章:汽車防盜機(jī)原理


關(guān)鍵詞: AI

相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉