首页 > 编程语言 >基于小波分析的糖尿病视网膜病变检测(Python)

基于小波分析的糖尿病视网膜病变检测(Python)

时间:2024-07-15 12:56:43浏览次数:9  
标签:plt img Python imm cv2 于小波 视网膜 np import

from scipy import misc
from PIL import Image
from skimage import exposure
from sklearn import svm


import scipy
from math import sqrt,pi
from numpy import exp
from matplotlib import pyplot as plt
import numpy as np
import glob
import matplotlib.pyplot as pltss
import cv2
from matplotlib import cm
import pandas as pd
from math import pi, sqrt
import pywt

Pre-processing

immatrix=[]
im_unpre = []


for i in range(1,90):
    img_pt = r'image'
    if i < 10:
        img_pt = img_pt + "00" + str(i) + ".png"
    else:
        img_pt = img_pt + "0" + str(i)+ ".png"


    img = cv2.imread(img_pt)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    equ = cv2.equalizeHist(img_gray) 
    immatrix.append(np.array(equ).flatten())
np.shape(np.array(equ).flatten())
(1728000,)

Visualising a random image after the above steps the array contains 90 images

np.shape(immatrix)
np.shape(equ)
plt.imshow(immatrix[78].reshape((1152,1500)),cmap='gray')
plt.show()

Performing Discrete-Wavelet transform on the 2-D array available

imm_dwt = []
for equ in immatrix:
    equ = equ.reshape((1152,1500))
    coeffs = pywt.dwt2(equ, 'haar')
    equ2 = pywt.idwt2(coeffs, 'haar')
    imm_dwt.append(np.array(equ2).flatten())

Visualising a random image

np.shape(imm_dwt)
np.shape(equ2)
plt.imshow(imm_dwt[78].reshape((1152,1500)),cmap='gray')
plt.show()

def _filter_kernel_mf_fdog(L, sigma, t = 3, mf = True):
    dim_y = int(L)
    dim_x = 2 * int(t * sigma)
    arr = np.zeros((dim_y, dim_x), 'f')
    
    ctr_x = dim_x / 2 
    ctr_y = int(dim_y / 2.)


    it = np.nditer(arr, flags=['multi_index'])
    while not it.finished:
        arr[it.multi_index] = it.multi_index[1] - ctr_x
        it.iternext()


    two_sigma_sq = 2 * sigma * sigma
    sqrt_w_pi_sigma = 1. / (sqrt(2 * pi) * sigma)
    if not mf:
        sqrt_w_pi_sigma = sqrt_w_pi_sigma / sigma ** 2


    def k_fun(x):
        return sqrt_w_pi_sigma * exp(-x * x / two_sigma_sq)


    def k_fun_derivative(x):
        return -x * sqrt_w_pi_sigma * exp(-x * x / two_sigma_sq)


    if mf:
        kernel = k_fun(arr)
        kernel = kernel - kernel.mean()
    else:
        kernel = k_fun_derivative(arr)


    return cv2.flip(kernel, -1) 


