Checking whether a point is within a contour
In this recipe, we will discover a way of checking whether a point is inside of a contour, or if it belongs to the contour's border.
Getting ready
You need to have OpenCV 3.x installed, with Python API support.
How to do it...
- Import all of the necessary modules, open an image, and display it on the screen:
import cv2, random import numpy as np img = cv2.imread('bw.png', cv2.IMREAD_GRAYSCALE)
- Find the contours of the image and display them:
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawContours(color, contours, -1, (0,255,0), 3) cv2.imshow('contours', color) cv2.waitKey() cv2.destroyAllWindows()
- Define a callback function to handle a user click on the image. This function draws a small circle where the click has happened, and the color of the circle is determined by whether the click was inside or outside of the contour:
contour = contours[0] image_to_show...