2014-03-26 60 views
1

我有一个尺寸为260 x 260像素的图像。例如,我知道如何将其大小调整为140 x 140像素,然后将其转换为灰度。让我们假设下面的matlab代码:在特定情况下调整图像大小

image = imread('my_image.jpg'); 
image_resized = imresize(image, [140 140]); 
size(image_resized) % 140 x 140 x 3 
image_gray = rgb2gray(image_resized); 
size(image_gray) % 140 x 140 

我想要的是一个特定的情况。我有兴趣将图像标准化为高度为140像素其中宽度相应地进行了重新调整,以便保留图像宽高比。不幸的是,我不知道如何编辑我的上面的代码。

任何帮助将不胜感激。

回答

1

试试这个 -

image = imread('my_image.jpg'); 
desired_height = 140; 

%%// Width of the resized image keeping the aspect ratio same as before 
n2 = round((size(image,2)/size(image,1))*desired_height); 

%%// Resized image 
image_resized = imresize(image, [desired_height n2]); 

编辑1

注:或者您可以使用通过使用NaN的imresize规定的夏嘉曦的解决方案的建议太大小,但它ceils或四舍五入在大多数情况下你可能不需要的尺寸。

为了证明这种情况,我试着imresize将高度保持为173,我用手动调整大小获得了不同的尺寸,而不是当我让imresize决定尺寸。用于实验

%%// Resized image 
image_resized_with_auto_sizing = imresize(image, [desired_height NaN]); 
image_resized_with_manual_sizing = imresize(image, [desired_height n2]); 

大小输出用于我的实验

代码 -

>> whos image_resized_with_manual_sizing image_resized_with_auto_sizing 
    Name         Size    Bytes Class Attributes 

    image_resized_with_auto_sizing  173x185x3   96015 uint8    
    image_resized_with_manual_sizing  173x184x3   95496 uint8 

通告两种情况中的宽度的差值。这个问题也被讨论了here

+1

为什么不让'imresize'自己找出'n2'? – Shai

+0

@Shai查看编辑1,为什么在让'imresize'决定尺寸之前,可能会三思而后行。 – Divakar

+0

好的,在这种情况下,您的宽度等于184而不是185和95496字节,而不是96015.这是否与自动调整大小相比具有优势?所以你的方法更有效率? – Christina

2

您可以使用NaN所需的大小参数exacty指明要

image_resized = imresize(image, [140 NaN]); 

这基本上告诉Matlab的什么“不与图像的宽度打扰我! - 弄清楚自己”。

有关更多信息,请参阅imresize文档。

+0

我试过你的代码和Divakar的代码,我得到了同样的结果。这两个代码是否相似,但是你的代码很简单? – Christina

+0

@Christina查看我的编辑1,关于'imresize'的一些问题,决定自己的尺寸。 – Divakar

+2

@Christina如果你不太挑剔其他维度是如何计算的('round'ed或'ceil'ed ...)比我的答案是[Divakar](http:// stackoverflow。 com/a/22656560/1714410)提出。恕我直言,使用简化版本保持代码更清晰,更易于理解和维护。 – Shai

相关问题