eig*_*tx2 4 rgb matlab image image-processing
我想在MATLAB中加载RGB图像并将其转换为二进制图像,我可以在其中选择二进制图像具有多少像素.例如,我将300x300 png/jpg图像加载到MATLAB中,最终得到的二进制图像(像素只能是#000或#FFF)可能是10x10像素.
这是我到目前为止所尝试的:
load trees % from MATLAB
gray=rgb2gray(map); % 'map' is loaded from 'trees'. Convert to grayscale.
threshold=128;
lbw=double(gray>threshold);
BW=im2bw(X,lbw); % 'X' is loaded from 'trees'.
imshow(X,map), figure, imshow(BW)
Run Code Online (Sandbox Code Playgroud)
(我从互联网搜索中得到了一些上述内容.)
在做这个时,我最终得到了一个黑色的图像imshow(BW).
您的第一个问题是您将索引图像(具有色彩图map)和RGB图像(不具有)混淆.trees.mat您在示例中加载的示例内置图像是索引图像,因此您应该使用该函数ind2gray首先将其转换为灰度强度图像.对于RGB图像,该功能rgb2gray也会这样做.
接下来,您需要确定用于将灰度图像转换为二进制图像的阈值.我建议使用该函数graythresh,它将计算插入im2bw(或更新imbinarize)的阈值.以下是我将如何完成您在示例中所做的事情:
load trees; % Load the image data
I = ind2gray(X, map); % Convert indexed to grayscale
level = graythresh(I); % Compute an appropriate threshold
BW = im2bw(I, level); % Convert grayscale to binary
Run Code Online (Sandbox Code Playgroud)
这是原始图像和结果的BW样子:


对于RGB图像输入,只需更换ind2gray与rgb2gray在上面的代码.
关于调整图像大小,可以使用图像处理工具箱功能轻松完成imresize,如下所示:
smallBW = imresize(BW, [10 10]); % Resize the image to 10-by-10 pixels
Run Code Online (Sandbox Code Playgroud)