(这两天让医生标图,对病灶进行分割标注,结果所有图都是在原图上画的红线,所以需要自己另外生成对应的mask)
算法目标
筛选出图像中的红色区域生成一张带有边界的二值图,对闭合区间内的数值进行填充;


(输入) (输出)
实现程序
- import cv2
- import numpy as np
-
-
- def find_specific_color(img, pixel_rgb):
- # 找到指定颜色,其他颜色设置为背景
- mask = np.zeros((img.shape[0], img.shape[1]), np.uint8)
-
- for row in range(img.shape[0]):
- for col in range(img.shape[1]):
- r=img[row, col, 0]
- g=img[row, col, 1]
- b=img[row, col, 2]
-
- if([r,g,b]==pixel_rgb):
- mask[row][col]=255
- else:
- mask[row][col]=0
-
- return mask
-
-
- def flood_fill(img_closed_loop):
- # 找出图像中的闭合区间,对内部进行填充
- im_floodfill = img_closed_loop.copy()
- mask = np.zeros((img_closed_loop.shape[0]+2, img_closed_loop.shape[1]+2), np.uint8)
-
- cv2.floodFill(im_floodfill, mask, (0, 0), 255)
- im_floodfill_inv = cv2.bitwise_not(im_floodfill)
- im_out = img_closed_loop | im_floodfill_inv
-
- return im_out
-
-
- if __name__ == '__main__':
- img = cv2.imread('1.png')
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # cv2读取图像的通道为BGR需要进行转换
- mask = find_specific_color(img, [255, 0, 0]) # 设置需要找到的颜色RGB值,[255,0,0]表示红色
- mask = flood_fill(mask)
- cv2.imwrite('res.png', mask)