Matlab学习笔记-1

引言

今天做病理图像分割,matlab代码,本来打算改成python代码,但是仔细一想,后面还有很多要取中心,取块,算边界的问题,用matlab更方便一点。所以硬着头皮看matlab代码,早晚的事,不如现在就干。
python和matlab有一些语法很容易就混淆…… 所以几乎遇到问题就百度。

查看矩阵大小

假设A为矩阵,则size(A)为查看矩阵大小,如4行5列中的4,5
length(A)给出行数和列数中较大者,如4行5列中的5。
[H,W] = size(A) 将4传给H,5传给W。

matlab取模

在C或者python中,取模,我们采用5%2,但是matlab中%是注释,所以取模直接是一个函数,mod(5,2)

matlab读取存储图像

A = imread('name.jpg')读取图像, imwrite(A,'name.jpg')存储图像。存储图像时注意如果出现图像命名需要动态按顺序,可以采取如下方式:

mkdir('/home/yann/Split_Image') % 创建文件夹
imwrite(I,['/home/yann/Split_Image/',num2str(i),'.jpg']) % I为矩阵数据, i为动态变化数字

具体可见2 matlab图像读取和存储

matlab循环判断语句

记住for if结束后加上end

%%% 以下从1到100打印语句
for i = 1:1:100
disp(['this is the ', num2str(i), 'number!'])
end

具体可见3 matlab的for结构等

matlab 修改图片尺寸

resize之前,一定要确保已经读入文件imread()过。举例:

A = imread('/home/yann/a.jpg');
B = imresize(A,0.5); % 0.5 为尺寸倍数,可以是大于0的任何数
C = imresize(A,[100,100]) % 直接resize为固定尺寸大小

源码分享

用程君论文里引用的细胞核分割方法分割细胞核,然后基于核中心取40*40大小的块,并保存每一patch图像。

clear
close all
tic
A = imread('/home/yann/Graduation/histology_segmentation/sample.jpg');
seg = hmt(A,[],false); % get the segmentation result
stats = regionprops(seg, 'centroid'); % get seg result matrix 'centroid' data
c = struct2cell(stats); % turn the struct data to cell
position = int32(cell2mat(c(:))); % turn the cell data to mat format and int32 the double data, position variable is 172*2
% below is the loop for getting the patch 40*40 image based on the centroid coordinate as the center of the patch
% take the centroid as the base.
for i = 1:1:length(position)
center = position(i,:);
patch = A(max(center(1)-20,1):min(center(1)+20,600), max(center(2)-20,1):min(center(2)+20,600), 1:3);
imwrite(patch,['/home/yann/split_image/',num2str(i),'.jpg']); % save the patch image, function `imwrite`
if mod(i,20) ==0
disp ([num2str(i), '.jpg', ' has saved !']) % disp function
end
end
toc

文中hmt()方法出处
方法引用出处

其他

关于bwlabel() bwboundary() regionprops()等函数有时间再统一分析一下。

参考文献

1 matlab查看矩阵大小
2 matlab图像读取和存储
3 matlab的for结构等
Nucleus Segmentation in Histology Images with Hierarchical Multilevel Thresholding
Integrative Analysis of Histopathological Images and Genomic Data Predicts Clear Cell Renal Cell Carcinoma Prognosis