我有一个图像,我想在图表下绘制该图像,显示该图像的任意行的强度。
显然,我无法“自动”使两个图表对齐(它们共享相同的 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 轴的图形和图像,同时保持图像纵横比?
最佳答案
旧代码:
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 代码等效项是提议的新代码。
关于matlab - 自动将图像和图表与共享 x 轴对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43769448/