OpenCV實現(xiàn)從灰度圖像切出Mask前景區(qū)域
從灰度圖像,根據(jù)閾值,切出多個前景區(qū)域,過濾面積太小的圖像。
OpenCV的Python邏輯,clip_gray_patches
:
def clip_gray_patches(img_gray, ths=32, filter_percent=0.0005): """ 從灰度圖像切出多個前景區(qū)域,閾值大于ths,過濾面積占比小于filter_percent的圖像 @param img_gray: 灰度圖像 @param ths: 前景閾值 @param filter_percent: 過濾面積 @return: patches list, 輪廓圖像 """ # 根據(jù)thresh_val過濾mask ret, gray_mask = cv2.threshold(img_gray, ths, 1, 0) contours, hierarchy = cv2.findContours(gray_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img_area = get_image_size(img_gray) # 圖像面積 img_copy = copy.copy(img_gray) img_patches = [] # 遍歷全部輪廓 for cnt in contours: area = cv2.contourArea(cnt) if area / img_area < filter_percent: # 過濾小圖像 continue # 將小patch的前景設(shè)置為255,背景設(shè)置為0 mask = np.zeros(img_gray.shape) cv2.drawContours(mask, [cnt], -1, 255, -1) mask = mask.astype(np.uint8) # 將原圖,根據(jù)mask,貼入新圖像中,再提取mask masked = cv2.add(img_gray, np.zeros(np.shape(img_gray), dtype=np.uint8), mask=mask) box = get_mask_box(mask) img_patch = get_cropped_patch(masked, box) img_patches.append(img_patch) img_copy = cv2.drawContours(img_copy, [cnt], -1, 255, 1) # 繪制邊界 return img_patches, img_copy def get_image_size(img): """ 獲取圖像尺寸 """ h, w = img.shape[:2] return float(h * w) def get_mask_box(mask): """ mask的邊框 """ import numpy as np y, x = np.where(mask) x_min = np.min(x) x_max = np.max(x) y_min = np.min(y) y_max = np.max(y) box = [x_min, y_min, x_max, y_max] return box def get_cropped_patch(img, box): """ 獲取Img的Patch :param img: 圖像 :param box: [x_min, y_min, x_max, y_max] :return 圖像塊 """ h, w = img.shape[:2] x_min = int(max(0, box[0])) y_min = int(max(0, box[1])) x_max = int(min(box[2], w)) y_max = int(min(box[3], h)) if len(img.shape) == 3: img_patch = img[y_min:y_max, x_min:x_max, :] else: img_patch = img[y_min:y_max, x_min:x_max] return img_patch
輸入的灰度圖像:
輸出圖像:
到此這篇關(guān)于OpenCV實現(xiàn)從灰度圖像切出Mask前景區(qū)域的文章就介紹到這了,更多相關(guān)OpenCV Mask前景區(qū)域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python request設(shè)置HTTPS代理代碼解析
這篇文章主要介紹了Python request設(shè)置HTTPS代理代碼解析,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02python?中的requirements.txt?文件的使用詳情
這篇文章主要介紹了python?中的requirements.txt文件的使用詳情,文章圍繞主題展開詳細內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-05-05python 實現(xiàn)批量替換文本中的某部分內(nèi)容
今天小編就為大家分享一篇python 實現(xiàn)批量替換文本中的某部分內(nèi)容,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12Python使用?TCP協(xié)議實現(xiàn)智能聊天機器人功能
TCP協(xié)議適用于對效率要求相對較低而準確性要求很高的場合,下面通過本文給大家介紹基于Python?使用?TCP?實現(xiàn)智能聊天機器人,需要的朋友可以參考下2022-05-05python使用ctypes調(diào)用第三方庫時出現(xiàn)undefined?symbol錯誤詳解
python中時間的庫有time和datetime,pandas也有提供相應(yīng)的時間處理函數(shù),下面這篇文章主要給大家介紹了關(guān)于python使用ctypes調(diào)用第三方庫時出現(xiàn)undefined?symbol錯誤的相關(guān)資料,需要的朋友可以參考下2023-02-02