OpenCV实现从灰度图像切出Mask前景区域

从灰度图像,根据阈值,切出多个前景区域,过滤面积太小的图像。

OpenCV的Python逻辑,clip_gray_patches

def clip_gray_patches(img_gray, ths=32, filter_percent=0.0005): """ 从灰度图像切出多个前景区域,阈值大于ths,过滤面积占比小于filter_percent的图像 @param img_gray: 灰度图像 @param ths: 前景阈值 @param filter_percent: 过滤面积 @return: patches list, 轮廓图像 """ # 根据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的前景设置为255,背景设置为0 mask = np.zeros(img_gray.shape) cv2.drawContours(mask, [cnt], -1, 255, -1) mask = mask.astype(np.uint8) # 将原图,根据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

输入的灰度图像:

输出图像:

到此这篇关于OpenCV实现从灰度图像切出Mask前景区域的文章就介绍到这了,更多相关OpenCV Mask前景区域内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!

推荐阅读