def show_images(images,titles=None, scale=1.3):
    n_ims = len(images)
    if titles is None: titles = ['(%d)' % i for i in range(1,n_ims + 1)]
    fig = plt.figure()
    n = 1
    for image,title in zip(images,titles):
        a = fig.add_subplot(1,n_ims,n)
        if image.ndim == 2:
            plt.imshow(image, cmap = cm.Greys_r)
        else:
            plt.imshow(cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
        a.set_title(title)
        plt.axis("off")
        n += 1
    fig.set_size_inches(np.array(fig.get_size_inches(), dtype=np.float) * n_ims / scale)
    plt.show()




def gaussian_matched_filter_kernel(L, sigma, t = 3):
    '''
    K =  1/(sqrt(2 * pi) * sigma ) * exp(-x^2/2sigma^2), |y| <= L/2, |x| < s * t
    '''
    return _filter_kernel_mf_fdog(L, sigma, t, True)


def createMatchedFilterBank(K, n = 12):
    rotate = 180 / n
    center = (K.shape[1] / 2, K.shape[0] / 2)
    cur_rot = 0
    kernels = [K]


    for i in range(1, n):
        cur_rot += rotate
        r_mat = cv2.getRotationMatrix2D(center, cur_rot, 1)
        k = cv2.warpAffine(K, r_mat, (K.shape[1], K.shape[0]))
        kernels.append(k)


    return kernels


def applyFilters(im, kernels):


    images = np.array([cv2.filter2D(im, -1, k) for k in kernels])
    return np.max(images, 0)




gf = gaussian_matched_filter_kernel(20, 5)
bank_gf = createMatchedFilterBank(gf, 4)


imm_gauss = []
for equ2 in imm_dwt:
    equ2 = equ2.reshape((1152,1500))
    equ3 = applyFilters(equ2,bank_gf)
    imm_gauss.append(np.array(equ3).flatten())
np.shape(imm_gauss)
plt.imshow(imm_gauss[78].reshape((1152,1500)),cmap='gray')
plt.show()

def createMatchedFilterBank():
    filters = []
    ksize = 31
    for theta in np.arange(0, np.pi, np.pi / 16):
        kern = cv2.getGaborKernel((ksize, ksize), 6, theta,12, 0.37, 0, ktype=cv2.CV_32F)
        kern /= 1.5*kern.sum()
        filters.append(kern)
    return filters


def applyFilters(im, kernels):
    images = np.array([cv2.filter2D(im, -1, k) for k in kernels])
    return np.max(images, 0)


bank_gf = createMatchedFilterBank()
imm_gauss2 = []
for equ2 in imm_dwt:
    equ2 = equ2.reshape((1152,1500))
    equ3 = applyFilters(equ2,bank_gf)
    imm_gauss2.append(np.array(equ3).flatten())
np.shape(imm_gauss2)
plt.imshow(imm_gauss2[20].reshape((1152,1500)),cmap='gray')
plt.show()

np.shape(imm_gauss2)
plt.imshow(imm_gauss2[1].reshape((1152,1500)),cmap='gray')
plt.show()

e_ = equ3
np.shape(e_)
e_=e_.reshape((-1,3))
np.shape(e_)
(576000, 3)

Performing K-means Clusttering with PP centers(non random) neighbours on the final image

img = equ3
Z = img.reshape((-1,3))


Z = np.float32(Z)


k=cv2.KMEANS_PP_CENTERS


criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 2
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,k)


center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))
imm_kmean = []
for equ3 in imm_gauss2:
    img = equ3.reshape((1152,1500))
    Z = img.reshape((-1,3))


    Z = np.float32(Z)


    k=cv2.KMEANS_PP_CENTERS


    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    K = 2
    ret,label,center=cv2.kmeans(Z,K,None,criteria,10,k)


    center = np.uint8(center)
    res = center[label.flatten()]
    res2 = res.reshape((img.shape))
    imm_kmean.append(np.array(res2).flatten())
np.shape(imm_kmean)
plt.imshow(imm_kmean[78].reshape((1152,1500)),cmap="gray")
plt.show()

工学博士,担任《Mechanical System and Signal Processing》审稿专家,担任《中国电机工程学报》优秀审稿专家,《控制与决策》,《系统工程与电子技术》,《电力系统保护与控制》,《宇航学报》等EI期刊审稿专家,擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

知乎学术咨询:https://www.zhihu.com/consult/people/792359672131756032?isMe=1

工学博士,担任《Mechanical System and Signal Processing》审稿专家,担任《中国电机工程学报》优秀审稿专家,《控制与决策》,《系统工程与电子技术》,《电力系统保护与控制》,《宇航学报》等EI期刊审稿专家,擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

擅长领域:现代信号处理,机器学习,深度学习,数字孪生,时间序列分析,设备缺陷检测、设备异常检测、设备智能故障诊断与健康管理PHM等。

