如何使用matlab中的matplotlib(python)和imshow()中的imshow()函数生成相同的图像?

时间:2016-07-23 22:10:16

标签: python matlab matplotlib

对于相同的矩阵,由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中的图像是不同的

1 个答案:

答案 0 :(得分:0)

不幸的是,我没有具有imtranslate功能的最新版本的Matlab,但幸运的是,Octave中的image软件包确实存在,我还是肯定是等价的。同样,我将使用oct2py模块而不是mlab,因为python可以在python中从octave访问imtranslate函数。

Octave代码:

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)

两种情况下产生的图像(相同):

enter image description here

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

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