[Numpy-discussion] Syntax trouble in translating matlab code to numpy

Oliver Siemoneit oliver.siemoneit@web...
Thu Apr 12 13:53:00 CDT 2007

```Dear numpy experts!

I'm just trying to port some matlab algorithm to python which allows an
image correction for color blind users. If I succeed this bit of code might
be part of the MoinMoin wiki, the wikisoftware scipy.org uses (see for more
on that http://moinmoin.wikiwikiweb.de/AccessibleMoin). Since I'm totally
new to matlab and numpy it took me already hours to figure the basics out -
without much success. So I decided to ask here on the mailing list for some
help. I hope - as an exception - this is ok for you...

Here's the part of the matlab code which should be translated. The last 5
lines actually cause the trouble (long version, see
http://www.stanford.edu/~ofidaner/psych221_proj/colorblindness_project.htm):
clear;
file_name = 'grandparents' ;
% transorm matrices
rgb2lms = [17.8824 43.5161 4.11935; 3.45565 27.1554 3.86714; 0.0299566
0.184309 1.46709] ;
lms2rgb = inv(rgb2lms) ;

sizeRGB = size(RGB) ;

%transform to LMS space
for i = 1:sizeRGB(1)
for j = 1:sizeRGB(2)
rgb = RGB(i,j,:);
rgb = rgb(:);
LMS(i,j,:) = rgb2lms * rgb;
end
end

And that's what I did with numpy and PIL in Python. The last 2 lines seems
to be wrong. But how to do it correct?

im = Image.open(fpath) # fpath is the path to the image
RGB = numpy.asarray(im) # checked: RGB is of shape[y,x,r/g/b]
# Colorspace transformation matrices
rgb2lms =
numpy.array([[17.8824,43.5161,4.11935],[3.45565,27.1554,3.86714],[0.0299566,0.184309,1.46709]])
lms2rgb = numpy.linalg.inv(rgb2lms)

# Transform to LMS space
LMS = numpy.zeros_like(RGB)
for i in range(RGB.shape[0]):
for j in range(RGB.shape[1]):
rgb = RGB[i,j,:2]
LMS[i,j,:2] = numpy.dot(rgb2lms, rgb)

This code fails in the last line with the error message "ValueError:
matrices are not aligned". But how to align them?

Any help would be highly appreciated. Many thanks in advance!

With regards,
Oliver Siemoneit

```