这应该适用于比框架更小、相等和更大的灰度和彩色图像。试图保持它的可读性。
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);