import numpy as np import cv2 import math imgcolor = cv2.imread('riz.jpg') img=cv2.cvtColor(imgcolor, cv2.COLOR_BGR2GRAY); print(img[0][0]) print(img[254][0]) #ret,thresh1 = cv2.threshold(img,60,255,cv2.THRESH_BINARY) # find otsu's threshold value with OpenCV function blur = cv2.GaussianBlur(img,(5,5),0) ret, thresh1= cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) kernel = np.ones((3,3),np.uint8) erosion = cv2.erode(thresh1,kernel,iterations = 2) ouverture = cv2.dilate(erosion,kernel,iterations = 1) contours, hierarchy = cv2.findContours(ouverture,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) i=0 for data in contours: print("The contours have this data "+str(data)) rect = cv2.minAreaRect(data) l=rect[1][1] m=rect[1][0] w=max(l,m) h=min(l,m) if h>0: aspect=float(w/h) else: aspect=10000000 area = cv2.contourArea(data) hull = cv2.convexHull(data) hull_area = cv2.contourArea(hull) if hull_area>0: solidity=float(area/hull_area) else: solidity=10000000000 perimeter = cv2.arcLength(data,True) #if i%2==0 : if aspect>1.9 and aspect<6 and area>40 and area<200 and solidity>0.8 and perimeter<45: cv2.drawContours(imgcolor,data,-1,(0,0,255),1) i=i+1 else: cv2.drawContours(imgcolor,data,-1,(0,255,0),1) print("hierarchy "+str(hierarchy )) #cv2.drawContours(imgcolor,contours,-1,(0,255,0),1) print(ret) print ("il y a "+str(i)+ " grains de riz") #sauver au format png pour compression sans perte '''cv2.imwrite('riz_ouverture.png',ouverture) cv2.imwrite('riz_erosion.png',erosion) cv2.imwrite('riz_thresh1.png',thresh1) cv2.imwrite('riz_out.png',img)''' cv2.imwrite('riz_out_contour.png',imgcolor) cv2.imshow('image',imgcolor) cv2.waitKey(0) cv2.destroyAllWindows() print("fini")