用opencv和python读取医学图片:mha
# -*- coding: utf-8 -*-
"""
Created on Sat Jan? 5 09:15:27 2019
@author: shenfangyuan
pip install SimpleITK
1,anxuexin.mha文件是(33,512,512)維的圖片,(通道數(shù)量=33,高=512,寬=512)
? 我只是選用了(21,:,:)這個(gè)通道的數(shù)據(jù)進(jìn)行試驗(yàn).可以考慮 把各個(gè)通道數(shù)據(jù)"邏輯或",
? "邏輯與"等操作.數(shù)學(xué)上的sum累加"不是好方法"
2,anxuexin.mha每個(gè)通道i的數(shù)據(jù)(channel=i,512,512)是 "0--1"二進(jìn)制數(shù)據(jù),? ?
? 相當(dāng)于true--false數(shù)據(jù)
3,anxuexin.mha數(shù)據(jù)類型dtype=np.unit16,注意這不是opencv常用的uint8類型
? 所以,送到opencv處理的時(shí)候最好先用np.unit8()函數(shù)進(jìn)行轉(zhuǎn)換.
4,由于數(shù)據(jù)值域是0--1,相當(dāng)于邏輯數(shù)據(jù),為了用opencv正常顯示,需要乘以255,值域
? 變?yōu)?--255,變成黑白圖片.
5,plt 圖像處理軟件可以直接顯示0-1圖片
6,我們經(jīng)常遇到的圖片像素的數(shù)據(jù)類型:
??? 1) 0--255 np.uint8:這種類型能夠被opencv直接處理
??? 2) 0.0--1.0? np.float類型的浮點(diǎn)數(shù)據(jù),一般在圖像像素進(jìn)行數(shù)值計(jì)算時(shí)候使用的類型
??? 3) true-1 ,false-0 :邏輯類型:需要轉(zhuǎn)換為0--255后才能顯示和存儲(chǔ).
??? 4) 可以用 img > 127 這樣的邏輯表達(dá)式方法 大概判斷數(shù)據(jù)范圍
"""
import matplotlib.pyplot as plt
import numpy as np
import SimpleITK
import cv2
filename = 'anxuexin.mha' #文件名稱
img = SimpleITK.ReadImage(filename) #讀取文件內(nèi)容
img_data = SimpleITK.GetArrayFromImage(img) #獲取文件中的圖片數(shù)據(jù)
img_tmp = np.zeros([512,512], dtype=np.uint8) #初始化一個(gè)512x512的緩沖區(qū)
#for i? in range(20,21):
#??? img_tmp = img_tmp + img_data[i,:,:]
img_tmp = img_data[21,:,:]
#從(33,512,512)數(shù)據(jù)中讀取 第21維數(shù)據(jù)到緩沖區(qū).,你可以選"其他通道"
print('-----',np.sum(np.sum(img_tmp))) #用該方法,看看該是否為"空?qǐng)D片"
img_tmp1 = np.uint8(img_tmp)*255
#把數(shù)據(jù)從uint16轉(zhuǎn)換為uint8,在把0--1轉(zhuǎn)換為0--255
#plt.imshow(img_tmp,cmap='gray') #plt軟件是可以直接顯示0--1數(shù)據(jù)的
cv2.imwrite('1.jpg',img_tmp1)? #將數(shù)據(jù)轉(zhuǎn)換為jpg格式保存起來(lái)
cv2.imshow('img_mha',img_tmp1)? #圖片顯示
cv2.waitKey(0)? #等待用戶輸入
cv2.destroyAllWindows()? #注銷顯示的窗口
總結(jié)
以上是生活随笔為你收集整理的用opencv和python读取医学图片:mha的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百钱买百鸡问题,Python编程解决
- 下一篇: 【转载:80个Python经典资料(教程