<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>

          使用Python+OpenCV進(jìn)行數(shù)據(jù)增廣方法綜述(附代碼演練)

          共 16143字,需瀏覽 33分鐘

           ·

          2021-03-23 17:24

          點(diǎn)擊下面卡片關(guān)注AI算法與圖像處理”,選擇加"星標(biāo)"或“置頂”

          重磅干貨,第一時(shí)間送達(dá)

          數(shù)據(jù)擴(kuò)充是一種增加數(shù)據(jù)集多樣性的技術(shù),無需收集更多的真實(shí)數(shù)據(jù),但仍然有助于提高模型的準(zhǔn)確性和防止模型過度擬合。在這篇文章中,你將學(xué)習(xí)使用Python和OpenCV實(shí)現(xiàn)最流行和最有效的對象檢測任務(wù)的數(shù)據(jù)擴(kuò)充過程。
          介紹的數(shù)據(jù)擴(kuò)充方法包括:
          1. 隨機(jī)剪裁
          2. Cutout
          3. ColorJitter
          4. 添加噪聲
          5. 過濾
          首先,讓我們導(dǎo)入幾個(gè)庫并準(zhǔn)備一些必要的子例程。
          import os
          import cv2
          import numpy as np
          import random

          def file_lines_to_list(path):
              '''
              ### Convert Lines in TXT File to List ###
              path: path to file
              '''

              with open(path) as f:
                  content = f.readlines()
              content = [(x.strip()).split() for x in content]
              return content

          def get_file_name(path):
              '''
              ### Get Filename of Filepath ###
              path: path to file
              '''

              basename = os.path.basename(path)
              onlyname = os.path.splitext(basename)[0]
              return onlyname

          def write_anno_to_txt(boxes, filepath):
              '''
              ### Write Annotation to TXT File ###
              boxes: format [[obj x1 y1 x2 y2],...]
              filepath: path/to/file.txt
              '''

              txt_file = open(filepath, "w")
              for box in boxes:
                  print(box[0], int(box[1]), int(box[2]), int(box[3]), int(box[4]), file=txt_file)
              txt_file.close()
          下圖在本文中用作示例圖像。

          隨機(jī)剪裁

          隨機(jī)剪裁:隨機(jī)選擇一個(gè)區(qū)域并將其裁剪出來,形成一個(gè)新的數(shù)據(jù)樣本,被裁剪的區(qū)域應(yīng)與原始圖像具有相同的寬高比,以保持對象的形狀。
          在上圖中,左邊的圖像是帶有真實(shí)邊界框的原始圖像(紅色部分),右邊的圖像是通過裁剪橙色框中的區(qū)域創(chuàng)建的新樣本。
          在新樣本的標(biāo)注中,去除所有與左側(cè)圖像中橙色框不重疊的對象,并將橙色框邊界上的對象的坐標(biāo)進(jìn)行細(xì)化,使之與新樣本相匹配。對原始圖像進(jìn)行隨機(jī)裁剪的輸出是新的裁剪后的圖像及其注釋。
          def randomcrop(img, gt_boxes, scale=0.5):
              '''
              ### Random Crop ###
              img: image
              gt_boxes: format [[obj x1 y1 x2 y2],...]
              scale: percentage of cropped area
              '''

              
              # Crop image
              height, width = int(img.shape[0]*scale), int(img.shape[1]*scale)
              x = random.randint(0, img.shape[1] - int(width))
              y = random.randint(0, img.shape[0] - int(height))
              cropped = img[y:y+height, x:x+width]
              resized = cv2.resize(cropped, (img.shape[1], img.shape[0]))
              
              # Modify annotation
              new_boxes=[]
              for box in gt_boxes:
                  obj_name = box[0]
                  x1 = int(box[1])
                  y1 = int(box[2])
                  x2 = int(box[3])
                  y2 = int(box[4])
                  x1, x2 = x1-x, x2-x
                  y1, y2 = y1-y, y2-y
                  x1, y1, x2, y2 = x1/scale, y1/scale, x2/scale, y2/scale
                  if (x1<img.shape[1and y1<img.shape[0]) and (x2>0 and y2>0):
                      if x1<0: x1=0
                      if y1<0: y1=0
                      if x2>img.shape[1]: x2=img.shape[1]
                      if y2>img.shape[0]: y2=img.shape[0]
                      new_boxes.append([obj_name, x1, y1, x2, y2])
              return resized, new_boxes

          Cutout

          Cutout是2017年由Terrance DeVries和Graham W. Taylor在他們的論文中介紹的,是一種簡單的正則化技術(shù),在訓(xùn)練過程中隨機(jī)掩蓋輸入的正方形區(qū)域,可以用來提高卷積神經(jīng)網(wǎng)絡(luò)的魯棒性和整體性能。這種方法不僅非常容易實(shí)現(xiàn),而且表明它可以與現(xiàn)有形式的數(shù)據(jù)擴(kuò)充和其他正則化器一起使用,進(jìn)一步提高模型的性能。
          • 論文地址:https://arxiv.org/abs/1708.04552
          與本文一樣,我們使用了cutout來提高圖像識別(分類)的精度,因此,如果我們將相同的方案部署到目標(biāo)檢測數(shù)據(jù)集中,可能會(huì)導(dǎo)致丟失目標(biāo)(特別是小目標(biāo))的問題。在下圖中,刪除了剪切區(qū)域(黑色區(qū)域)內(nèi)的大量小對象,這不符合數(shù)據(jù)增強(qiáng)的精神。
          為了使這種方式適合對象檢測,我們可以做一個(gè)簡單的修改,而不是僅使用一個(gè)遮罩并將其放置在圖像中的隨機(jī)位置,而是隨機(jī)選擇一半的對象,并將裁剪應(yīng)用于每個(gè)目標(biāo)區(qū)域,效果更佳。增強(qiáng)后的圖像如下圖所示。
          Cutout的輸出是一個(gè)新生成的圖像,我們不刪除對象或改變圖像大小,那么生成的圖像的注釋就是原始注釋。
          def cutout(img, gt_boxes, amount=0.5):
              '''
              ### Cutout ###
              img: image
              gt_boxes: format [[obj x1 y1 x2 y2],...]
              amount: num of masks / num of objects 
              '''

              out = img.copy()
              ran_select = random.sample(gt_boxes, round(amount*len(gt_boxes)))

              for box in ran_select:
                  x1 = int(box[1])
                  y1 = int(box[2])
                  x2 = int(box[3])
                  y2 = int(box[4])
                  mask_w = int((x2 - x1)*0.5)
                  mask_h = int((y2 - y1)*0.5)
                  mask_x1 = random.randint(x1, x2 - mask_w)
                  mask_y1 = random.randint(y1, y2 - mask_h)
                  mask_x2 = mask_x1 + mask_w
                  mask_y2 = mask_y1 + mask_h
                  cv2.rectangle(out, (mask_x1, mask_y1), (mask_x2, mask_y2), (000), thickness=-1)
              return out

          ColorJitter

          ColorJitter是另一種簡單的圖像數(shù)據(jù)擴(kuò)充類型,我們隨機(jī)改變圖像的亮度、對比度和飽和度。我相信這個(gè)“家伙”很容易被大多數(shù)讀者理解。
          def colorjitter(img, cj_type="b"):
              '''
              ### Different Color Jitter ###
              img: image
              cj_type: {b: brightness, s: saturation, c: constast}
              '''

              if cj_type == "b":
                  # value = random.randint(-50, 50)
                  value = np.random.choice(np.array([-50-40-30304050]))
                  hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
                  h, s, v = cv2.split(hsv)
                  if value >= 0:
                      lim = 255 - value
                      v[v > lim] = 255
                      v[v <= lim] += value
                  else:
                      lim = np.absolute(value)
                      v[v < lim] = 0
                      v[v >= lim] -= np.absolute(value)

                  final_hsv = cv2.merge((h, s, v))
                  img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
                  return img
              
              elif cj_type == "s":
                  # value = random.randint(-50, 50)
                  value = np.random.choice(np.array([-50-40-30304050]))
                  hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
                  h, s, v = cv2.split(hsv)
                  if value >= 0:
                      lim = 255 - value
                      s[s > lim] = 255
                      s[s <= lim] += value
                  else:
                      lim = np.absolute(value)
                      s[s < lim] = 0
                      s[s >= lim] -= np.absolute(value)

                  final_hsv = cv2.merge((h, s, v))
                  img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
                  return img
              
              elif cj_type == "c":
                  brightness = 10
                  contrast = random.randint(40100)
                  dummy = np.int16(img)
                  dummy = dummy * (contrast/127+1) - contrast + brightness
                  dummy = np.clip(dummy, 0255)
                  img = np.uint8(dummy)
                  return img

          添加噪聲

          通常,噪聲被認(rèn)為是圖像中不可預(yù)料的因素,然而,有幾種類型的噪聲(如高斯噪聲、椒鹽噪聲)可以用于數(shù)據(jù)擴(kuò)充,在深度學(xué)習(xí)中,添加噪聲是一種非常簡單而有益的數(shù)據(jù)擴(kuò)充方法。在下面的例子中,為了增強(qiáng)數(shù)據(jù),將高斯噪聲和椒鹽噪聲添加到原始圖像中。
          對于那些無法識別高斯噪聲和椒鹽噪聲區(qū)別的人,高斯噪聲的取值范圍取決于配置,從0到255,因此,在RGB圖像中,高斯噪聲像素可以是任何顏色。相反,椒鹽噪聲像素只能有兩個(gè)值:0或255,分別為黑色(椒)或白色(鹽)。
          def noisy(img, noise_type="gauss"):
              '''
              ### Adding Noise ###
              img: image
              cj_type: {gauss: gaussian, sp: salt & pepper}
              '''

              if noise_type == "gauss":
                  image=img.copy() 
                  mean=0
                  st=0.7
                  gauss = np.random.normal(mean,st,image.shape)
                  gauss = gauss.astype('uint8')
                  image = cv2.add(image,gauss)
                  return image
              
              elif noise_type == "sp":
                  image=img.copy() 
                  prob = 0.05
                  if len(image.shape) == 2:
                      black = 0
                      white = 255            
                  else:
                      colorspace = image.shape[2]
                      if colorspace == 3:  # RGB
                          black = np.array([000], dtype='uint8')
                          white = np.array([255255255], dtype='uint8')
                      else:  # RGBA
                          black = np.array([000255], dtype='uint8')
                          white = np.array([255255255255], dtype='uint8')
                  probs = np.random.random(image.shape[:2])
                  image[probs < (prob / 2)] = black
                  image[probs > 1 - (prob / 2)] = white
                  return image

          過濾

          本文介紹的最后一個(gè)數(shù)據(jù)擴(kuò)充過程是過濾。與添加噪聲類似,過濾也很簡單,易于實(shí)現(xiàn)。在實(shí)現(xiàn)中使用的三種濾波類型包括模糊(均值)、高斯和中值。
          def filters(img, f_type = "blur"):
              '''
              ### Filtering ###
              img: image
              f_type: {blur: blur, gaussian: gaussian, median: median}
              '''

              if f_type == "blur":
                  image=img.copy()
                  fsize = 9
                  return cv2.blur(image,(fsize,fsize))
              
              elif f_type == "gaussian":
                  image=img.copy()
                  fsize = 9
                  return cv2.GaussianBlur(image, (fsize, fsize), 0)
              
              elif f_type == "median":
                  image=img.copy()
                  fsize = 9
                  return cv2.medianBlur(image, fsize)

          總結(jié)

          在這篇文章中,主要向大家介紹了一個(gè)關(guān)于對象檢測任務(wù)中數(shù)據(jù)擴(kuò)充實(shí)現(xiàn)的教程。你們可以在這里找到完整實(shí)現(xiàn)。
          • https://github.com/tranleanh/data-augmentation


          個(gè)人微信(如果沒有備注不拉群!
          請注明:地區(qū)+學(xué)校/企業(yè)+研究方向+昵稱



          下載1:何愷明頂會(huì)分享


          AI算法與圖像處理」公眾號后臺回復(fù):何愷明,即可下載。總共有6份PDF,涉及 ResNet、Mask RCNN等經(jīng)典工作的總結(jié)分析


          下載2:終身受益的編程指南:Google編程風(fēng)格指南


          AI算法與圖像處理」公眾號后臺回復(fù):c++,即可下載。歷經(jīng)十年考驗(yàn),最權(quán)威的編程規(guī)范!



          下載3 CVPR2021

          AI算法與圖像處公眾號后臺回復(fù):CVPR,即可下載1467篇CVPR 2020論文 和 CVPR 2021 最新論文

          點(diǎn)亮 ,告訴大家你也在看



          瀏覽 112
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

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

          手機(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>
                  亚洲人性爱视频 | 黄色av网 | 精品一区二区三区东京热 | 黄色免费性爱视频 | 黄色直播免费在线 |