Search code examples
pythonpython-3.xopencvcontour

Get contours and points of an image


I have my code like this:

import numpy as np
import cv2
im = cv2.imread('snorlax.jpg')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
cv2.drawContours(im, contours, -1, (0, 255, 0), 3)
cv2.imshow("imagen", im)
input()

The print show a list of lists that have to number every list I dont know if that are the points (x,y) of the contours and the cv2.show only showme a grey screen and doesn't show me the contours of the image.


Solution

  • import numpy as np
    import cv2
    
    img = cv2.imread("snorlax.jpg", cv2.IMREAD_GRAYSCALE)
    
    canny = cv2.Canny(img, 100, 150)
    
    cv2.imshow("Image", img)
    cv2.imshow("Canny", canny)
    
    indices = np.where(canny != [0])
    coordinates = zip(indices[0], indices[1])
    
    coordinates_list = ""
    for coordinate in coordinates:
        x = "'('{}, {}')', ".format(coordinate[1] / 100, -coordinate[0] / 100)
        coordinates_list += x
    
    coordinates_list = "'('{}')'".format(coordinates_list)
    coordinates_list = coordinates_list.replace("'('", "{")
    coordinates_list = coordinates_list.replace("')'", "}")
    
    print(coordinates_list)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    I use canny to resolve the problem then with the "where" function of numpy I get all the white points and zip it in a variable, the last past of the code is to get the points in a specific format to use it in an other language.