2015-05-24 32 views
1

我想提取圖像的大小爲(p*hight,p*width,3)的矩形區域。 p是[0,1]之間的雙倍值。獲取matlab中圖像的中心像素

follwoing代碼的作品,但我想知道是否有更好的方法來實現這一目標?

img = imread(ImageName); 

% size parameter 
p = 0.5; 

% store image size 
hight = size(img,1); 
width = size(img,2); 

% calculate the center of the image both in width and hight 
% used as reference 
centerHight = floor(hight/2); 
centerWidth = floor(width/2); 

% use half of the actual size of the rectangular region 
halfHight = floor(p*hight/2); 
halfWidth = floor(p*width/2); 

% start index for hight and width 
startHight = 1 + centerHight - halfHight; 
startWidth = 1 + centerWidth - halfWidth; 

% end index for hight and width 
endHight = centerHight + halfHight; 
endWidth = centerWidth + halfWidth; 

% extract center pixels 
CenterPixels = img(startHight:endHight,startWidth:endWidth,:); 

是否有任何matlab命令獲得相同的結果?也許只需指定矩形和圖像中心的大小?

+0

出於好奇,什麼是您提供的內容有誤?即使Matlab確實有一個內置函數來執行你想要的功能,但它可能並沒有太大的不同。 –

+0

沒什麼。但對我來說,這似乎是一個「簡單」任務的很多代碼。只是想知道是否有可能用較少的代碼行來完成這個任務。 – evolved

回答

4

如果你有Image Processing toolbox,您可以使用imcrop功能和一些數學:

[nl, nc, ~] = size(img); 
CenterPixels = imcrop(img, [[nc nl] * (1 - p)/2 [nc nl] * p]); 

編輯:或者你可以做這樣的:

[nl, nc, ~] = size(img); 
CenterPixels = img(nl*(1-p)/2:nl*(1+p)/2, nc*(1-p)/2:nc*(1+p)/2, :);