Skip to content

Instantly share code, notes, and snippets.

@MLLeKander
Last active August 29, 2015 14:13
Show Gist options
  • Save MLLeKander/b10b1f51c1884ef3d070 to your computer and use it in GitHub Desktop.
Save MLLeKander/b10b1f51c1884ef3d070 to your computer and use it in GitHub Desktop.
Autothresholding
char mean(char* img, int dim) {
int sum = 0;
for (int i = 0; i < dim; i++) {
sum += img[i];
}
return (char)(sum/(double)dim);
}
int autothresh_book(char* img, int dim) {
int hiCount, loCount, hiSum, loSum;
char T = mean(img, dim), oldT = 0;
do {
oldT = T;
hiCount = loCount = hiSum = loSum = 0;
for (int i = 0; i < dim; i++) {
if (img[i] > T) {
hiCount++;
hiSum += img[i];
} else {
loCount++;
loSum += img[i];
}
}
T = (char)((hiCount/(double)hiSum + loCount/(double)loSum)/2);
} while (oldT != T);
return T;
}
int gt_char(const void *a, const void *b) {
return *(char *)a - *(char *)b;
}
char autothresh_mine(char* img, int dim) {
char* sortedImg = malloc(dim * sizeof(char));
memcpy(sortedImg, img, dim * sizeof(char));
qsort(sortedImg, dim, sizeof(char), gt_char);
int* sums = malloc(dim * sizeof(int));
sums[0] = 0;
for (int i = 1; i < dim; i++) {
sums[i] = sums[i-1] + sortedImg[i];
}
int maxSum = sums[dim-1];
for (int i = 0; i < dim; i++) {
char T = sortedImg[i];
while (i+1 < dim && sortedImg[i+1] == T) {
i++;
}
if ((char)(sums[i]/((double)i+1) + (maxSum - sums[i])/(dim-(double)i)) == 2*T) {
return T;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment