Search code examples
imagematlabroi

Get center pixels of image in matlab


I want to extract a rectangular region of size (p*hight,p*width,3) of an image. p is a double value between [0,1].

The follwoing code works but I would like to know if there is a better way to achieve this?

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,:);

Are there any matlab commands to get the same result? Maybe by specifying just the size of the rectangle and the image center?


Solution

  • If you have the Image Processing toolbox, you could use the imcrop function and some math:

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

    EDIT: Or you could do it like this:

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