Skip to content

Instantly share code, notes, and snippets.

@InputBlackBoxOutput
Last active January 27, 2022 06:21
Show Gist options
  • Save InputBlackBoxOutput/72d37317b63060d5f7a6ecf87d4a3cfa to your computer and use it in GitHub Desktop.
Save InputBlackBoxOutput/72d37317b63060d5f7a6ecf87d4a3cfa to your computer and use it in GitHub Desktop.
Canny edge detector with threshold calculation using Otsu's method
import cv2
import numpy as np
def calculate_threshold(img):
hist, bin_edges = np.histogram(img, bins=256)
bin_mids = (bin_edges[:-1] + bin_edges[1:]) / 2.
weight1 = np.cumsum(hist)
weight2 = np.cumsum(hist[::-1])[::-1]
mean1 = np.cumsum(hist * bin_mids) / weight1
mean2 = (np.cumsum((hist * bin_mids)[::-1]) / weight2[::-1])[::-1]
inter_class_variance = weight1[:-1] * weight2[1:] * (mean1[:-1] - mean2[1:]) ** 2
index_of_max_val = np.argmax(inter_class_variance)
return bin_mids[:-1][index_of_max_val]
def detect_edges(img):
t = calculate_threshold(img)
lower = int(max(0, t * 0.5))
upper = int(min(255, t))
edges = cv2.Canny(img, lower, upper)
return edges
if __name__ == '__main__':
img = cv2.imread("fish.jpg", cv2.IMREAD_GRAYSCALE)
edges = 255 - detect_edges(img)
cv2.imshow("Edges", edges)
cv2.waitKey(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment