matlab - Center crop or pad an image within a frame -


my question problem easy solve, interested in learning best practice this. (nominally matlab, not language-specific ).

i loading image of arbitrary size, , need make fit (without scaling nor change of aspect ratio) within black image of predefined size (let's call frame). loaded image can smaller, equal or bigger predefined frame, in either or both dimension(s).

if image smaller frame, want padded zeros (there black border around it), frame size, , centered. if bigger, want crop in centered fashion.

ideally, not want make assumptions on parity of pixel numbers in either dimension - is, both loaded image , frame can have odd or pixel numbers both dimensions. surely there rounding do.

i'm sure problem has been researched, solved , exhausted, shouldn't hard question knowledgeable programmers experience in image processing :)

this should work both greyscale , color images of smaller, equal , larger size frame. tried keep sort of readable.

framewidth = 800; frameheight = 600; imagepath = 'smaller.jpg'; % 'equal.jpg', 'larger.jpg'  img = im2double(imread(imagepath)); [imgheight, imgwidth, channels] = size(img); frame = zeros(frameheight, framewidth, channels);  dimagewidth = round((framewidth - imgwidth)/2); dimageheight = round((frameheight - imgheight)/2);  unequalheight = (imgheight ~= frameheight); unequalwidth = (imgwidth ~= framewidth);  if imgheight <= frameheight     framevstart = max(1, dimageheight);     framevend = min(frameheight, frameheight-dimageheight-unequalheight);     imgvstart = 1;     imgvend = imgheight; else     framevstart = 1;     framevend = frameheight;      imgvstart = max(1, -dimageheight);     imgvend = min(imgheight, imgheight+dimageheight); end  if imgwidth <= framewidth     framehstart = max(1, dimagewidth);     framehend = min(framewidth, framewidth-dimagewidth-unequalwidth);     imghstart = 1;     imghend = imgwidth; else     framehstart = 1;     framehend = framewidth;      imghstart = max(1, -dimagewidth);     imghend = min(imgwidth, imgwidth+dimagewidth); end  frame(framevstart:framevend, framehstart:framehend, :) = ...     img(imgvstart:imgvend, imghstart:imghend, :);  imshow(frame); 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -