How can I extract array elements from cv2.findcontours

Viewed 35

I am trying to use cv2.findcontours and python3 to get the endpoints of a line. My image file is 1000X600 and contains only one line at about a 15 degree angle. This is the array I get from my code. total number of contouers found : 2 [array([[[865, 314]],

   [[864, 315]],

   [[863, 315]],

   ...,

   [[868, 314]],

   [[867, 314]],

   [[866, 314]]], dtype=int32)]

The endpoints of my line are aprox are: X0,Y0 = 71, 317 and X1,Y1 = 967,310

The image I used is a test to generate a single set of cordinates from cv2.findcountours.

I want to use the endpoints to calculate slope so that I can deskew old tabulated documents prior to OCR.

Below is my code.

import cv2
import numpy as np

#
#
# load raw image
#

imagefile = "1-line.png"
#
# load raw image
#
image = cv2.imread(imagefile)
# get the image size
#
h, w, c = image.shape
print('width:  ', w)
print('height: ', h)
print('channel:', c)


result = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
#
# Detect horizontal lines
#
# Default settinga are 40, 1
#
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (50,1))
detect_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

#
# Original parameters, don't remove
#
cnts = cv2.findContours(detect_horizontal, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
#
# Added temporay code
#
print ("total number of contouers found : ", str(len(cnts)))
#print ("Contours 0 is : ", cnts[0])
#print ("Contours 1 is : ", cnts[1])
#print ("Contours 1 is : ", cnts[2])

# end of added code


cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(result, [c], -1, (255,255,122), 5)
    print ([c])

cv2.imshow('result', result)
cv2.waitKey()

What I don't understand is the array structure of the contours returned.

As a newbie to cv2 and python I need all the help I can get.

Thanks

0 Answers
Related