Ask Your Question

Revision history [back]

About contours and sort I think you can use this :

import numpy as np
import cv2  as cv

def surface(p1):
    x1 = cv.contourArea(p1[2])
    return x1

img = cv.imread("g:/lib/opencv/samples/data/pic1.png",cv.IMREAD_GRAYSCALE)
if img is None:
    print("Check file path")
    exit()
ret,imgbin =cv.threshold(img,50,255,cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(imgbin,  cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

ctrhullList=[]
for idx,p in enumerate(contours):
    hull = cv.convexHull(p)
    ctrhullList.append([idx,p,hull])
print ('before sort')
for p in ctrhullList:
    print (p[0],' : Surface = ', cv.contourArea(p[1]),'  HullSurface = ',cv.contourArea(p[2]))
ctrhullList.sort(key=surface)
print ('after sort')
for p in ctrhullList:
    print (p[0],' : Surface = ', cv.contourArea(p[1]),'  HullSurface = ',cv.contourArea(p[2]))
imgctr=np.zeros((img.shape[0],img.shape[1],3),np.uint8)
cv.drawContours(img, contours, -1, (0,255,0), 3)
cv.waitKey()

I use surface as lambda function

About contours and sort I think you can use this :

import numpy as np
import cv2  as cv

def surface(p1):
    x1 = cv.contourArea(p1[2])
    return x1

img = cv.imread("g:/lib/opencv/samples/data/pic1.png",cv.IMREAD_GRAYSCALE)
if img is None:
    print("Check file path")
    exit()
ret,imgbin =cv.threshold(img,50,255,cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(imgbin,  cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

ctrhullList=[]
for idx,p in enumerate(contours):
    hull = cv.convexHull(p)
    ctrhullList.append([idx,p,hull])
print ('before sort')
for p in ctrhullList:
    print (p[0],' : Surface = ', cv.contourArea(p[1]),'  HullSurface = ',cv.contourArea(p[2]))
ctrhullList.sort(key=surface)
print ('after sort')
for p in ctrhullList:
    print (p[0],' : Surface = ', cv.contourArea(p[1]),'  HullSurface = ',cv.contourArea(p[2]))
imgctr=np.zeros((img.shape[0],img.shape[1],3),np.uint8)
cv.drawContours(img, contours, -1, (0,255,0), 3)
cv.waitKey()

I use surface as lambda function

or you can forget lambda function :

import numpy as np
import cv2  as cv


img = cv.imread("g:/lib/opencv/samples/data/pic1.png",cv.IMREAD_GRAYSCALE)
if img is None:
    print("Check file path")
    exit()
ret,imgbin =cv.threshold(img,50,255,cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(imgbin,  cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)

ctrhullList=[]
for idx,p in enumerate(contours):
    hull = cv.convexHull(p)
    ctrhullList.append(cv.contourArea(hull))
print ('before sort')
for idx,p in enumerate(ctrhullList):
    print (idx,' : Surface = ', cv.contourArea(contours[idx]),'  HullSurface = ',p)
ctrhullList = np.array(ctrhullList)
indice=ctrhullList.argsort()
print ('after sort')
for p in indice:
#    print (ctrhullList[p,0],' : Surface = ', cv.contourArea(ctrhullList[p,1]),'  HullSurface = ',cv.contourArea(ctrhullList[p,2]))
    print (p,' : Surface = ', cv.contourArea(contours[p]),'  HullSurface = ',ctrhullList[p])