When reading an image for RGB pixel values โโthere is a different green value in matlab and python
I want to get pixel values โโfor RGB from image. I did it in Matlab and Python, but I got different values, especially on the green value. I would be grateful if you have any advice on this matter. thanks Here is my code in 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]
Also this is the code in 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)
It looks like images are read in a different "direction" in Python compared to Matlab.
If you change your python code to:
ij = j , i
instead
ij = i , j
you will get the same result as in Matlab.
If you want to Matlab gave the same results as the Python, you'll have to turn i
and j
there:
Img(j,i)=0.2989*Im(j,i,1)+0.5870*Im(j,i,2)+0.1140*Im(j,i,3);
This is how I figured it out through simple debugging:
- I first got the image here and saved it as
.jpg
. -
Then I changed the Matlab loops to
for i=1:2 for j=1:2
So, I would get the first 4 pixels.
-
Print to
i
,j
and the contentsIm
, 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 have done 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 from Matlab and Python.
- Hence, changing
i
andj
in Python fromij = i, j
toij = j, i
will reproduce the Matlab results.