import numpy as np import cv2 import math print("version openCV:"+str( cv2.__version__ )) img = cv2.imread('riz2.jpg',cv2.IMREAD_COLOR) imggray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #imggray=(0.5*imggray).astype(np.uint8) cv2.imwrite('imggray.png',imggray) ret,imgthresh1 = cv2.threshold(imggray,63,255,cv2.THRESH_BINARY) ret2,imgthresh2 = cv2.threshold(imggray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) print(ret2) cv2.imwrite('imgthresh1.png',imgthresh1) cv2.imwrite('imgthresh2.png',imgthresh2) kernel = np.ones((3,3),np.uint8) imgerosion = cv2.erode(imgthresh2,kernel,iterations = 2) cv2.imwrite('imgerosion.png',imgerosion) imgeouverture = cv2.dilate(imgerosion,kernel,iterations = 1) #comparons les 2 images imgdiff=cv2.bitwise_xor(imgthresh2,imgeouverture) cv2.imwrite('imgdiff.png',imgdiff) cv2.imwrite('imgeouverture.png',imgeouverture) contours, hierarchy = cv2.findContours(imgeouverture,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for indice,contour in enumerate(contours): print("The contours have this data: "+ str(contour) ) M = cv2.moments(contour) print("M:"+str(M)) surface=M['m00'] print("surface:" +str(surface)) cu = int(M['m10']/M['m00']) cv = int(M['m01']/M['m00']) #if indice%2==0: img[cv,cu]=[255,0,0] rect = cv2.minAreaRect(contour) box = cv2.boxPoints(rect) box = np.int0(box) #img = cv2.drawContours(img,[box],0,(0,255,255),1) print("rect:"+str(rect)) w=rect[1][0] h=rect[1][1] if w20 and surface<200 and solidity>0.8 and aspect_ratio> 2 and aspect_ratio<6: cv2.drawContours(img,[contour],-1,(0,255,0),1) else: cv2.drawContours(img,[contour],-1,(0,0,255),1) epsilon = 0.1*cv2.arcLength(contour,True) approx = cv2.approxPolyDP(contour,epsilon,True) #cv2.drawContours(img,[approx],-1,(255,0,0),1) cv2.imwrite('imgcontour.png',img) print("hierarchy:"+str(hierarchy)) cv2.imshow('image',imgerosion) cv2.waitKey(0) cv2.destroyAllWindows()