I am having problems in Matlab, I do not understand. The following code snippet analyzes a collection of images and should return a coherent image (and always did).
But since I put an if condition in the second for-loop (for optimization purposes), it returns an interlaced image.
I do not understand why, and I am ready to throw my computer out of the window. I suspect this has something to ind2sub with ind2sub , but as far as I can see, everything works just fine! Does anyone know why this is being done?
function imageMedoid(imageList, resizeFolder, outputFolder, x, y) % local variables medoidImage = zeros([1, y*x, 3]); alphaImage = zeros([yx]); medoidContainer = zeros([y*x, length(imageList), 3]); % loop through all images in the resizeFolder for i=1:length(imageList) % get filename and load image and alpha channel fname = imageList(i).name; [container, ~, alpha] = imread([resizeFolder fname]); % convert alpha channel to zeros and ones, add to alphaImage alphaImage = alphaImage + (double(alpha) / 255); % add (r,g,b) values to medoidContainer and reshape to single line medoidContainer(:, i, :) = reshape(im2double(container), [y*x 3]); end % loop through every pixel for i=1:(y * x) % convert i to coordinates for alphaImage [xCoord, yCoord] = ind2sub([xy],i); if alphaImage(yCoord, xCoord) == 0 % write default value to medoidImage if alpha is zero medoidImage(1, i, 1:3) = 0; else % calculate distances between all values for current pixel distances = pdist(squeeze(medoidContainer(i,:,1:3))); % convert found distances to matrix of distances distanceMatrix = squareform(distances); % find index of image with the medoid value [~, j] = min(mean(distanceMatrix,2)); % write found medoid value to medoidImage medoidImage(1, i, 1:3) = medoidContainer(i, j, 1:3); end end % replace values larger than one (in alpha channel) by one alphaImage(alphaImage > 1) = 1; % reshape image to original proportions medoidImage = reshape(medoidImage, y, x, 3); % save medoid image imwrite(medoidImage, [outputFolder 'medoid_modified.png'], 'Alpha', alphaImage); end
I have not included all the code, just this function (for the sake of brevity), if someone needs more (for a better understanding), please let me know and I will enable it.