xfzh193

python+opencv阈值分割

  1 import matplotlib.pyplot as plt
  2 import numpy as np
  3 import os
  4 import pydicom
  5 import cv2
  6 
  7 info = {}
  8 # 读取dicom文件,乳腺癌MRI图片
  9 dcm = pydicom.read_file("D:/1/dicom/datuidwi.dcm")
 10 # 通过字典关键字来获取图像的数据元信息(当然也可以根据TAG号)
 11 # 这里获取几种常用信息
 12 info["PatientID"] = dcm.PatientID               # 患者ID
 13 info["PatientName"] = dcm.PatientName           # 患者姓名
 14 #info["PatientBirthData"] = dcm.PatientBirthData # 患者出生日期
 15 info["PatientAge"] = dcm.PatientAge             # 患者年龄
 16 info[\'PatientSex\'] = dcm.PatientSex             # 患者性别
 17 info[\'StudyID\'] = dcm.StudyID                   # 检查ID
 18 info[\'StudyDate\'] = dcm.StudyDate               # 检查日期
 19 info[\'StudyTime\'] = dcm.StudyTime               # 检查时间
 20 info[\'InstitutionName\'] = dcm.InstitutionName   # 机构名称
 21 info[\'Manufacturer\'] = dcm.Manufacturer         # 设备制造商
 22 info[\'StudyDescription\']=dcm.StudyDescription   # 检查项目描述
 23 print(info)
 24 
 25 filename = "D:/1/dicom/datuidwi.dcm"
 26 jpgname = "D:/1/dicom/test4.jpg"
 27 # 读取dicom文件
 28 dcm = pydicom.read_file(filename)
 29 # 获取图像唯一标识符UID
 30 uid = dcm.SOPInstanceUID
 31 # 获取像素矩阵
 32 img_arr = dcm.pixel_array
 33 # 打印矩阵大小
 34 #print(img_arr.shape)
 35 # 获取像素点个数
 36 lens = img_arr.shape[0]*img_arr.shape[1]
 37 # 获取像素点的最大值和最小值
 38 arr_temp = np.reshape(img_arr,(lens,))
 39 max_val = max(arr_temp)
 40 min_val = min(arr_temp)
 41 # 图像归一化
 42 img_arr = (img_arr-min_val)/(max_val-min_val) 
 43 # 绘制图像并保存
 44 #保存图片时去掉周围白边
 45 plt.axis(\'off\')
 46 fig = plt.gcf()
 47 fig.set_size_inches(7.0/3,7.0/3) #dpi = 300, output = 700*700 pixels
 48 plt.gca().xaxis.set_major_locator(plt.NullLocator())
 49 plt.gca().yaxis.set_major_locator(plt.NullLocator())
 50 plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
 51 plt.margins(0,0)
 52 plt.imshow(img_arr,cmap=plt.cm.bone)
 53 fig.savefig(jpgname, format=\'jpg\', transparent=True, dpi=300, pad_inches = 0)
 54 
 55 #获取图像灰度直方图查看灰度分布
 56 img=cv2.imread(\'D:/1/dicom/test4.jpg\')
 57 plt.hist(img.ravel(),256,[0,256])#ravel函数功能是将多维数组降为一维数组
 58 plt.show()
 59 
 60 img = cv2.imread(\'D:/1/dicom/test4.jpg\', 0)
 61 jpgname = \'D:/1/dicom/test58.jpg\'
 62 # 固定阈值
 63 ret, th1 = cv2.threshold(img, 165, 255, cv2.THRESH_BINARY)
 64 images = [img, th1]
 65 #保存粗分割结果
 66 plt.axis(\'off\')
 67 fig = plt.gcf()
 68 fig.set_size_inches(7.0/3,7.0/3) #dpi = 300, output = 700*700 pixels
 69 plt.gca().xaxis.set_major_locator(plt.NullLocator())
 70 plt.gca().yaxis.set_major_locator(plt.NullLocator())
 71 plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
 72 plt.margins(0,0)
 73 plt.imshow(images[1], \'gray\')
 74 fig.savefig(jpgname, format=\'jpg\', transparent=True, dpi=300, pad_inches = 0)
 75 #对粗分割结果中非病灶区域填充
 76 #截取图片中的指定区域或在指定区域添加某一图片
 77 def jie_image(src1):
 78     src2 = src1[5:125, 280:600]#截取第5行到125行的第280列到600列的区域
 79     #cv.imshow("截取", src2)
 80     src1[360:480, 280:600] = src2#指定位置填充,大小要一样才能填充
 81     cv2.imshow("合成", src1)
 82 src = cv2.imread("D:/1/dicom/test58.jpg", 0)
 83 #cv.imshow("原来", src)
 84 jie_image(src)
 85 cv2.waitKey(0)
 86 cv2.destroyAllWindows()
 87 cv2.imwrite(\'D:/1/dicom/test68.jpg\', src)
 88 
 89 #填充后得到第二次的粗分割结果,病灶区域存在孔洞,使用孔洞填充方法进行填充
 90 \'\'\'
 91 图像说明:
 92 图像为二值化图像,255白色为目标物,0黑色为背景
 93 要填充白色目标物中的黑色空洞
 94 \'\'\'
 95 imgPath = \'D:/1/dicom/test68.jpg\'
 96 SavePath = \'D:/1/dicom/test78.jpg\'
 97 def FillHole(imgPath,SavePath):
 98     im_in = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE);
 99     # 复制 im_in 图像
100     im_floodfill = im_in.copy()
101     # Mask 用于 floodFill,官方要求长宽+2
102     h, w = im_in.shape[:2]
103     mask = np.zeros((h+2, w+2), np.uint8)
104     # floodFill函数中的seedPoint必须是背景
105     isbreak = False
106     for i in range(im_floodfill.shape[0]):
107         for j in range(im_floodfill.shape[1]):
108             if(im_floodfill[i][j]==0):
109                 seedPoint=(i,j)
110                 isbreak = True
111                 break
112         if(isbreak):
113             break
114     # 得到im_floodfill
115     cv2.floodFill(im_floodfill, mask, seedPoint, 255);
116     # 得到im_floodfill的逆im_floodfill_inv
117     im_floodfill_inv = cv2.bitwise_not(im_floodfill)
118     # 把im_in、im_floodfill_inv这两幅图像结合起来得到前景
119     im_out = im_in | im_floodfill_inv
120     # 保存结果
121     cv2.imwrite(SavePath, im_out)
122 FillHole(imgPath,SavePath
#以上这种填充结果会把轮廓外围也填充,分割不准确,因此使用了MATLAB中的imfill函数对分割后病灶区域的结果进行孔洞填充,得到的分割结果如下图所示
clear all; clc; close all;
img = imread(\'D:\matlab\bin\test68.jpg\');
if ndims(img)==3
    img = rgb2gray(img);
end
img_bw = im2bw(img);
img_fill = imfill(img_bw, \'holes\');
imwrite(img_fill,\'D:\matlab\bin\temp34.jpg\');
%figure;
%subplot(1,2,1),imshow(img_bw), title(\'有空洞的图像\');
%subplot(1,2,2),imshow(img_fill), title(\'孔洞被填充的图像\');

由于一些原因,不能放原图,分割结果如下所示

粗分割结果                                                      

第一次填充后结果

孔洞填充得到最终分割结果


 参考文章:

1.https://www.zhihu.com/tardis/sogou/art/154181400

2.https://zhuanlan.zhihu.com/p/63919290

3.https://www.cnblogs.com/FHC1994/p/9033580.html

4.https://www.jianshu.com/p/293e04f134c3

作者:舟华520

出处:https://www.cnblogs.com/xfzh193/

本文以学习,分享,研究交流为主,欢迎转载,请标明作者出处!

分类:

技术点:

相关文章: