import numpy as np import cv2 import math print("version openCV:"+str( cv2.__version__ )) img = cv2.imread('riz2.jpg',0) # Appliquer le facteur 1/2 aux valeurs des pixels pour tester le seuil adaptatif #img = (img / 2).astype(np.uint8) #ou #img = cv2.convertScaleAbs(img, alpha=0.5, beta=0) ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY) # Otsu's thresholding ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) print("ret2:"+str(ret2)) print(img) print(type(img)) print(img.shape) kernel = np.ones((3,3),np.uint8) erosion = cv2.erode(th2,kernel,iterations = 2) #affichage difference #cv2.imshow('image',th2-erosion) dilation = cv2.dilate(erosion,kernel,iterations = 1) cv2.imwrite('dilation.png',dilation) #affichage difference #cv2.imshow('image',th2-dilation) imgcolor = cv2.cvtColor(dilation, cv2.COLOR_GRAY2BGR) cpt=0 contours, hierarchy = cv2.findContours(dilation,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) for contour in contours: print("The contours have this data " +str(contour)) M = cv2.moments(contour) print(str(M)) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) imgcolor[cy][cx]=[255,0,0] area = cv2.contourArea(contour) perimeter = cv2.arcLength(contour,True) hull = cv2.convexHull(contour) rect = cv2.minAreaRect(contour) aspectratio=max(rect[1])/min(rect[1]) hullarea = cv2.contourArea(hull) #box = cv2.boxPoints(rect) #box = np.int0(box) solidity=float(area)/hullarea #if cpt%2==0: if area>20 and area<200 and aspectratio> 2 and aspectratio<6 and solidity>0.8: cv2.drawContours(imgcolor,contour,-1,(0,255,0),1) else: cv2.drawContours(imgcolor,contour,-1,(0,0,255),1) cpt=cpt+1 cv2.imshow('image',imgcolor) cv2.waitKey(0) cv2.destroyAllWindows()