Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def otsu(source_image):
- total_pixel_count = source_image.shape[0] * source_image.shape[1]
- # build histogram: brightness -> count
- gray_histogram = dict()
- for i in range(source_image.shape[0]):
- for j in range(source_image.shape[1]):
- current_pixel_value = source_image[i, j]
- gray_histogram[current_pixel_value] = gray_histogram.get(current_pixel_value, 0) + 1
- total_weighted_sum = sum([brightness * count for brightness, count in gray_histogram.items()])
- # -1 for monochromatic images
- best_threshold = -1
- max_criterion_value = 0
- left_weighted_sum = 0
- left_pixel_count = 0
- for current_threshold, count in list(gray_histogram.items())[:-1]:
- left_weighted_sum += current_threshold * count
- left_pixel_count += count
- right_pixel_count = total_pixel_count - left_pixel_count
- left_mean = left_weighted_sum / left_pixel_count
- right_mean = (total_weighted_sum - left_weighted_sum) / right_pixel_count
- current_criterion_value = left_pixel_count * right_pixel_count * (left_mean - right_mean) ** 2
- if current_criterion_value > max_criterion_value:
- max_criterion_value = current_criterion_value
- best_threshold = current_threshold
- destination_image = None
- if best_threshold != -1:
- destination_image = np.zeros(source_image.shape, source_image.dtype)
- for i in range(destination_image.shape[0]):
- for j in range(destination_image.shape[1]):
- if source_image[i, j] > best_threshold:
- destination_image[i, j] = np.iinfo(source_image.dtype).max
- else:
- destination_image = source_image
- return best_threshold, destination_image
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement