版权声明:本文为博主原创文章,转载请注明作者和出处。https://blog.csdn.net/xq920831/article/details/89671791
最近做了一个医学息肉图像分割,用到了传统算法中的形态学部分算法,下面是一个demo版,图像就不贴了,看看代码。
# -*- coding:utf-8 -*-
# Author: Agent Xu
import cv2
import numpy as np
from skimage import morphology,color
original_img = cv2.imread('C:/Users/Administrator/Desktop/colonoscopy/Colonoscopy-polyps-detection-with-CNNs-master/downloaded/Original/305.tif')
res = cv2.resize(original_img,None,fx=0.6, fy=0.6,
interpolation = cv2.INTER_CUBIC) #图形太大了缩小一点
img = color.rgb2gray(res)
#OpenCV定义的结构矩形元素
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
# eroded = cv2.erode(RedThresh,kernel) #腐蚀图像
# dilated = cv2.dilate(RedThresh,kernel) #膨胀图像
closed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel,iterations=3) #闭运算
opened = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel,iterations=1) #开运算
retval1, result1 = cv2.threshold(closed, 0.45, 1, cv2.THRESH_BINARY) #使用阈值获得二值图
retval2, result2 = cv2.threshold(opened, 0.45, 1, cv2.THRESH_BINARY) #使用阈值获得二值图
#编写一个函数来生成原始二值图像
def Convert_Bool(data):
return data < data.mean()
def Convert_Bool1(data):
return data > data.mean()
def Booltofloat(data):
(a,b) = data.shape
img = np.zeros((a,b))
for i in range(a):
for j in range(b):
if data[i,j] == False:
img[i,j] = 1
else:
img[i,j] = 0
return img
image1 = Convert_Bool(result2)
img_1 = morphology.remove_small_objects(image1, 1500)
img_1 = Booltofloat(img_1)
img_2 = Convert_Bool1(img_1)
img_2 = morphology.remove_small_objects(img_2, 200)
img_2 = Booltofloat(img_2)
gradient1 = cv2.morphologyEx(result1, cv2.MORPH_GRADIENT, kernel) #梯度
gradient2 = cv2.morphologyEx(result2, cv2.MORPH_GRADIENT, kernel)
gradient3 = cv2.morphologyEx(img_1, cv2.MORPH_GRADIENT, kernel)
sure_bg = cv2.dilate(img_2, kernel, iterations=1)
surface = cv2.erode(img_2, kernel, iterations=3)
sure_bg = np.uint8(sure_bg)
surface_fg = np.uint8(surface)
unknown = cv2.subtract(sure_bg, surface_fg)
ret, markers = cv2.connectedComponents(surface_fg)
cv2.imshow("original_img", res) #原图像
# cv2.imshow("R_channel_img", img)
# cv2.imshow("closed", closed)
# cv2.imshow("opened", opened)
# cv2.imshow("result1", result1)
# cv2.imshow("result2", result2)
# cv2.imshow("gradient1", gradient1)
# cv2.imshow("gradient2", gradient2)
# cv2.imshow("gradient3", gradient3)
# cv2.imshow("qqqq", sure_bg)
# cv2.imshow('img',img_2)
# cv2.imshow("xxxx", surface)
# cv2.imshow("Eroded Image",eroded) #显示腐蚀后的图像
# cv2.imshow("Dilated Image",dilated) #显示膨胀后的图像
# watershed transfrom
markers += 1
markers[unknown == 1] = 0
markers = cv2.watershed(res, markers=markers)
res[markers == -1] = [255, 0, 0]
cv2.imshow("jieguo", res)
#NumPy定义的结构元素
# NpKernel = np.uint8(np.ones((3,3)))
# Nperoded = cv2.erode(RedThresh,NpKernel) #腐蚀图像
# cv2.imshow("Eroded by NumPy kernel",Nperoded) #显示腐蚀后的图像
cv2.waitKey(0)
cv2.destroyAllWindows()