欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

OpenCV實現(xiàn)從灰度圖像切出Mask前景區(qū)域

 更新時間:2022年06月16日 08:59:22   作者:SpikeKing  
本文主要介紹了如何利用OpenCV實現(xiàn)從灰度圖像,根據(jù)閾值,切出多個前景區(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)文章

最新評論