【问题标题】:Automatically align image and graph with shared x-axis自动将图像和图形与共享 x 轴对齐
【发布时间】:2017-05-03 20:30:04
【问题描述】:

我有一张图像,我想在图表下绘制该图像的任意行的强度。

显然,我无法“自动”使这两个图既对齐(它们共享相同的 x 轴)又不失真

这是一个使用 MATLAB 附带的 kobi.png 图像的 MWE。对于这个解决方案,我使用了this question 的答案,但这并不是我想要的。原因在代码之后就会清楚。

im = imread('kobi.png'); % read default image
img = rgb2gray(im); % convert to grayscale

y = 600; % select line to "scan"

% plot image with highlithed line
subplot(3,3,4:9);
imagesc(img);
colormap gray
hold on
line([0 size(img,2)], [y y], 'Color', 'r', 'LineWidth', 1.5);
hold off
axis image

photoAxs = gca;
photoAxsRatio = get(photoAxs,'PlotBoxAspectRatio');

% plot intensity of selected row
subplot(3,3,1:3);
r = img(y, :);
plot(r);
axis tight

topAxs = gca;

% adjust ratios
topAxsRatio = photoAxsRatio;
topAxsRatio(2) = photoAxsRatio(2)/2.4; % I want to get rid of this number!  
set(topAxs,'PlotBoxAspectRatio', topAxsRatio)

如您所见,这产生了(几乎)预期结果,但有一个硬​​编码的数字(我链接的答案不同,3.8,而这里是2.4),我想排除。另外,我认为这个数字只提供了一个显然对齐的解决方案,但是对于我轻微的强迫症,这个错误空间让我毛骨悚然!

所以问题是:

是否有任何可行的方法来自动对齐具有相同 x 轴的图形和图像,同时保持图像纵横比

【问题讨论】:

    标签: matlab matlab-figure


    【解决方案1】:

    旧代码:

    topAxsRatio = photoAxsRatio;
    topAxsRatio(2) = photoAxsRatio(2)/2.4; % I want to get rid of this number!  
    set(topAxs,'PlotBoxAspectRatio', topAxsRatio)
    

    新代码:

    photoratio = photoAxs.PlotBoxAspectRatio(1)/photoAxs.PlotBoxAspectRatio(2);
    ratio = photoratio * photoAxs.Position(4)/topAxs.Position(4);
    topAxs.PlotBoxAspectRatio = [ratio, 1, 1];
    

    结果:


    一点解释:

    当第一次绘制图形时,您会注意到只有高度不同,尽管您可以清楚地看到宽度也不同。

    我不是 100% 确定 Matlab 这样做的原因,但这是我的猜测。

    通常,宽度和高度两个属性足以定义 2D 图形的大小,但 Matlab 引入了一个额外的属性 PlotBoxAspectRatio 来控制大小。为了避免冲突,Matlab 决定在第一次创建图形时给宽度属性一个固定的数字。但是实际宽度是由height*PlotBoxAspectRatio计算的。

    因此,我们有:

    TopAxis.width = TopAxis.height * TopAxis.ratio 
    Photo.width = Photo.height * Photo.ratio
    

    为了保留TopAxis的初始高度,我们只能改变纵横比。

    TopAxis.width = Photo.width
    

    我们有

    TopAxis.height * TopAxis.ratio = Photo.height * Photo.ratio
    TopAixs.ratio = Photo.ratio * Photo.height / TopAxis.height
    

    Matlab 代码等价物是新提出的代码。

    【讨论】:

    • 谢谢!您的解释非常好,它解释了 2.4(实际上是正确的)。是两个人的身高之比,不是吗? :)
    • @UJIN 确实,我没有意识到:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2019-05-01
    • 2017-12-07
    • 2019-09-03
    相关资源
    最近更新 更多