【问题标题】:How to generate the same image with the function of imshow() from matplotlib(python) and imshow() in matlab?matlab中matplotlib(python)和imshow()的imshow()函数如何生成相同的图像?
【发布时间】:2016-07-23 22:10:16
【问题描述】:

对于同一个矩阵,matplotlib和matlab中函数imshow()生成的图像是不同的。如何在matplotlib中改变imshow()的一些参数在matlab中可以得到相同的结果

%matlab
img = 255*rand(101);
img(:,1:50)=3;
img(:,52:101)=1;
img(:,51)=2;
trans_img=imtranslate(img,[3*cos(pi/3),3*sin(pi/3)]);
imshow(trans_img)

This is an image generated by matlab

#python
import numpy as np
import matplotlib.pyplot as plt
from mlab.releases import latest_release as mtl #call matlab function

img = 255 * np.random.uniform(0, 1, (101, 101))
img[:, 51:101] = 1 
img[:, 0:50] = 3
img[:, 50] = 2
trans_img = mtl.imtranslate(img, [[3*math.cos(math.pi/3),3*math.sin(math.pi/3)]] 
i = plt.imshow(trans_img, cmap=plt.cm.gray)
plt.show(i)

This is an image generated by matplotlib

两种情况下的trans_img矩阵是一样的,但是matlab和python中的图片不一样

【问题讨论】:

  • 您需要更具体地了解您正在生成的图像以及两个版本之间的确切差异。
  • 抱歉,我已经更新了我的代码的一些细节以使这个问题更具体。

标签: python matlab matplotlib


【解决方案1】:

不幸的是,我没有足够最新的具有imtranslate 函数的Matlab 版本,但幸运的是Octave 中的image 包可以,我确信它是等效的。同样,我将使用oct2py 模块而不是mlab 作为结果,以便python 从python 中的八度访问imtranslate 函数。

八度码:

img = 255*rand(101);
img(:,1:50)=3;
img(:,52:101)=1;
img(:,51)=2;
trans_img = imtranslate(img, 3*cos(pi/3),3*sin(pi/3));
imshow(trans_img, [min(trans_img(:)), max(trans_img(:))])

Python 代码:

import numpy as np
import matplotlib.pyplot as plt
import math
from oct2py import octave
octave.pkg('load','image');  # load image pkg for access to 'imtranslate'
img = 255 * np.random.uniform(0, 1, (101, 101))
img[:, 51:101] = 1 
img[:, 0:50] = 3
img[:, 50] = 2
trans_img = octave.imtranslate(img, 3*math.cos(math.pi/3), 3*math.sin(math.pi/3))
i = plt.imshow(trans_img, cmap=plt.cm.gray)
plt.show(i)

两种情况下的结果图像(相同):

我对您可能看到差异的唯一评论是,我确实imshow 中指定了 minmax 值,以确保适当的强度缩放。同样,您也可以改用imagesc(trans_img)(我实际上更喜欢这个)。我没有在 python 中为plt.imshow 明确指定这样的限制......也许它默认执行缩放。

另外,您的代码有一个小错误;至少在imtranslate 的八度版本中,该函数接受3 个参数,而不是两个。 (另外,您的原始代码有一个不平衡的括号)。

【讨论】:

  • 感谢您的回答。我已经更新了这个问题的一些代码。唯一让我困惑的是 matlab 和 python 的 imshow() 对同一矩阵给出不同的图像结果。
  • 根据更新的问题更新了答案。 :) 另外,请原谅我的粗鲁,但是,为了哄骗“真正的”问题,我必须先用一个过于简单的“诱饵”答案来回答,这对所有相关人员来说都是浪费时间。请尽力提出适当的具体问题,例如下次从头开始的更新版本:)
  • 感谢您的回答。我仍然有一个问题,因为我只想在matplotlib中更改imshow()的一些参数,以在Matlab中使用imshow(trans_img)实现相同的结果。不需要像代码一样更改任何参数:imshow(trans_img,[最小值(trans_img(:)),最大值(trans_img(:))])。真的很抱歉我用手机发表评论,不方便将代码设置为适当的格式
  • 我在上面说的是imshow(trans_img) % in matlab 显示了错误 结果,因为它没有考虑缩放。你是在问我如何使用 matplotlib 复制 wrong 结果?
  • 实际上,即使我在matlab和python中都去掉了代码函数imtranslate()这行,在matlab和python中只去掉了imshow(img),它仍然不是同一个图像。
猜你喜欢
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 2019-01-22
  • 2022-08-16
相关资源
最近更新 更多