标签:plt,img,Python,imm,cv2,于小波,视网膜,np,import
From: https://blog.csdn.net/weixin_39402231/article/details/140435898

相关文章

  • 简单的小波分析入门教程(第一部分,Python)
    importnumpyasnpimportmatplotlib.pyplotaspltimportpywtSimpleSignalAnalysisusingDWT#Generatethesignalt=np.linspace(0,1,1000,endpoint=False)signal=np.cos(2.0*np.pi*7*t)+np.sin(2.0*np.pi*13*t)#ApplyDWTcoeffs=p......
  • Python数据库应用
      通过文件操作可以实现简单的数据操作功能,如果要处理的数据量巨大,则需要将数据存储在数据库中。Python支持多种数据库。  本章主要介绍数据库概念以及结构化数据库查询语言SQL,分析并理解Python自带的轻量级关系数据库SQLlite的使用方法(同样用于MySQL数据库)  文......
  • 基于风光储能和需求响应的微电网日前经济调度(Python代码实现)
    目录0引言1计及风光储能和需求响应的微电网日前经济调度模型1.1风光储能需求响应都不参与的模型1.2风光参与的模型1.3风光和储能参与模型1.4风光和需求响应参与模型1.5风光储能和需求响应都参与模型 2需求侧响应评价2.1 负载率2.2可再生能源消纳率2.3用户......
  • 基于风光储能和需求响应的微电网日前经济调度(Python代码实现)
    目录0引言1计及风光储能和需求响应的微电网日前经济调度模型1.1风光储能需求响应都不参与的模型1.2风光参与的模型1.3风光和储能参与模型1.4风光和需求响应参与模型1.5风光储能和需求响应都参与模型 2需求侧响应评价2.1 负载率2.2可再生能源消纳率2.3用户......
  • Python酷库之旅-第三方库Pandas(023)
    目录一、用法精讲58、pandas.isnull函数58-1、语法58-2、参数58-3、功能58-4、返回值58-5、说明58-6、用法58-6-1、数据准备58-6-2、代码示例58-6-3、结果输出59、pandas.notna函数59-1、语法59-2、参数59-3、功能59-4、返回值59-5、说明59-6、用法59-6-1、......
  • Python - garbage collection
    References【说站】python标记清除的过程深度讲解python垃圾回收机制GarbageCollectionasaMemoryManagementTechniqueinPythonQ&AQ1:python代码:x=10,y=x在这段代码中,变量x和y是不是存放在栈内存中的gcroots对象A1:在Python中,x=10和y=x这两行代码涉......
  • Python类型注释
    基本类型注释#变量名后面用":"表示类型注释string_val:str=""int_val:int=0float_val:float=0.0dic_val:dict=dict()list_val:list=list()tuple_val:tuple=tuple()函数形参&结果注释#形参名后面用":"表示类型注释,输出结果用"->"表示类型注释def......
  • Python中 `__pycache__` 文件夹是什么?
    引言当你编写一个独立的Python脚本时,目录结构看起来可能没什么特别。但随着项目逐渐变得复杂,你可能会倾向于将一些功能分离到其他模块或包中。这时,你可能会发现在源文件旁边,似乎毫无规律地,突然冒出一个__pycache__文件夹。project/│├──mathematics/│││├──......
  • Python常用数据类型 新手必看 超详细介绍
    目录一、Int整型二、Float浮点型科学计数法三、Bool布尔类型bool函数四、Str字符型字符串的声明字符串的常见操作查找:计数:大小写转换:编码与解码:切割与拼接:替换:五、None六、List列表列表的声明列表的常见操作 增加元素:删除元素:其他:七、Tuple元组元组的......
  • Python网页开发的常用框架
    Python网页开发的框架众多,各有其独特的特点、缺点以及在性能上的优劣势。以下是一些主流的Python网页开发框架及其特点的详细介绍:1.Django特点:全功能框架:Django是一个高级PythonWeb框架,鼓励快速开发和干净、实用的设计。它遵循MVC(模型-视图-控制器)设计模式,但Django中更......