Advertisement
Guest User

Untitled

a guest
Dec 17th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. def otsu(source_image):
  2.  
  3. total_pixel_count = source_image.shape[0] * source_image.shape[1]
  4.  
  5. # build histogram: brightness -> count
  6. gray_histogram = dict()
  7. for i in range(source_image.shape[0]):
  8. for j in range(source_image.shape[1]):
  9. current_pixel_value = source_image[i, j]
  10. gray_histogram[current_pixel_value] = gray_histogram.get(current_pixel_value, 0) + 1
  11.  
  12. total_weighted_sum = sum([brightness * count for brightness, count in gray_histogram.items()])
  13.  
  14. # -1 for monochromatic images
  15. best_threshold = -1
  16. max_criterion_value = 0
  17.  
  18. left_weighted_sum = 0
  19. left_pixel_count = 0
  20.  
  21. for current_threshold, count in list(gray_histogram.items())[:-1]:
  22. left_weighted_sum += current_threshold * count
  23. left_pixel_count += count
  24.  
  25. right_pixel_count = total_pixel_count - left_pixel_count
  26.  
  27. left_mean = left_weighted_sum / left_pixel_count
  28. right_mean = (total_weighted_sum - left_weighted_sum) / right_pixel_count
  29.  
  30. current_criterion_value = left_pixel_count * right_pixel_count * (left_mean - right_mean) ** 2
  31.  
  32. if current_criterion_value > max_criterion_value:
  33. max_criterion_value = current_criterion_value
  34. best_threshold = current_threshold
  35.  
  36. destination_image = None
  37.  
  38. if best_threshold != -1:
  39. destination_image = np.zeros(source_image.shape, source_image.dtype)
  40. for i in range(destination_image.shape[0]):
  41. for j in range(destination_image.shape[1]):
  42. if source_image[i, j] > best_threshold:
  43. destination_image[i, j] = np.iinfo(source_image.dtype).max
  44. else:
  45. destination_image = source_image
  46.  
  47. return best_threshold, destination_image
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement