MATLAB: Return the cropped image to the original image

croppingimage processing

|I have an image of eyes where the left and right eyes are located in the left portion and right portion of the image respectively so I cropped the image in half using: (I did this because I have to binarize left and right image differently)
I = imread('Eyes.jpg'); %Left and right eye image 1080x1920
I = rgb2gray(I);
n=fix(size(I,2)/2);
A=I(:,1:n,:); %Left Eye image 1080x960
B=I(:,n+1:end,:); %Right Eye image 1080x960
I cropped the A and B into smaller ones to get the pupil of both image, did some testing and found out arbitrarily values +221 -221 exacts the pupil x-y position for left eye and -960 (rxmx,rxmn) for x-pos in the right eye. But I am having problems with other eye images as it did not locate the pupil using the +221 and -221 values. Is there something wrong with my code?
r= 60;
th = 0:pi/50:2*pi;
Lxunit = r * cos(th) + Lcx; %(Lcx,Lcy) - left eye coordinates from ginput(1)
Lyunit = r * sin(th) + Lcy;
Lxmin = floor(min(Lxunit));
Lxmax = floor(max(Lxunit));
Lymin = floor(min(Lyunit));
Lymax = floor(max(Lyunit));
Rxunit = r * cos(th) + Rcx; %(Rcx,Rcy) - right eye coordinates from ginput(1)
Ryunit = r * sin(th) + Rcy;
Rxmin = floor(min(Rxunit));
Rxmax = floor(max(Rxunit));
Rymin = floor(min(Ryunit));
Rymax = floor(max(Ryunit));
myLeftCroppedImg = A(Lxmin+221:Lxmax+221,Lymin-221:Lymax-221,:); %CROP LEFT PUPIL
rxmn = Rxmin-960;
rxmx = Rxmax-960;
myRightCroppedImg = B(rxmn:rxmx,Rymin:Rymax,:); %CROP RIGHT PUPIL
Now I did some processing to my left and right cropped image and wanted to get it back to its original image variable "I" with the changes I made. What I did was:
[ii jj] = find( myLeftCroppedImg == 0 ); %FIND BLACK PIXELS
for kk=1:size(ii)
A(Lxmin+ ii(kk)+221,Lymin+jj(kk)-221) = myLeftCroppedImg(ii(kk),jj(kk));
end
[ii jj] = find(myRightCroppedImg == 0 );
for kk=1:size(ii)
B(Rxmin+ii(kk)-960,Rymin+jj(kk)) = myRightCroppedImg(ii(kk),jj(kk));
end
I=cat(2,A,B);
If it helps, I attached examples of different eye images.

Best Answer

Well first of all, you swapped a and y. Arrays are NOT* indexed as (x,y) - common beginner mistake - they are indexed as (y, x). Try getting rid of the for loops and just assign the whole array in a vectorized manner:
[rows, columns] = size(myLeftCroppedImg);
row1 = Lymin;
row2 = row1 + rows - 1;
col1 = Lxmin;
col2 = col1 + columns - 1;
A(row1:row2, col1:col2) = myLeftCroppedImg;
Same concept for myRightCroppedImg.