* Note: * suffix B indicates subset of all graylevels before current gray level * suffix F indicates subset of all graylevels after current gray level */
| 29 | * suffix F indicates subset of all graylevels after current gray level |
| 30 | */ |
| 31 | array otsu(const array& in) { |
| 32 | array gray; |
| 33 | int channels = in.dims(2); |
| 34 | if (channels > 1) |
| 35 | gray = colorSpace(in, AF_GRAY, AF_RGB); |
| 36 | else |
| 37 | gray = in; |
| 38 | unsigned total = gray.elements(); |
| 39 | array hist = histogram(gray, 256, 0.0f, 255.0f); |
| 40 | array wts = range(256); |
| 41 | |
| 42 | array wtB = accum(hist); |
| 43 | array wtF = total - wtB; |
| 44 | array sumB = accum(wts * hist); |
| 45 | array meanB = sumB / wtB; |
| 46 | float lastElemInSumB; |
| 47 | sumB(seq(255, 255, 1)).host((void*)&lastElemInSumB); |
| 48 | array meanF = (lastElemInSumB - sumB) / wtF; |
| 49 | array mDiff = meanB - meanF; |
| 50 | |
| 51 | array interClsVar = wtB * wtF * mDiff * mDiff; |
| 52 | |
| 53 | float max = af::max<float>(interClsVar); |
| 54 | float threshold2 = where(interClsVar == max).scalar<unsigned>(); |
| 55 | array threshIdx = where(interClsVar >= max); |
| 56 | float threshold1 = |
| 57 | threshIdx.elements() > 0 ? threshIdx.scalar<unsigned>() : 0.0f; |
| 58 | |
| 59 | return threshold(gray, (threshold1 + threshold2) / 2.0f); |
| 60 | } |
| 61 | |
| 62 | int main(int argc, char** argv) { |
| 63 | try { |