function clean = thr(drawing, threshold)
%THR remove 8-connected segments smaller than the threshold
    labeled = bwlabel(drawing, 8);
    s = size(labeled);
    clean = zeros(s(1), s(2));
    segments = zeros(1, max(max(labeled)));
    for k = 1:max(max(labeled))
        segments(k) = sum(sum(labeled==k));
    end
    for i = 1:s(1)
        for j = 1:s(2)
            if labeled(i,j) > 0 && segments(labeled(i,j)) >= threshold
                clean(i,j) = 1;
            else
                clean(i,j) = 0;
            end
        end
    end
end

