image - RGB图像转二值图像

标签 image matlab image-processing rgb

我想在 MATLAB 中加载 RGB 图像并将其转换为二值图像,我可以在其中选择二值图像有多少像素。例如,我将一个 300x300 的 png/jpg 图像加载到 MATLAB 中,我最终会得到一个可能为 10x10 像素的二值图像(像素只能是 #000 或 #FFF)。

这是我到目前为止尝试过的:

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)

(以上是我从网上搜索得到的一些内容。)

在执行 imshow(BW) 时,我最终得到了一张黑色图像。

最佳答案

你的第一个问题是你混淆了indexed images (有一个颜色图 map)和 RGB images (没有)。您在示例中加载的示例内置图像 trees.mat 是一个索引图像,因此您应该使用函数 ind2gray首先将其转换为 grayscale intensity image .对于 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

这是原始图像和结果 BW 的样子:

enter image description here

enter image description here

对于 RGB 图像输入,只需将上面代码中的 ind2gray 替换为 rgb2gray

关于调整图像大小,可以使用图像处理工具箱功能轻松完成 imresize ,像这样:

smallBW = imresize(BW, [10 10]);  % Resize the image to 10-by-10 pixels

关于image - RGB图像转二值图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12181620/

相关文章:

Spring Boot 镜像上传和服务

python - 手写文本的边框

图像转换库 : Word, PDF、Excel 到图像

关于 png 图像的 Android 内存不足

math - 在 MATLAB 中找到两个向量之间的交点

matlab - 有没有办法使 matlab 包可用于同一 .m 文件中可用的所有函数

html - 让 <li> 和 <img> 元素在调整大小时遵守纵横比

c++ - 在 opencv (imwrite) 上压缩图像。如何显式设置压缩因子?

Java:JAI 与 JIMI

matlab删除矩阵计算中的for循环