Matteo Possamai
Matteo Possamai

Reputation: 574

Opencv findCountours function

I'm trying to learn opencv. Online i found that, with opencv, I can obtain the contours of some image. So i tried that. Here is the script:

import cv2
import numpy as np

def getC(imagine):
    global imgContour
    c,h = cv2.findContours(imagine,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    for cnt in c:
        a = cv2.contourArea(cnt)
        print(area)
        if area>500:
            cv2.drawContour(imgContour,cnt,-1,(255,0,0),3)

img = cv2.imread("a3.jpg")
imgContour = img.copy()
imgG = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgB = cv2.GaussianBlur(imgG,(7,7),1)
imgC = cv2.Canny(imgB,50,50)

getC(imgContour)

cv2.imshow("",img)
cv2.imshow("g",imgG)
cv2.imshow("b",imgB)
cv2.imshow("l",imgContour)
cv2.waitKey(0)

I think there is a problem with global variabiles, but also with the format. a3.jpg is that image.

I don't now what to do now, and how to resolve the issue.

Thanks for the help

Upvotes: 0

Views: 81

Answers (1)

Karim Elgazar
Karim Elgazar

Reputation: 194

  1. you saved the area as the variable a but used it with the name area you can fix this by changing the variable name a to area
area = cv2.contourArea(cnt)
  1. there is a typo in cv2.drawContour you should write it like that cv2.drawContours

  2. cv2.drawContours method expects the contour you want to draw to be a list of lists so you need to call it like that

cv2.drawContours(imgContour,[cnt],-1,(255,0,0),3)
  1. when you pass the image to the getC method you gave it an image without pre-processing this image and converting it to threshold image using canny so you need to call it like that
getC(imgC)

The Final Script


import cv2
import numpy as np


def getC(imagine):

    global imgContour
    print(imgContour.shape)
    c,h = cv2.findContours(imagine,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    for cnt in c:
        area = cv2.contourArea(cnt)
        print(area)
        if area>500:
            cv2.drawContours(imgContour,[cnt],-1,(255,0,0),3)


img = cv2.imread("./a3.jpg")
imgContour = img.copy()

imgG = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgB = cv2.GaussianBlur(imgG,(7,7),1)
imgC = cv2.Canny(imgB,50,50)

getC(imgC)

cv2.imshow("",img)
cv2.imshow("g",imgG)
cv2.imshow("b",imgB)
cv2.imshow("l",imgContour)
cv2.waitKey(0)

Upvotes: 2

Related Questions