在读取RGB像素值时,Matlab和Python中的绿色值不同。

3

我希望可以从图像中获取RGB的像素值。我用Matlab和Python做了这件事,但是我得到了不同的值,特别是绿色值。 如果您对此事有建议,我将不胜感激。 以下是我的Python代码:

from PIL import Image
import numpy as np

im = Image.open("lena.jpg")
imPixelVal = np.ones(np.size(im))
imSize = np.size(im)

for i in range (0,imSize[0]):
            for j in range (0,imSize[1]):         
                ij = i , j
                p = im.getpixel(ij)
                imPixelVal[i,j] = (0.2989 * p[0]) + (0.5870 * p[1]) + (0.1140 * p[2])
                print p[0]
                print p[1] 
                print p[2]

这是Matlab的代码:

Im=imread('lena.jpg');
Img = (ones(size(Im,1),size(Im,2))); 

for i=1:size(Im,1)
      for j=1:size(Im,2)
          Img(i,j)=0.2989*Im(i,j,1)+0.5870*Im(i,j,2)+0.1140*Im(i,j,3);
      end
end
Im(1,1,1)
Im(1,1,2)
Im(1,1,3)

3
您能提供一个 MCVE,并且给出数据差异的例子吗?请注意,翻译过程中尽量保持原意,同时让内容更加通俗易懂。 - Ffisegydd
了解你的图像使用哪种数据格式可能会很有趣。 - OBu
请具体说明您使用了哪些代码以及它们之间的区别。 - Joop
我编辑并添加了Python和Matlab的代码。 - lisa
由于JPEG是一种有损格式,不同的读取器在解码值舍入方式上可能会相差+/-1,因此很容易出现偏差。尽管如此,Schorsch的答案可能是正确的。 - Mark Ransom
@Mark 很有趣的信息。然而,我检查了这种情况,所有值在Python和Matlab之间都是相同的。 - Schorsch
1个回答

3
似乎 Python 中读取图像的“方向”与 Matlab 不同。如果你将 Python 代码更改为:
ij = j , i

代替
ij = i , j

如果你想让Matlab输出与Python相同的结果,你需要将ij翻转:


这样做后,你将获得与Matlab相同的输出。

Img(j,i)=0.2989*Im(j,i,1)+0.5870*Im(j,i,2)+0.1140*Im(j,i,3);

以下是我通过简单的调试方法找出问题的过程:

  • First, I got the image from here and saved it as .jpg.
  • Then, I changed the Matlab loops to

    for i=1:2
        for j=1:2
    

    So that I would only get the first 4 pixels.

  • By printing both i, j and the contents of Im I got:

    i = 1, j = 1
    225, 137, 125
    
    i = 1, j = 2
    227, 139, 127
    
    i = 2, j = 1
    224, 136, 124
    
    i = 2, j = 2
    226, 138, 126  
    
  • Now, I did the same in python:

    for i in range (0,2):
        for j in range (0,2):
    
  • This gave me:

    (0, 0)
    225 137 125
    (0, 1)
    224 136 124
    (1, 0)
    227 139 127
    (1, 1)
    226 138 126
    
  • This showed me that the order is different between Matlab and Python.

  • Hence, changing i and j in Python from ij = i, j to ij = j, i will reproduce the Matlab results.

@Lisa - 请考虑接受此答案,或者如果它对您没有起作用,请留下评论。 - Schorsch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接