function generatePatchImages(outDir, params, allFeatures, ...
  assignedClust, centers, positivePatches, selectedClusters)
if ~exist(outDir, 'dir')
  mkdir(outDir);
end

canoSize = params.patchCanonicalSize;
clInd = selectedClusters;
parfor j = 1 : length(clInd)
  k = clInd(j);
  avgI = zeros(canoSize(1), canoSize(2), 1);
  clustKMem = find(assignedClust==k);
  nearN = getNearestN(allFeatures(clustKMem, :), centers(j, :), 300);
  cData = positivePatches(clustKMem);
  cData = cData(nearN);
  cDataInd = clustKMem(nearN);
  
  for i = 1 : length(cData)%length(cData(1:(min(300, length(cData)))))
    D = cData(i);
    I = im2double(imread(D.im));
    if D.flip
      I(:,:,1) = fliplr(I(:,:,1));
      I(:,:,2) = fliplr(I(:,:,2));
      I(:,:,3) = fliplr(I(:,:,3));
    end

    I = I(D.y1:D.y2, D.x1:D.x2, :);
    I1 = imresize_old(I, canoSize, 'bilinear');
    imwrite(I1, [outDir sprintf('%d_%d_%d.jpg', j, k, cDataInd(i))]);
    [IX, IY] = gradient(I);
    I = sum(abs(IX), 3) + sum(abs(IY), 3);
    I = imresize_old(I, canoSize, 'bilinear');
    avgI = avgI + I;
  end
  avgI = avgI / length(cData);
  imwrite(avgI, [outDir sprintf('%d_%d_00_avg.jpg', j, k)]);
  avgI = avgI ./ max(max(avgI));
  scImg = getScaledImage(avgI);
  imwrite(scImg, [outDir sprintf('%d_%d_%d_00_sc.jpg', j, k, ...
    length(cData))]);
end
disp('Done writing cluster images.');
end
