Mask原图
该图像存在噪声,白色背景为255,灰色为128,黑色部分为0
实现效果
去燥 + 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()
多目标思路
- 先用skimage.morphology.remove_small_objects函数去掉噪声(小目标)。
- 再使用连接性检测skimage.measure.label函数返回的ndarray进行统计,该函数返回的不同目标的像素会带有不同的编号。