matlab 类型转换,类型判断

  • char:Convert to character array,转换为字符数组;matlab 下没有 str 字符串类型转换;
    • char(0-255) ⇒ ASCII 码的转换;
  • im2double():
    • 将 intensity image (0-255,uint8 的整型类型)转换为 0-1 的 double 类型(double precision,双精度);

0. ismatrix()

ismatrix 对于三维的矩阵返回值为 logical false。只在一种情况下返回值才为 true,当矩阵的 size(A) 的返回值为 [m, n](不可以是 [m, n, p]),且 m, n 均非负时。

if ismatrix(I)
    I = cat(3, I, I, I);
end
            % 二维灰度图像变为三维图像;

1. uint8 与 double

另外对于 uint8,相加、相乘,都容易溢出,所谓溢出,就是得到的超过 255 的结果,都会截断为 255,一般这种情况,即会出现相加相乘运算时,先转换为 double 类型。

matlab 对数值类型十分敏感,

  • 对 uint8 类型,期待其值域范围为 0-255;
    • uint8 类型的变量之间,无论执行什么样的运算,或加或减,或乘或除,得到的结果还是 uint8 类型,最终的值域还是 0-255,不会出现负数,也不会比 255 更大;
  • 对于 double 则,期待的值域为 0-1;

    因此,如果要 imshow 一个 double 类型时,数据中大于 1 的数会视为溢出,也即显示为白色,

2. mat2gray

将 matrix 转换为灰度图像(grayscale),将无论是什么类型的 matrix(值可正可负),转化为可显示为图像的数值类型和数据范围。

I = imread(\'rice.png\');
J = filter2(fspecial(\'sobel\'), I);
K = mat2gray(J);

% 可以显示转换前后,J、K 矩阵各自的数据范围
subplot(121), histogram(J); subplot(122), histogram(K)

3. categorical to numeric

c = categorical({\'Male\',\'Female\',\'Female\',\'Male\',\'Female\'})
n = grp2idx(c)
  • Create index vector from grouping variable