Reputation: 31
I want to obtain the pixel values for RGB from image.I did it in Matlab and Python but i obtained different values especially at the green value. I'll appreciate if you have an advice about 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)
Upvotes: 3
Views: 654
Reputation: 7905
It appears that the images are read in a different "direction" in Python compared to Matlab.
If you change your python code to:
ij = j , i
instead of
ij = i , j
you'll get the same output as in Matlab.
If you want Matlab to give the same results as Python, you'd have to flip 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);
Here's how I figured this out through simple debugging:
.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.
i
and j
in Python from ij = i, j
to ij = j, i
will reproduce the Matlab results.Upvotes: 3