假设您要隔离眼睛血管,这里有一种方法,可以分为两个阶段,一个是去除伪影,另一个是隔离血管
- 将图像转换为灰度
- 大津阈值获取二值图像
- 执行形态学操作以去除伪影
- 隔离血管的自适应阈值
- 使用最大阈值区域查找轮廓和过滤
- 按位与得到最终结果
从您的原始图像开始,我们转换为灰度和 Otsu 的阈值以获得二值图像
现在我们执行 morph open 以移除伪影(左)。我们反转这个掩码以获得白色边框,然后进行一系列按位运算来获得去除的伪影图像(右)
从这里我们自适应阈值来获得静脉
请注意,存在不需要的边界,因此我们使用最大阈值区域找到轮廓并进行过滤。如果轮廓通过过滤器,我们将其绘制到空白蒙版上
最后,我们对原始图像执行按位与运算以获得我们的结果
请注意,我们可以在自适应阈值之后执行额外的变形打开以去除小颗粒噪声,但代价是它将去除静脉细节。我将把这个可选步骤留给你
import cv2
import numpy as np
# Grayscale, Otsu's threshold, opening
image = cv2.imread('1.png')
blank_mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,15))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)
inverse = 255 - opening
inverse = cv2.merge([inverse,inverse,inverse])
removed_artifacts = cv2.bitwise_and(image,image,mask=opening)
removed_artifacts = cv2.bitwise_or(removed_artifacts, inverse)
# Isolate blood vessels
veins_gray = cv2.cvtColor(removed_artifacts, cv2.COLOR_BGR2GRAY)
adaptive = cv2.adaptiveThreshold(veins_gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,3)
cnts = cv2.findContours(adaptive, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area < 5000:
cv2.drawContours(blank_mask, [c], -1, (255,255,255), 1)
blank_mask = cv2.cvtColor(blank_mask, cv2.COLOR_BGR2GRAY)
final = cv2.bitwise_and(image, image, mask=blank_mask)
# final[blank_mask==0] = (255,255,255) # White version
cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.imshow('removed_artifacts', removed_artifacts)
cv2.imshow('adaptive', adaptive)
cv2.imshow('blank_mask', blank_mask)
cv2.imshow('final', final)
cv2.waitKey()