I am attempting to implement hysteresis in OpenCV. I am almost there but I am unsure how I can join my lower and upper threshold images together. Can you suggest how I can achieve this? I'll explain my understanding of hysteresis below, can you let me know if this is correct.
Hysteresis is where we supply an upper and lower threshold value. We threshold an image with the lower threshold, ie, we say give me all pixels whose value is LOWER_THRESH or above. We get alot of edges plus alot of noise/non-edges - this image contains our certain AND probable edges. We then threshold an image with a higher threshold, ie, we say give me all pixels whose value is HIGHER_THRESH or above. The resultant image contains our certain edges only. If a certain edge touches a probable edge then we keep that probable edge, if not we throw away that probable edge because its probable noise. Is this correct?
How can I keep all white pixels in upper_thresh that touch white pixels in lower thresh?
import cv2
import numpy as np
LOWER_THRESH = 49
UPPER_THRESH = 100
def main():
src = cv2.imread('../images/rect_hysteresis.png', cv2.IMREAD_GRAYSCALE)
const_width = 300
aspect = float(src.shape[0]) / float(src.shape[1])
src = cv2.resize(src, (const_width, int(const_width * aspect)))
_, lower_thresh = cv2.threshold(src, LOWER_THRESH, 255, cv2.THRESH_BINARY)
_, upper_thresh = cv2.threshold(src, UPPER_THRESH, 255, cv2.THRESH_BINARY)
# lower_thresh = cv2.inRange(src, (50,), (255,))
# upper_thresh = cv2.inRange(src, (150,), (255,))
# dilate the upper_thresh so we have collisions with lower thresh
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
upper_thresh = cv2.dilate(upper_thresh, kernel)
# How can I keep all white pixels in upper_thresh that touch white pixels in lower thresh
hysteresis = cv2.bitwise_and(upper_thresh, lower_thresh)
cv2.imshow('src', src)
cv2.imshow('lower_thresh', lower_thresh)
cv2.imshow('upper_thresh', upper_thresh)
cv2.imshow('hysteresis', hysteresis)
cv2.waitKey(0)
if __name__ == "__main__":
main()