主頁 >  其他 > 飛槳AI進階實戰:工業表計讀數(記錄)

飛槳AI進階實戰:工業表計讀數(記錄)

2021-12-16 09:54:43 其他

1、專案說明

在該專案中,主要向大家介紹如何使用目標檢測和語意分割來實作對指標型表計讀數,

在電力能源廠區需要定期監測表計讀數,以保證設備正常運行及廠區安全,但廠區分布分散,人工巡檢耗時長,無法實時監測表計,且部分作業環境危險導致人工巡檢無法觸達,針對上述問題,希望通過攝像頭拍照->智能讀數的方式高效地完成此任務,
在這里插入圖片描述

為實作智能讀數,我們采取目標檢測->語意分割->讀數后處理的方案:

第一步,使用目標檢測模型定位出影像中的表計;
第二步,使用語意分割模型將各表計的指標和刻度分割出來;
第三步,根據指標的相對位置和預知的量程計算出各表計的讀數,

2、資料準備

本案例開放了表計檢測資料集、指標和刻度分割資料集、表計測驗圖片(只有圖片無真值標注),使用這些圖片可以完成目標檢測模型、語意分割模型的訓練、模型預測,點擊下表中的鏈接可下載資料集,提前下載資料集不是必須的,因為在接下來的模型訓練部分中提供的訓練腳本會自動下載資料集,

表計測驗圖片 表計檢測資料集 指標和刻度分割資料集
meter_test meter_det meter_seg
解壓后的表計檢測資料集的檔案夾內容如下:
訓練集有725張圖片,測驗集有58張圖片,

meter_det/
|-- annotations/ # 標注檔案所在檔案夾
| |-- instance_train.json # 訓練集標注檔案
| |-- instance_test.json # 測驗集標注檔案
|-- test/ # 測驗圖片所在檔案夾
| |-- 20190822_105.jpg # 測驗集圖片
| |-- … …
|-- train/ # 訓練圖片所在檔案夾
| |-- 20190822_101.jpg # 訓練集圖片
| |-- … …
解壓后的指標和刻度分割資料集的檔案夾內容如下:
訓練集有374張圖片,測驗集有40張圖片,

meter_seg/
|-- annotations/ # 標注檔案所在檔案夾
| |-- train # 訓練集標注圖片所在檔案夾
| | |-- 105.png
| | |-- … …
| |-- val # 驗證集合標注圖片所在檔案夾
| | |-- 110.png
| | |-- … …
|-- images/ # 圖片所在檔案夾
| |-- train # 訓練集圖片
| | |-- 105.jpg
| | |-- … …
| |-- val # 驗證集圖片
| | |-- 110.jpg
| | |-- … …
|-- labels.txt # 類別名串列
|-- train.txt # 訓練集圖片串列
|-- val.txt # 驗證集圖片串列
解壓后的表計測驗圖片的檔案夾內容如下:
一共有58張測驗圖片,

meter_test/
|-- 20190822_105.jpg
|-- 20190822_142.jpg
|-- … …

3、模型選擇

PaddleX提供了豐富的視覺模型,在目標檢測中提供了RCNN和YOLO系列模型,在語意分割中提供了DeepLabV3P和BiSeNetV2等模型,

因最終部署場景是本地化的服務器GPU端,算力相對充足,因此在本專案中采用精度和預測性能皆優的PPYOLOV2進行表計檢測,

考慮到指標和刻度均為細小區域,我們采用精度更優的DeepLabV3P進行指標和刻度的分割,

4、表計檢測模型訓練

本專案中采用精度和預測性能的PPYOLOV2進行表計檢測,

訓練結束后,最優模型精度bbox_mmap達到100%,

5、 指標和刻度分割模型訓練

本專案中采用精度更優的DeepLabV3P進行指標和刻度的分割,

訓練結束后,最優模型精度miou達84.09,

準備階段

