使用传统图像处理获取单目标mask的bbox

Mask原图

该图像存在噪声,白色背景为255,灰色为128,黑色部分为0

mask原图

实现效果

去燥 + bbox

最终效果

Code

依赖库

pip install scikit-image opencv-python numpy

核心代码

import numpy as np
import cv2
import PIL.Image as Image
from skimage import measure, morphology

# 载入原图
img = cv2.imread('0001.png')
cv2.imshow('origin', img)
cv2.waitKey(5000)
cv2.destroyAllWindows()
# 将非背景部分转为黑色,此时图像只剩下255和0两种数值
img[img != 255] = 0
# 将rgb图转灰度图
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 连接性检测,num为当前图像有多少个不连接目标
labels, num = measure.label(img, background=255, return_num=True, connectivity=2)
# 将数值调整为0和1,对应false和true
img[img == 0] = 1
img[img == 255] = 0
bool_area = np.array(img, bool)
# 移除小目标,最小目标尺寸为2 piexl
bool_area = morphology.remove_small_objects(bool_area, min_size=2)
# 获取为true的像素索引
area = np.array(np.where(bool_area == True))
# 根据x和y的最值画出bbox
ori = cv2.rectangle(cv2.imread('0001.png'), (np.min(area[1]), np.min(area[0])), (np.max(area[1]), np.max(area[0])), (255, 0, 0), 1, 4)
cv2.imshow('pred', ori)
cv2.waitKey(5000)
cv2.destroyAllWindows()

多目标思路

  1. 先用skimage.morphology.remove_small_objects函数去掉噪声(小目标)。
  2. 再使用连接性检测skimage.measure.label函数返回的ndarray进行统计,该函数返回的不同目标的像素会带有不同的编号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex-Leung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值