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

发布时间:2022-6-16 11:43

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

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图像处理之直方图比较方法详解 生活杂谈

OpenCV图像处理之直方图比较方法详解

直方图比较是对输入的两张图像进行计算得到直方图H1与H2,归一化到相同的尺度空间,然后可以通过计算H1与H2的之间的距离得到两个直方图的相似程度,进而比较图像本身的相似程度。本文将为大家详细讲讲直方图...
GoLang与Java各自生成grpc代码流程介绍 生活杂谈

GoLang与Java各自生成grpc代码流程介绍

1.背景: 由于公司的日志系统使用的是plumelog,最近生产环境老是报 jedis连接池不够,导致丢失日志,而且服务老是重启,怀疑跟日志系统有关,于是自己改造plumelog,使用go grpc...
MySQL同步数据Replication的实现步骤 生活杂谈

MySQL同步数据Replication的实现步骤

MySQL提供了Replication功能,可以实现将一个数据库的数据同步到多台其他数据库。前者通常称之为主库(master),后者则被称从库(slave)。MySQL复制过程采用异步方式,但延时非常...