第一步:創建Notebook模型任務

step1:進入BML主頁,點擊立即使用

🔗:https://ai.baidu.com/bml/

圖片

step2:點擊Notebook,創建“通用任務”

圖片

step3:填寫任務資訊

圖片


第二步:下載任務操作模板

下載鏈接:https://aistudio.baidu.com/aistudio/datasetdetail/120387

圖片

目標檢測模型訓練

第一步:配置Notebook

1.找到昨天創建的Notebook任務,點擊配置

圖片

2.配置選擇

  • 開發語言:Python3.7
  • AI框架:PaddlePaddle2.0.0
  • 資源規格:GPU V100

圖片

3.打開Notebook

圖片

4.上傳本次Notebook操作模型

若沒來得及下載,請點擊鏈接下載:https://aistudio.baidu.com/aistudio/datasetdetail/120387

圖片

圖片

第二步:環境準備

1.安裝filelock

!pip install filelock

圖片

圖片

2.安裝PaddleX

!pip install paddlex==2.0.0

注意:安裝paddlex的時候需要制定版本,

圖片

圖片

3.升級paddlepaddle-gpu為2.1.3版本

!pip install paddlepaddle-gpu==2.1.3.post101 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html

圖片

圖片

第三步:目標檢測模型訓練

訓練程序說明:

定義資料預處理 -> 定義資料集路徑 -> 初始化模型 -> 模型訓練

圖片

1.呼叫PaddleX

import paddlex as pdxfrom paddlex import transforms as T

圖片

2.定義訓練和驗證時的transforms

API詳細說明:https://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/transforms/operators.py

