Change language

Find Coordinates of Contours Using OpenCV | python

| | | | |

We will use findContour () OpenCV findContour () which helps to extract contours from an image.

Fit:
The coordinates of each vertex of the path are hidden in the path itself. In this approach, we will use the numpy library to convert all of the path coordinates to a linear array. This line array will contain the x and y coordinates of each path. The key point here is that the first coordinate in the array will always be the coordinate of the topmost vertex and therefore can help in determining the orientation of the image.

In the following code, we will use an image named & # 39; test. jpg & # 39; to find outlines and print the coordinates of the vertices on the image itself.

# Python code for finding coordinates
# outlines found in the image.

import numpy as np

import cv2

 
# Reading the image

font = cv2.FONT_HERSHEY_COMPLEX

img2 = cv2.imread ( ’test.jpg’ , cv2.IMREAD_COLOR)

 
# Read the same image in another
# variable and greyscale.

img = cv2.imread ( ’test.jpg’ , cv2.IMREAD_GRAYSCALE)

 
# Convert image to binary
# (black and white image only).

_, threshold = cv2.threshold (img, 110 , 255 , cv2.THRESH_BINARY)

  
Detect outlines in the image.

contours, _ = cv2.findContours ( threshold, cv2.RETR_TREE,

cv2.CHAIN_APPROX_SIMPLE)

 
# Going through all the paths found in the image.

for cnt in contours:

 

approx = cv2.approxPolyDP (cnt, 0.009 * cv2.arcLength (cnt, True ), True )

 

# draws the border of the contours.

cv2.drawContours (img2, [approx], 0 , ( 0 , 0 , 255 ), 5

 

# Used to align an array containing

# vertex coordinates.

n = approx.ravel () 

i = 0

 

for j in n:

  if (i % 2 = = 0 ):

x = n [i]

y = n [i + 1 ]

 

  # A string containing coordinates.

string = str (x) + "" + str (y) 

 

  if (i = = 0 ):

# top coordinate text.

cv2.puttext-method/">puttext-method/">putText (img2, "Arrow tip" , (x, y),

font, 0.5 , ( 255 , 0 , 0 )) 

else :

# text in remaining coordinates.

  cv2.puttext-method/">puttext-method/">putText (img2, string, (x, y), 

  font , 0.5 , ( 0 , 255 , 0 )) 

i = i + 1

 
# Display the final image .

cv2.imshow ( ’image2’ , img2) 

 
# Exit the window if a key is pressed on the keyboard "Q".

if cv2.waitKey ( 0 ) & amp;  0xFF = = ord ( ’q’ ): 

cv2.destroyAllWindows ()

Input image:

Output: