如何获取灰度图像中区域的像素值?

时间:2015-11-16 05:09:21

标签: matlab image-processing

我想将区域的像素值标记为红色矩形。我想在之后裁剪图像

enter image description here

1 个答案:

答案 0 :(得分:2)

以下代码将解决您的问题。但是可以有几个更好的解决方案。下次请不要问问题,而是展示你曾经尝试过的东西。

% 20151116
% crop image by area

clc; clear all;

img = imread('xgOFu.png');
subplot(1,5,1);
imshow(img);
xl1 = xlim;
title('Original');

imgr = img(:,:,1);
subplot(1,5,2);
imshow(imgr);
xlim(xl1);
title('Red channel');

imgb = im2bw(imgr,.9);
subplot(1,5,3);
imshow(imgb);
xlim(xl1);
title('Binary');

s  = regionprops(imgb);

c1 = s.BoundingBox(1);
c2 = s.BoundingBox(1)+s.BoundingBox(3)-1;
r1 = s.BoundingBox(2);
r2 = s.BoundingBox(2)+s.BoundingBox(4)-1;

subplot(1,5,4);
imgc = imgb(r1:r2,c1:c2,:);
imshow(imgc);
xlim(xl1);
title('Crop with border');

s2  = regionprops(imcomplement(imgc));

c3 = s2.BoundingBox(1)+c1;
c4 = s2.BoundingBox(1)+s2.BoundingBox(3)-1+c1;
r3 = s2.BoundingBox(2)+r1;
r4 = s2.BoundingBox(2)+s2.BoundingBox(4)-1+r1;

imgc2 = img(r3:r4,c3:c4,:);
subplot(1,5,5);
imshow(imgc2);
xlim(xl1);
title('Crop without border');

输出:

enter image description here

更新了没有regionprops的旧版本的答案。

% 20151116
% filter image by area 2

clc; clear all;

img = imread('xgOFu.png');
imgr = img(:,:,1);
imgb = im2bw(imgr,.9);

[r, c] = find(imgb(:,:,1)==1);
r1 = min(r);
r2 = max(r);
c1 = min(c);
c2 = max(c);
img2 = img(r1:r2,c1:c2,:);

img2r = img2(:,:,1);
img2b = im2bw(img2r,.9);

[r, c] = find(img2b(:,:)==0);
r1 = min(r);
r2 = max(r);
c1 = min(c);
c2 = max(c);
img3 = img2(r1:r2,c1:c2,:);
imshow(img3);