1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        使用OpenCV自動去除背景色

        共 4049字,需瀏覽 9分鐘

         ·

        2020-09-01 02:07


        點(diǎn)擊上方小白學(xué)視覺”,選擇加"星標(biāo)"或“置頂

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

        幾天前,我遇到了一個項(xiàng)目,要求將草圖放到某個文件夾中時刪除草圖的白色背景。這都是在硬件掃描儀中發(fā)生的。


        下面是一個草圖示例:

        第一步是安裝此項(xiàng)目的依賴關(guān)系,具體需要內(nèi)容我們將在下面列出。此外,我們還將使用Python 3.7。

        opencv_python==4.1.0.25pip install opencv-pythonnumpy==1.16.4pip install numpy


        之后,我們將導(dǎo)入項(xiàng)目所需的所有模塊


        import cv2import osimport stringimport randomfrom os import listdirfrom os.path import isfile, join, splitextimport timeimport sysimport numpy as npimport argparse


        然后,我們創(chuàng)建三個不同的變量:要處理的文件夾的名稱,圖像在處理后存儲的文件夾的名稱,以及在監(jiān)視文件夾時的輪詢時間(即,它檢查文件夾中更改的頻率,在我們這里設(shè)置的是一秒鐘)


        watch_folder = ‘toprocess’processed_folder = ‘processed’poll_time = 1


        文件夾“ toprocess”和“ processed”放置在和我們的python腳本的同一目錄中。


        然后,我們將介紹我們程序主要功能的代碼,它將監(jiān)視我們的“ toprocess”目錄,如果沒有發(fā)生任何更改,程序?qū)⑻幚泶嫒朐谠撐募A的所有圖像。


        before = dict([(f, None) for f in os.listdir(watch_folder)])while 1:  time.sleep(poll_time)  after = dict([(f, None) for f in os.listdir(watch_folder)])  added = [f for f in after if not f in before]  removed = [f for f in before if not f in after]  if added:    print(“Added “, “, “.join(added))  if added[0] is not None:    processImage(added[0])  if removed:    print(“Removed “, “, “.join(removed))  before = after


        這段代碼將無限循環(huán)運(yùn)行,直到腳本被殺死為止。啟動后,它將文件存儲在名為“ before”的詞典目錄中。接下來,下面將分解介紹無限循環(huán)中的步驟:

        • 睡眠指定的poll_time(1秒)。
        • 將文件信息存儲在名為after的字典目錄中。
        • 通過比較之后的IN和之前的NOT來存儲已添加的內(nèi)容
        • 檢查最后添加的元素(added [0])(如果存在),然后調(diào)用一個函數(shù),我們將在文件上稍作介紹的processImage進(jìn)行討論。
        • 如果已刪除,請通過打印一些信息來讓用戶知道。
        • 最后,將目錄中的最新文件進(jìn)行更新。


        接下來介紹processImage函數(shù),這是程序的核心。這就是OpenCV后臺刪除魔術(shù)發(fā)生的地方。下面的注釋解釋了該代碼(需要基本的OpenCV知識):

        def processImage(fileName):  # Load in the image using the typical imread function using our watch_folder path, and the fileName passed in, then set the final output image to our current image for now  image = cv2.imread(watch_folder + ‘/’ + fileName)  output = image  # Set thresholds. Here, we are using the Hue, Saturation, Value color space model. We will be using these values to decide what values to show in the ranges using a minimum and maximum value. THESE VALUES CAN BE PLAYED AROUND FOR DIFFERENT COLORS  hMin = 29  # Hue minimum  sMin = 30  # Saturation minimum  vMin = 0   # Value minimum (Also referred to as brightness)  hMax = 179 # Hue maximum  sMax = 255 # Saturation maximum  vMax = 255 # Value maximum  # Set the minimum and max HSV values to display in the output image using numpys' array function. We need the numpy array since OpenCVs' inRange function will use those.  lower = np.array([hMin, sMin, vMin])  upper = np.array([hMax, sMax, vMax])  # Create HSV Image and threshold it into the proper range.  hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Converting color space from BGR to HSV  mask = cv2.inRange(hsv, lower, upper) # Create a mask based on the lower and upper range, using the new HSV image  # Create the output image, using the mask created above. This will perform the removal of all unneeded colors, but will keep a black background.  output = cv2.bitwise_and(image, image, mask=mask)  # Add an alpha channel, and update the output image variable  *_, alpha = cv2.split(output)  dst = cv2.merge((output, alpha))  output = dst  # Resize the image to 512, 512 (This can be put into a variable for more flexibility), and update the output image variable.  dim = (512, 512)  output = cv2.resize(output, dim)  # Generate a random file name using a mini helper function called randomString to write the image data to, and then save it in the processed_folder path, using the generated filename.  file_name = randomString(5) + ‘.png’  cv2.imwrite(processed_folder + ‘/’ + file_name, output)



        接下來是一個非常簡單的功能,可以正確地完成工作。再次強(qiáng)調(diào),使用閾值可以提供更好的結(jié)果。我們需要討論的最后一件事是mini helper函數(shù),該函數(shù)為文件名生成隨機(jī)字符串。


        def randomString(length):  letters = string.ascii_lowercase  return ‘’.join(random.choice(letters) for i in range(length))


        這是一個簡單的功能。它使用“string”庫獲取字母,然后根據(jù)我們傳入的長度加入隨機(jī)選擇的字符。傳入5的長度將生成5個字符的字符串。


        整個程序的處理結(jié)果如下所示:


        流群


        歡迎加入公眾號讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器、自動駕駛、計(jì)算攝影、檢測、分割、識別、醫(yī)學(xué)影像、GAN、算法競賽等微信群(以后會逐漸細(xì)分),請掃描下面微信號加群,備注:”昵稱+學(xué)校/公司+研究方向“,例如:”張三?+?上海交大?+?視覺SLAM“。請按照格式備注,否則不予通過。添加成功后會根據(jù)研究方向邀請進(jìn)入相關(guān)微信群。請勿在群內(nèi)發(fā)送廣告,否則會請出群,謝謝理解~


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

        手機(jī)掃一掃分享

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

        手機(jī)掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            明星大尺度激情做爰视频 | 天天天天干| 97操逼视频 | 91特黄色 | 99精品视频在线观看视频 | 欧美cccc极品丰满hd | 国产精品一二三 | 亚洲精品午夜成人片DY888 | 国产美女爽爽爽 | 鸡吧插逼视频 |