我在matlab中遇到一些我不明白的问题。下面的代码分析了一组图像,并且应该返回一个连贯的图像(并且总是这样做)。
但是因为我在第二个for循环中放置了一个if条件(出于优化目的),它返回一个隔行扫描图像。
我不明白为什么,并准备把我的电脑扔出窗外。我怀疑它与ind2sub
有关,但据我所知,一切正常! 有谁知道为什么会这样做?
function imageMedoid(imageList, resizeFolder, outputFolder, x, y)
% local variables
medoidImage = zeros([1, y*x, 3]);
alphaImage = zeros([y x]);
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([x y],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
我没有包含整个代码,只是这个功能(为了简洁起见),如果有人需要更多(为了更好地理解它),请告诉我,我会包含它。
答案 0 :(得分:0)
当您致电ind2sub
时,您会给出[x y]
的尺寸,但alphaImage
的实际尺寸为[y x]
,因此您没有使用{{1为正确的位置编制索引}和xCoord
。