2016-04-09 66 views
2

我有以下圖像,我想在中間分割矩形對象。我實現了以下代碼來分割,但我無法隔離該對象。我可以採用哪些功能或方法來隔離圖像中的矩形對象?最好的方法來隔離矩形對象

im = imread('image.jpg'); 

% convert image to grayscale, 
imHSV = rgb2hsv(im); 
imGray = rgb2gray(im); 
imSat = imHSV(:,:,2); 
imHue = imHSV(:,:,1); 
imVal = imHSV(:,:,3); 

background = imopen(im,strel('disk',15)); 

I2 = im - background; 

% detect edge using sobel algorithm 
[~, threshold] = edge(imGray, 'sobel'); 
fudgeFactor = .5; 
imEdge = edge(imGray,'sobel', threshold * fudgeFactor); 
%figure, imshow(imEdge); 

% split image into colour channels 
redIM = im(:,:,1); 
greenIM = im(:,:,2); 
blueIM = im(:,:,3); 

% convert image to binary image (using thresholding) 
imBlobs = and((imSat < 0.6),(imHue < 0.6)); 
imBlobs = and(imBlobs, ((redIM + greenIM + blueIM) > 150)); 
imBlobs = imfill(~imBlobs,4); 
imBlobs = bwareaopen(imBlobs,50); 

figure,imshow(imBlobs); 

enter image description here enter image description here

回答

4

在這個例子中,你可以利用該矩形包含在其所有角落的藍色,以建立一個良好的初始遮蔽的事實。

  1. 使用閾值來定位圖像中的藍色位置並創建初始遮罩。
  2. 給定此初始掩碼,使用最小和最大操作查找其角點。
  3. 用角線連接角落以獲得矩形。
  4. 使用imfill填充矩形。

代碼例如:

% convert image to binary image (using thresholding) 
redIM = im(:,:,1); 
greenIM = im(:,:,2); 
blueIM = im(:,:,3); 
mask = blueIM > redIM*2 & blueIM > greenIM*2; 
%noise cleaning 
mask = imopen(mask,strel('disk',3)); 

%find the corners of the rectangle 
[Y, X] = ind2sub(size(mask),find(mask)); 
minYCoords = find(Y==min(Y)); 
maxYCoords = find(Y==max(Y)); 
minXCoords = find(X==min(X)); 
maxXCoords = find(X==max(X)); 
%top corners 
topRightInd = find(X(minYCoords)==max(X(minYCoords)),1,'last'); 
topLeftInd = find(Y(minXCoords)==min(Y(minXCoords)),1,'last'); 
p1 = [Y(minYCoords(topRightInd)) X((minYCoords(topRightInd)))]; 
p2 = [Y(minXCoords(topLeftInd)) X((minXCoords(topLeftInd)))]; 
%bottom corners 
bottomRightInd = find(Y(maxXCoords)==max(Y(maxXCoords)),1,'last'); 
bottomLeftInd = find(X(minYCoords)==min(X(minYCoords)),1,'last'); 
p3 = [Y(maxXCoords(bottomRightInd)) X((maxXCoords(bottomRightInd)))]; 
p4 = [Y(maxYCoords(bottomLeftInd)) X((maxYCoords(bottomLeftInd)))]; 

%connect between the corners with lines 
l1Inds = drawline(p1,p2,size(mask)); 
l2Inds = drawline(p3,p4,size(mask)); 
maskOut = mask; 
maskOut([l1Inds,l2Inds]) = 1; 

%fill the rectangle which was created 
midP = ceil((p1+p2+p3+p4)./4); 
maskOut = imfill(maskOut,midP); 

%present the final result 
figure,imshow(maskOut); 

最終結果: final result

中間結果(1-後閾服用,2-之後加入行): enter image description here

* DrawLine的功能取自drawline webpage