使用OpenCV自動(dòng)去除背景色
點(diǎn)擊上方“小白學(xué)視覺(jué)”,選擇加"星標(biāo)"或“置頂”
重磅干貨,第一時(shí)間送達(dá)
幾天前,我遇到了一個(gè)項(xiàng)目,要求將草圖放到某個(gè)文件夾中時(shí)刪除草圖的白色背景。這都是在硬件掃描儀中發(fā)生的。
下面是一個(gè)草圖示例:

第一步是安裝此項(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)建三個(gè)不同的變量:要處理的文件夾的名稱,圖像在處理后存儲(chǔ)的文件夾的名稱,以及在監(jiān)視文件夾時(shí)的輪詢時(shí)間(即,它檢查文件夾中更改的頻率,在我們這里設(shè)置的是一秒鐘)
watch_folder = ‘toprocess’processed_folder = ‘processed’poll_time = 1
文件夾“ toprocess”和“ processed”放置在和我們的python腳本的同一目錄中。
然后,我們將介紹我們程序主要功能的代碼,它將監(jiān)視我們的“ toprocess”目錄,如果沒(méi)有發(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
這段代碼將無(wú)限循環(huán)運(yùn)行,直到腳本被殺死為止。啟動(dòng)后,它將文件存儲(chǔ)在名為“ before”的詞典目錄中。接下來(lái),下面將分解介紹無(wú)限循環(huán)中的步驟:
睡眠指定的poll_time(1秒)。 將文件信息存儲(chǔ)在名為after的字典目錄中。 通過(guò)比較之后的IN和之前的NOT來(lái)存儲(chǔ)已添加的內(nèi)容 檢查最后添加的元素(added [0])(如果存在),然后調(diào)用一個(gè)函數(shù),我們將在文件上稍作介紹的processImage進(jìn)行討論。 如果已刪除,請(qǐng)通過(guò)打印一些信息來(lái)讓用戶知道。 最后,將目錄中的最新文件進(jìn)行更新。
接下來(lái)介紹processImage函數(shù),這是程序的核心。這就是OpenCV后臺(tái)刪除魔術(shù)發(fā)生的地方。下面的注釋解釋了該代碼(需要基本的OpenCV知識(shí)):
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 nowimage = 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 COLORShMin = 29 # Hue minimumsMin = 30 # Saturation minimumvMin = 0 # Value minimum (Also referred to as brightness)hMax = 179 # Hue maximumsMax = 255 # Saturation maximumvMax = 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 HSVmask = 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)
接下來(lái)是一個(gè)非常簡(jiǎn)單的功能,可以正確地完成工作。再次強(qiáng)調(diào),使用閾值可以提供更好的結(jié)果。我們需要討論的最后一件事是mini helper函數(shù),該函數(shù)為文件名生成隨機(jī)字符串。
def randomString(length):letters = string.ascii_lowercasereturn ‘’.join(random.choice(letters) for i in range(length))
這是一個(gè)簡(jiǎn)單的功能。它使用“string”庫(kù)獲取字母,然后根據(jù)我們傳入的長(zhǎng)度加入隨機(jī)選擇的字符。傳入5的長(zhǎng)度將生成5個(gè)字符的字符串。
整個(gè)程序的處理結(jié)果如下所示:

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