<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【深度學(xué)習(xí)】利用OpenCV+ConvNets檢測(cè)幾何圖形

          共 2598字,需瀏覽 6分鐘

           ·

          2021-11-09 20:29


          導(dǎo)讀


          人工智能領(lǐng)域中增長(zhǎng)最快的子領(lǐng)域之一是自然語(yǔ)言處理(NLP),它處理計(jì)算機(jī)與人類(自然)語(yǔ)言之間的交互,特別是如何編程計(jì)算機(jī)以處理和理解大量自然語(yǔ)言數(shù)據(jù)。


          自然語(yǔ)言處理通常涉及語(yǔ)音識(shí)別、自然語(yǔ)言理解和自然語(yǔ)言生成等。其中,命名實(shí)體識(shí)別(NER)等信息提取問(wèn)題正迅速成為NLP的基礎(chǔ)應(yīng)用之一。在這篇文章中,我們將分享一個(gè)解決執(zhí)行NER時(shí)出現(xiàn)的最棘手問(wèn)題之一的解決方案。



          深度學(xué)習(xí)的最新發(fā)展導(dǎo)致了可用于實(shí)體提取和其他NLP相關(guān)任務(wù)的復(fù)雜技術(shù)的迅速發(fā)展。通常,企業(yè)級(jí)OCR軟件(ABBY、ADLIB等)用于將大量非結(jié)構(gòu)化和基于圖像的文檔轉(zhuǎn)換為完全可搜索的PDF和PDF/A,人們可以使用最先進(jìn)的算法(BERT、ELMo等)創(chuàng)建高度上下文化的語(yǔ)言模型來(lái)推斷提取的信息并實(shí)現(xiàn)NLP目標(biāo)。


          但實(shí)際上,并非所有文檔都僅由基于語(yǔ)言的數(shù)據(jù)組成。文檔可以具有許多其他非語(yǔ)言元素,例如單選按鈕、簽名塊或某些其他幾何形狀,這些元素可能包含有用的信息,但無(wú)法通過(guò)OCR或上述任何算法輕松處理。因此,需要設(shè)計(jì)一個(gè)專門的解決方案來(lái)識(shí)別和處理這些元素。


          操作步驟

          步驟1:將文檔(PDF等)轉(zhuǎn)換為圖像文件。編寫一個(gè)基于OpenCV API的啟發(fā)式代碼來(lái)提取所有可能的圖像片段,此代碼應(yīng)針對(duì)覆蓋率而不是準(zhǔn)確性進(jìn)行優(yōu)化。


          步驟2:相應(yīng)地標(biāo)記步驟1中提取的圖像。創(chuàng)建一個(gè)基于CNN的深度學(xué)習(xí)網(wǎng)絡(luò),并根據(jù)標(biāo)記的圖像對(duì)其進(jìn)行培訓(xùn),這一步將保證準(zhǔn)確性。


          步驟3:創(chuàng)建一個(gè)Sklearn pipeline,集成上述兩個(gè)步驟,以便在接收文檔時(shí),提取所有潛在圖像,然后使用經(jīng)過(guò)訓(xùn)練的CNN模型預(yù)測(cè)所需形狀的圖像。



          設(shè)計(jì)細(xì)節(jié)


          需要注意的是,OpenCV代碼盡可能多的識(shí)別所需形狀的圖像段。本質(zhì)上,我們需要有一個(gè)寬的檢測(cè)范圍,不必?fù)?dān)心誤報(bào),它們將由后續(xù)的ConvNet模型處理。之所以選擇CNN進(jìn)行圖像分類,是因?yàn)樗子诮:涂焖俳?,但只要性能和精度在可接受的范圍?nèi),就可以使用任何其他選擇的算法。Pipelining?在構(gòu)造ML代碼中起著關(guān)鍵作用,它有助于簡(jiǎn)化工作流程和強(qiáng)制執(zhí)行步驟的順序。


          實(shí)踐操作


          第1步:OpenCV


          此代碼具有雙重用途:

          1)創(chuàng)建訓(xùn)練/測(cè)試數(shù)據(jù)

          2)在集成到管道中時(shí)提取圖像段


          提取代碼目前可以檢測(cè)2種類型(單選按鈕和復(fù)選框),但通過(guò)在ShapeFinder類下添加新方法,可以輕松支持其他對(duì)象,下面是用于識(shí)別正方形/矩形(也稱為復(fù)選框)的代碼片段。

           #detect checkbox/squaredef extract_quads(self,image_arr,name_arr):
          if len(image_arr) > 0:
          for index,original_image in enumerate(image_arr):
          #to store extracted images extracted_quad = [] image = original_image.copy()
          #grayscale only if its not already if len(image.shape) > 2: gray = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY) else: gray = image.copy()
          #image preprocessing for quadrilaterals img_dilate = self.do_quad_imageprocessing(gray,self.blocksize,self.thresh_const,self.kernelsize)
          if len(img_dilate) > 0:
          try: #detect contours cnts = cv2.findContours(img_dilate.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts)
          #loop through detected contours for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, (self.epsilon)* peri, True)
          #bounding rec cordinates (x, y, w, h) = cv2.boundingRect(approx)
          #get the aspect ratio aspectratio = float(w/h) area = cv2.contourArea(c) if area < self.rec_max_area and area > self.rec_min_area and (aspectratio >= self.aspect_ratio[0] and aspectratio <= self.aspect_ratio[1]):
          #check if there are 4 corners in the polygon if len(approx) == 4: cv2.drawContours(original_image,[c], 0, (0,255,0), 2) roi = original_image[y:y+h, x:x+w] extracted_quad.append(roi)
          except Exception as e: print('The following exception occured during quad shape detection: ',e)
          self.extracted_img_data.append([original_image,extracted_quad,name_arr[index]])
          else: print('No image is found during the extraction process')


          使用pdf2image將pdf轉(zhuǎn)換為圖像:

          def Img2Pdf(dirname):        images = []        #get the pdf file    for x in os.listdir(dirname):        if (dirname.split('.')[1]) == 'pdf':            pdf_filename = x            images_from_path = convert_from_path(os.path.join(dirname),dpi=300, poppler_path = r'C:\Program Files (x86)\poppler-0.68.0_x86\poppler-0.68.0\bin')for image in images_from_path:                images.append(np.array(image))                    return images


          第二步:卷積神經(jīng)網(wǎng)絡(luò)


          由于提取的圖像片段將具有相對(duì)較小的尺寸,簡(jiǎn)單的3層CNN將為我們提供幫助,但我們?nèi)匀恍枰尤胍恍┱齽t化和Adam來(lái)優(yōu)化輸出。


          網(wǎng)絡(luò)應(yīng)針對(duì)每種類型的圖像樣本分別進(jìn)行訓(xùn)練,以獲得更好的精度。如果添加了新的圖像形狀,可以創(chuàng)建一個(gè)新的網(wǎng)絡(luò),但現(xiàn)在我們對(duì)復(fù)選框和單選按鈕都使用了相同的網(wǎng)絡(luò)。它目前只是一個(gè)二進(jìn)制分類,但進(jìn)一步的分類也可以這樣做:

          • 勾選復(fù)選框

          • 空復(fù)選框

          • 其他

          #keras thingsfrom keras.utils import to_categoricalfrom keras import layersfrom keras import modelsfrom keras.regularizers import l2

          Y_test_orig = to_categorical(Y_test_orig, num_classes=2) Y_train_orig = to_categorical(Y_train_orig, num_classes=2)
          # 3 layer ConvNetmodel = models.Sequential()model.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(32,32,1)))model.add(layers.MaxPooling2D((2, 2)))
          model.add(layers.Conv2D(64, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))
          model.add(layers.Conv2D(128, (3, 3), activation='relu'))model.add(layers.MaxPooling2D((2, 2)))
          #dense layermodel.add(layers.Flatten())
          #add the regulizermodel.add(layers.Dense(128, activation='linear', activity_regularizer=l2(0.0003)))model.add(layers.Dense(128, activation='relu'))model.add(layers.Dense(2, activation='sigmoid'))
          model.summary()
          from keras.optimizers import Adamopt = Adam(lr=0.001)model.compile(optimizer=opt, loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])
          ntrain = len(X_train_orig)nval = len(X_test_orig)X_train_orig = X_train_orig.reshape((len(X_train_orig),32,32,1)) X_test_orig = X_test_orig.reshape((len(X_test_orig),32,32,1))
          train_datagen = ImageDataGenerator(rescale = 1./255,rotation_range = 40, width_shift_range = .2, height_shift_range = .2, shear_range = .2, zoom_range = .2, horizontal_flip = True)
          val_datagen = ImageDataGenerator(rescale = 1./255)
          train_generator = train_datagen.flow(X_train_orig,Y_train_orig,batch_size=32)val_generator = val_datagen.flow(X_test_orig,Y_test_orig,batch_size = 32)

          #X_train_orig, X_test_orig, Y_train_orig,Y_test_orighistory = model.fit_generator(train_generator,steps_per_epoch = ntrain/32, epochs = 64, validation_data = val_generator, validation_steps = nval/32 )

          第3步中,我們將把所有內(nèi)容整合在一個(gè)Sklearn pipeline中,并通過(guò)predict函數(shù)將其公開(kāi)。我們沒(méi)有介紹的一個(gè)重要功能是將復(fù)選框或單選按鈕與文檔中相應(yīng)的文本相關(guān)聯(lián)。在實(shí)際應(yīng)用中,僅僅檢測(cè)沒(méi)有關(guān)聯(lián)的元素是毫無(wú)用處的。


          GITHUB代碼鏈接:

          https://github.com/nebuchadnezzar26/Shape-Detector

          往期精彩回顧




          站qq群554839127,加入微信群請(qǐng)掃碼:
          瀏覽 58
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  成人福利免费视频 | 韩国毛片视频 | 豆花视频一区免费 | www亚洲无 码A片 | 自拍偷拍精品视频 |