train_transforms = T.Compose([    T.MixupImage(mixup_epoch=250), T.RandomDistort(),    T.RandomExpand(im_padding_value=[123.675, 116.28, 103.53]), T.RandomCrop(),    T.RandomHorizontalFlip(), T.BatchRandomResize(        target_sizes=[320, 352, 384, 416, 448, 480, 512, 544, 576, 608],        interp='RANDOM'), T.Normalize(            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
eval_transforms = T.Compose([    T.Resize(        608, interp='CUBIC'), T.Normalize(            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])

圖片

3.下載用于目標檢測訓練的表計讀數資料集

meter_det_dataset = 'https://bj.bcebos.com/paddlex/examples/meter_reader/datasets/meter_det.tar.gz'pdx.utils.download_and_decompress(meter_det_dataset, path='./')

圖片

可在左側檔案夾區域查看資料集

圖片

4.設定訓練引數

詳細API說明:https://github.com/PaddlePaddle/PaddleX/blob/develop/paddlex/cv/datasets/coco.py#L26

train_dataset = pdx.datasets.CocoDetection(    data_dir='meter_det/train/',    ann_file='meter_det/annotations/instance_train.json',    transforms=train_transforms,    shuffle=True)eval_dataset = pdx.datasets.CocoDetection(    data_dir='meter_det/test/',    ann_file='meter_det/annotations/instance_test.json',    transforms=eval_transforms)

圖片

圖片

圖片

5.訓練結束后查看bestmodel

圖片

圖片

第四步:保存Notebook并關閉、停止運行

圖片

圖片

語意分割模型訓練

第一步:重新安裝環境

1.啟動Notebook并打開

圖片

2.重新執行安裝的三條命令

圖片

圖片

圖片

第二步:指標和刻度分割模型訓練

1.呼叫paddlex

import paddlex as pdxfrom paddlex import transforms as T

圖片

2.定義訓練和驗證時的transforms

詳細API說明參考:https://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/transforms/operators.py

train_transforms = T.Compose([    T.Resize(target_size=512),    T.RandomHorizontalFlip(),    T.Normalize(        mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),])
eval_transforms = T.Compose([    T.Resize(target_size=512),    T.Normalize(        mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),])

圖片

3.下載和解壓指標刻度分割資料集

meter_seg_dataset = 'https://bj.bcebos.com/paddlex/examples/meter_reader/datasets/meter_seg.tar.gz'pdx.utils.download_and_decompress(meter_seg_dataset, path='./')

圖片

4.定義訓練和驗證所用的資料集,配置相應路徑

詳細API說明參考:https://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/datasets/seg_dataset.py#L22

train_dataset = pdx.datasets.SegDataset(    data_dir='meter_seg',    file_list='meter_seg/train.txt',    label_list='meter_seg/labels.txt',    transforms=train_transforms,    shuffle=True)
eval_dataset = pdx.datasets.SegDataset(    data_dir='meter_seg',    file_list='meter_seg/val.txt',    label_list='meter_seg/labels.txt',    transforms=eval_transforms,    shuffle=False)

圖片

5.選擇PaddleX內置的DeepLabV3P模型進行訓練

API說明:https://github.com/PaddlePaddle/PaddleX/blob/release/2.0-rc/paddlex/cv/models/segmenter.py#L150

num_classes = len(train_dataset.labels)model = pdx.seg.DeepLabV3P(    num_classes=num_classes, backbone='ResNet50_vd', use_mixed_loss=True)

圖片

6.設定訓練時的引數

各引數介紹與調整說明:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html

model.train(    num_epochs=2,    train_dataset=train_dataset,    train_batch_size=4,    eval_dataset=eval_dataset,    pretrain_weights='IMAGENET',    learning_rate=0.1,    save_dir='output/deeplabv3p_r50vd')

圖片

圖片

圖片

7.訓練結束后查看bestmodel

圖片

圖片

第三步:保存Notebook并關閉、停止運行

圖片

圖片

提示:Notebook一旦運行即會開始計費,如果不用請及時停止!以免浪費免費額度

模型預測

第一步:重新安裝環境

1.啟動Notebook并打開

圖片

2.重新執行安裝的三條命令

圖片

圖片

圖片

第二步:上傳預測的py檔案

1.點擊下方鏈接將py檔案下載至本地

https://aistudio.baidu.com/aistudio/datasetdetail/120795

圖片

2.上傳至Notebook中

圖片

第三步:模型預測

圖片

1.上傳reader_infer.py檔案后,執行一下命令進行模型預測

!python work/meter_reader/reader_infer.py --det_model_dir output/ppyolov2_r50vd_dcn/best_model --seg_model_dir output/deeplabv3p_r50vd/best_model/ --image meter_det/test/20190822_105.jpg

圖片

圖片

2.打開output/result查看預測結果

圖片

第四步:保存Notebook并關閉、停止運行

圖片

圖片

推理代碼:

# coding: utf8
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import os.path as osp
import numpy as np
import math
import cv2
import argparse

from paddlex import transforms as T
import paddlex as pdx

# 讀數后處理中有把圓形表盤轉成矩形的操作,矩形的寬即為圓形的外周長
# 因此要求表盤影像大小為固定大小,這里設定為[512, 512]
METER_SHAPE = [512, 512]  # 高x寬
# 圓形表盤的中心點
CIRCLE_CENTER = [256, 256]  # 高x寬
# 圓形表盤的半徑
CIRCLE_RADIUS = 250
# 圓周率
PI = 3.1415926536
# 在把圓形表盤轉成矩形后矩形的高
# 當前設定值約為半徑的一半,原因是:圓形表盤的中心區域除了指標根部就是背景了
# 我們只需要把外圍的刻度、指標的尖部保存下來就可以定位出指標指向的刻度
RECTANGLE_HEIGHT = 120
# 矩形表盤的寬,即圓形表盤的外周長
RECTANGLE_WIDTH = 1570
# 當前案例中只使用了兩種型別的表盤,第一種表盤的刻度根數為50
# 第二種表盤的刻度根數為32,因此,我們通過預測的刻度根數來判斷表盤型別
# 刻度根數超過閾值的即為第一種,否則是第二種
TYPE_THRESHOLD = 40
# 兩種表盤的配置資訊,包含每根刻度的值,量程,單位
METER_CONFIG = [{
    'scale_interval_value': 25.0 / 50.0,
    'range': 25.0,
    'unit': "(MPa)"
}, {
    'scale_interval_value': 1.6 / 32.0,
    'range': 1.6,
    'unit': "(MPa)"
}]
# 分割模型預測類別id與類別名的對應關系
SEG_CNAME2CLSID = {'background': 0, 'pointer': 1, 'scale': 2}


def parse_args():
    parser = argparse.ArgumentParser(description='Meter Reader Infering')
    parser.add_argument(
        '--det_model_dir',
        dest='det_model_dir',
        help='The directory of the detection model',
        type=str)
    parser.add_argument(
        '--seg_model_dir',
        dest='seg_model_dir',
        help='The directory of the segmentation model',
        type=str)
    parser.add_argument(
        '--image_dir',
        dest='image_dir',
        help='The directory of images to be inferred',
        type=str,
        default=None)
    parser.add_argument(
        '--image',
        dest='image',
        help='The image to be inferred',
        type=str,
        default=None)
    parser.add_argument(
        '--use_erode',
        dest='use_erode',
        help='Whether erode the lable map predicted from a segmentation model',
        action='store_true')
    parser.add_argument(
        '--erode_kernel',
        dest='erode_kernel',
        help='Erode kernel size',
        type=int,
        default=4)
    parser.add_argument(
        '--save_dir',
        dest='save_dir',
        help='The directory for saving the predicted results',
        type=str,
        default='./output/result')
    parser.add_argument(
        '--score_threshold',
        dest='score_threshold',
        help="Predicted bounding boxes whose scores are lower than this threshlod are filtered",
        type=float,
        default=0.5)
    parser.add_argument(
        '--seg_batch_size',
        dest='seg_batch_size',
        help="The number of images fed into the segmentation model during one forward propagation",
        type=int,
        default=2)

    return parser.parse_args()


def is_pic(img_name):
    """判斷是否是圖片

    引數:
        img_name (str): 圖片路徑

    回傳:
        flag (bool): 判斷值,
    """
    valid_suffix = ['JPEG', 'jpeg', 'JPG', 'jpg', 'BMP', 'bmp', 'PNG', 'png']
    suffix = img_name.split('.')[-1]
    flag = True
    if suffix not in valid_suffix:
        flag = False
    return flag


class MeterReader:
    """檢測表盤的位置,分割各表盤內刻度和指標的位置,并根據分割結果計算出各表盤的讀數

    引數:
        det_model_dir (str): 用于定位表盤的檢測模型所在路徑,
        seg_model_dir (str): 用于分割刻度和指標的分割模型所在路徑,

    """

    def __init__(self, det_model_dir, seg_model_dir):
        if not osp.exists(det_model_dir):
            raise Exception("Model path {} does not exist".format(
                det_model_dir))
        if not osp.exists(seg_model_dir):
            raise Exception("Model path {} does not exist".format(
                seg_model_dir))
        self.detector = pdx.load_model(det_model_dir)
        self.segmenter = pdx.load_model(seg_model_dir)

    def decode(self, img_file):
        """影像解碼

        引數:
            img_file (str|np.array): 影像路徑,或者是已解碼的BGR影像陣列,

        回傳:
            img (np.array): BGR影像陣列,
        """

        if isinstance(img_file, str):
            img = cv2.imread(img_file).astype('float32')
        else:
            img = img_file.copy()
        return img

    def filter_bboxes(self, det_results, score_threshold):
        """過濾置信度低于閾值的檢測框

        引數:
            det_results (list[dict]): 檢測模型預測介面的回傳值,
            score_threshold (float):置信度閾值,

        回傳:
            filtered_results (list[dict]): 過濾后的檢測狂,

        """
        filtered_results = list()
        for res in det_results:
            if res['score'] > score_threshold:
                filtered_results.append(res)
        return filtered_results

    def roi_crop(self, img, det_results):
        """摳取影像上各檢測框的影像區域

        引數:
            img (np.array):BRG影像陣列,
            det_results (list[dict]): 檢測模型預測介面的回傳值,

        回傳:
            sub_imgs (list[np.array]): 各檢測框的影像區域,

        """
        sub_imgs = []
        for res in det_results:
            # Crop the bbox area
            xmin, ymin, w, h = res['bbox']
            xmin = max(0, int(xmin))
            ymin = max(0, int(ymin))
            xmax = min(img.shape[1], int(xmin + w - 1))
            ymax = min(img.shape[0], int(ymin + h - 1))
            sub_img = img[ymin:(ymax + 1), xmin:(xmax + 1), :]
            sub_imgs.append(sub_img)
        return sub_imgs

    def resize(self, imgs, target_size, interp=cv2.INTER_LINEAR):
        """影像縮放至固定大小

        引數:
            imgs (list[np.array]):批量BGR影像陣列,
            target_size (list|tuple):縮放后的影像大小,格式為[高, 寬],
            interp (int):影像差值方法,默認值為cv2.INTER_LINEAR,

        回傳:
            resized_imgs (list[np.array]):縮放后的批量BGR影像陣列,

        """

        resized_imgs = list()
        for img in imgs:
            img_shape = img.shape
            scale_x = float(target_size[1]) / float(img_shape[1])
            scale_y = float(target_size[0]) / float(img_shape[0])
            resize_img = cv2.resize(
                img, None, None, fx=scale_x, fy=scale_y, interpolation=interp)
            resized_imgs.append(resize_img)
        return resized_imgs

    def seg_predict(self, segmenter, imgs, batch_size):
        """分割模型完成預測

        引數:
            segmenter (pdx.seg.model):加載后的分割模型,
            imgs (list[np.array]):待預測的輸入BGR影像陣列,
            batch_size (int): 分割模型前向預測一次時輸入影像的批量大小,

        回傳:
            seg_results (list[dict]): 輸入影像的預測結果,

        """
        seg_results = list()
        num_imgs = len(imgs)
        for i in range(0, num_imgs, batch_size):
            batch = imgs[i:min(num_imgs, i + batch_size)]
            result = segmenter.predict(batch)
            seg_results.extend(result)
        return seg_results

    def erode(self, seg_results, erode_kernel):
        """對分割模型預測結果中label_map做影像腐蝕操作

        引數:
            seg_results (list[dict]):分割模型的預測結果,
            erode_kernel (int): 影像腐蝕的卷積核的大小,

        回傳:
            eroded_results (list[dict]):對label_map進行腐蝕后的分割模型預測結果,

        """
        kernel = np.ones((erode_kernel, erode_kernel), np.uint8)
        eroded_results = seg_results
        for i in range(len(seg_results)):
            test_resulte = seg_results[i]['label_map']
            # print('***********************************',type(test_resulte))
            # eroded_results[i]['label_map'] = cv2.erode(
            #     seg_results[i]['label_map'], kernel)
            eroded_results[i]['label_map'] = cv2.erode(
            test_resulte.astype('uint8'), kernel)
        return eroded_results

    def circle_to_rectangle(self, seg_results):
        """將圓形表盤的預測結果label_map轉換成矩形

        圓形到矩形的計算方法:
            因本案例中兩種表盤的刻度起始值都在左下方,故以圓形的中心點為坐標原點,
            從-y軸開始逆時針計算極坐標到x-y坐標的對應關系:
              x = r + r * cos(theta)
              y = r - r * sin(theta)
            注意:
                1. 因為是從-y軸開始逆時針計算,所以r * sin(theta)前有負號,
                2. 還是因為從-y軸開始逆時針計算,所以矩形從上往下對應圓形從外到內,
                   可以想象把圓形從-y軸切開再往左右拉平時,圓形的外圍是上面,內圍在下面,

        引數:
            seg_results (list[dict]):分割模型的預測結果,

        回傳值:
            rectangle_meters (list[np.array]):矩形表盤的預測結果label_map,

        """
        rectangle_meters = list()
        for i, seg_result in enumerate(seg_results):
            label_map = seg_result['label_map']
            # rectangle_meter的大小已經由預先設定的全域變數RECTANGLE_HEIGHT, RECTANGLE_WIDTH決定
            rectangle_meter = np.zeros(
                (RECTANGLE_HEIGHT, RECTANGLE_WIDTH), dtype=np.uint8)
            for row in range(RECTANGLE_HEIGHT):
                for col in range(RECTANGLE_WIDTH):
                    theta = PI * 2 * (col + 1) / RECTANGLE_WIDTH
                    # 矩形從上往下對應圓形從外到內
                    rho = CIRCLE_RADIUS - row - 1
                    y = int(CIRCLE_CENTER[0] + rho * math.cos(theta) + 0.5)
                    x = int(CIRCLE_CENTER[1] - rho * math.sin(theta) + 0.5)
                    rectangle_meter[row, col] = label_map[y, x]
            rectangle_meters.append(rectangle_meter)
        return rectangle_meters

    def rectangle_to_line(self, rectangle_meters):
        """從矩形表盤的預測結果中提取指標和刻度預測結果并沿高度方向壓縮成線狀格式,

        引數:
            rectangle_meters (list[np.array]):矩形表盤的預測結果label_map,

        回傳:
            line_scales (list[np.array]):刻度的線狀預測結果,
            line_pointers (list[np.array]):指標的線狀預測結果,

        """
        line_scales = list()
        line_pointers = list()

        for rectangle_meter in rectangle_meters:
            height, width = rectangle_meter.shape[0:2]
            line_scale = np.zeros((width), dtype=np.uint8)
            line_pointer = np.zeros((width), dtype=np.uint8)
            for col in range(width):
                for row in range(height):
                    if rectangle_meter[row, col] == SEG_CNAME2CLSID['pointer']:
                        line_pointer[col] += 1
                    elif rectangle_meter[row, col] == SEG_CNAME2CLSID['scale']:
                        line_scale[col] += 1
            line_scales.append(line_scale)
            line_pointers.append(line_pointer)
        return line_scales, line_pointers

    def mean_binarization(self, data_list):
        """對影像進行均值二值化操作

        引數:
            data_list (list[np.array]):待二值化的批量陣列,

        回傳:
            binaried_data_list (list[np.array]):二值化后的批量陣列,

        """
        batch_size = len(data_list)
        binaried_data_list = data_list
        for i in range(batch_size):
            mean_data = np.mean(data_list[i])
            width = data_list[i].shape[0]
            for col in range(width):
                if data_list[i][col] < mean_data:
                    binaried_data_list[i][col] = 0
                else:
                    binaried_data_list[i][col] = 1
        return binaried_data_list

    def locate_scale(self, line_scales):
        """在線狀預測結果中找到每根刻度的中心位置

        引數:
            line_scales (list[np.array]):批量的二值化后的刻度線狀預測結果,

        回傳:
            scale_locations (list[list]):各影像中每根刻度的中心位置,

        """
        batch_size = len(line_scales)
        scale_locations = list()
        for i in range(batch_size):
            line_scale = line_scales[i]
            width = line_scale.shape[0]
            find_start = False
            one_scale_start = 0
            one_scale_end = 0
            locations = list()
            for j in range(width - 1):
                if line_scale[j] > 0 and line_scale[j + 1] > 0:
                    if find_start == False:
                        one_scale_start = j
                        find_start = True
                if find_start:
                    if line_scale[j] == 0 and line_scale[j + 1] == 0:
                        one_scale_end = j - 1
                        one_scale_location = (
                            one_scale_start + one_scale_end) / 2
                        locations.append(one_scale_location)
                        one_scale_start = 0
                        one_scale_end = 0
                        find_start = False
            scale_locations.append(locations)
        return scale_locations

    def locate_pointer(self, line_pointers):
        """在線狀預測結果中找到指標的中心位置

        引數:
            line_scales (list[np.array]):批量的指標線狀預測結果,

        回傳:
            scale_locations (list[list]):各影像中指標的中心位置,

        """
        batch_size = len(line_pointers)
        pointer_locations = list()
        for i in range(batch_size):
            line_pointer = line_pointers[i]
            find_start = False
            pointer_start = 0
            pointer_end = 0
            location = 0
            width = line_pointer.shape[0]
            for j in range(width - 1):
                if line_pointer[j] > 0 and line_pointer[j + 1] > 0:
                    if find_start == False:
                        pointer_start = j
                        find_start = True
                if find_start:
                    if line_pointer[j] == 0 and line_pointer[j + 1] == 0:
                        pointer_end = j - 1
                        location = (pointer_start + pointer_end) / 2
                        find_start = False
                        break
            pointer_locations.append(location)
        return pointer_locations

    def get_relative_location(self, scale_locations, pointer_locations):
        """找到指標指向了第幾根刻度

        引數:
            scale_locations (list[list]):批量的每根刻度的中心點位置,
            pointer_locations (list[list]):批量的指標的中心點位置,

        回傳:
            pointed_scales (list[dict]):每個表的結果組成的list,每個表的結果由字典表示,
                字典有兩個關鍵詞:'num_scales'、'pointed_scale',分別表示預測的刻度根數、
                預測的指標指向了第幾根刻度,

        """

        pointed_scales = list()
        for scale_location, pointer_location in zip(scale_locations,
                                                    pointer_locations):
            num_scales = len(scale_location)
            pointed_scale = -1
            if num_scales > 0:
                for i in range(num_scales - 1):
                    if scale_location[
                            i] <= pointer_location and pointer_location < scale_location[
                                i + 1]:
                        pointed_scale = i + (
                            pointer_location - scale_location[i]
                        ) / (scale_location[i + 1] - scale_location[i] + 1e-05
                             ) + 1
            result = {'num_scales': num_scales, 'pointed_scale': pointed_scale}
            pointed_scales.append(result)
        return pointed_scales

    def calculate_reading(self, pointed_scales):
        """根據刻度的間隔值和指標指向的刻度根數計算表盤的讀數
        """
        readings = list()
        batch_size = len(pointed_scales)
        for i in range(batch_size):
            pointed_scale = pointed_scales[i]
            # 刻度根數大于閾值的為第一種表盤
            if pointed_scale['num_scales'] > TYPE_THRESHOLD:
                reading = pointed_scale['pointed_scale'] * METER_CONFIG[0][
                    'scale_interval_value']
            else:
                reading = pointed_scale['pointed_scale'] * METER_CONFIG[1][
                    'scale_interval_value']
            readings.append(reading)

        return readings

    def get_meter_reading(self, seg_results):
        """對分割結果進行讀數后處理得到各表盤的讀數

        引數:
            seg_results (list[dict]): 分割模型的預測結果,

        回傳:
            meter_readings (list[dcit]): 各表盤的讀數,

        """

        rectangle_meters = self.circle_to_rectangle(seg_results)
        line_scales, line_pointers = self.rectangle_to_line(rectangle_meters)
        binaried_scales = self.mean_binarization(line_scales)
        binaried_pointers = self.mean_binarization(line_pointers)
        scale_locations = self.locate_scale(binaried_scales)
        pointer_locations = self.locate_pointer(binaried_pointers)
        pointed_scales = self.get_relative_location(scale_locations,
                                                    pointer_locations)
        meter_readings = self.calculate_reading(pointed_scales)
        return meter_readings

    def print_meter_readings(self, meter_readings):
        """列印各表盤的讀數

        引數:
            meter_readings (list[dict]):各表盤的讀數
        """
        for i in range(len(meter_readings)):
            print("Meter {}: {}".format(i + 1, meter_readings[i]))

    def visualize(self, img, det_results, meter_readings, save_dir="./"):
        """可視化影像中各表盤的位置和讀數

        引數:
            img (str|np.array): 影像路徑,或者是已解碼的BGR影像陣列,
            det_results (dict): 檢測模型的預測結果,
            meter_readings (list): 各表盤的讀數,
            save_dir (str):可視化后的圖片保存路徑,

        """
        vis_results = list()
        for i, res in enumerate(det_results):
            # 將檢測結果中的關鍵詞`score`替換成讀數,就可以呼叫pdx.det.visualize畫圖了
            res['score'] = meter_readings[i]
            vis_results.append(res)
        # 檢測結果可視化時會濾除score低于threshold的框,這里讀數都是>=-1的,所以設定thresh=-1
        pdx.det.visualize(img, vis_results, threshold=-1, save_dir=save_dir)

    def predict(self,
                img_file,
                save_dir='./',
                use_erode=True,
                erode_kernel=4,
                score_threshold=0.5,
                seg_batch_size=2):
        """檢測影像中的表盤,而后分割出各表盤中的指標和刻度,對分割結果進行讀數后處理后得到各表盤的讀數,

        引數:
            img_file (str):待預測的圖片路徑,
            save_dir (str): 可視化結果的保存路徑,
            use_erode (bool, optional): 是否對分割預測結果做影像腐蝕,默認值:True,
            erode_kernel (int, optional): 影像腐蝕的卷積核大小,默認值: 4,
            score_threshold (float, optional): 用于濾除檢測框的置信度閾值,默認值:0.5,
            seg_batch_size (int, optional):分割模型前向推理一次時輸入表盤影像的批量大小,默認值為:2,
        """

        img = self.decode(img_file)
        det_results = self.detector.predict(img)
        filtered_results = self.filter_bboxes(det_results, score_threshold)
        sub_imgs = self.roi_crop(img, filtered_results)
        sub_imgs = self.resize(sub_imgs, METER_SHAPE)
        seg_results = self.seg_predict(self.segmenter, sub_imgs,
                                       seg_batch_size)
        seg_results = self.erode(seg_results, erode_kernel)
        meter_readings = self.get_meter_reading(seg_results)
        self.print_meter_readings(meter_readings)
        self.visualize(img, filtered_results, meter_readings, save_dir)


def infer(args):
    image_lists = list()
    if args.image is not None:
        if not osp.exists(args.image):
            raise Exception("Image {} does not exist.".format(args.image))
        if not is_pic(args.image):
            raise Exception("{} is not a picture.".format(args.image))
        image_lists.append(args.image)
    elif args.image_dir is not None:
        if not osp.exists(args.image_dir):
            raise Exception("Directory {} does not exist.".format(
                args.image_dir))
        for im_file in os.listdir(args.image_dir):
            if not is_pic(im_file):
                continue
            im_file = osp.join(args.image_dir, im_file)
            image_lists.append(im_file)

    meter_reader = MeterReader(args.det_model_dir, args.seg_model_dir)
    if len(image_lists) > 0:
        for image in image_lists:
            meter_reader.predict(image, args.save_dir, args.use_erode,
                                 args.erode_kernel, args.score_threshold,
                                 args.seg_batch_size)


if __name__ == '__main__':
    args = parse_args()
    infer(args)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/382136.html

標籤:其他

上一篇:覆寫Webview2之上的MediaElement

下一篇:NCNN驗證YOLOV4模型輸入資料歸一化系數

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more