用MATLAB将灰度图片通过循环判定使其二值化的简要代码
时间: 2024-10-07 10:08:09 浏览: 54
在MATLAB中,可以使用阈值处理方法来将灰度图像二值化。下面是一个简单的示例,它通过循环遍历每个像素,并将其转换为0(黑色)或255(白色),如果像素值高于某个预设阈值:
```matlab
% 加载灰度图像
img = imread('your_grayscale_image.jpg'); % 替换为你实际的图像文件名
% 定义阈值(可以根据需要调整)
threshold = 128; % 对于这个例子,我们选择半灰作为分界线
% 创建全零矩阵,用于存储二值图像
binary_img = zeros(size(img));
% 循环遍历每个像素
for i = 1:size(img, 1)
for j = 1:size(img, 2)
% 判断像素值是否大于阈值,如果是则设置为255,否则为0
binary_img(i,j) = img(i,j) > threshold ? 255 : 0;
end
end
% 显示原图和二值化后的结果
subplot(1,2,1), imshow(uint8(img)), title('Original Gray Image');
subplot(1,2,2), imshow(binary_img), title('Binary Image');
% 存储二值化后的图像
imwrite(binary_img, 'binary_output.jpg', 'JPEG'); % 可选步骤:保存二值化结果
阅读全文
相关推荐

















