import numpy as np import cv2 import math from matplotlib import pyplot as plt print("version openCV:"+str( cv2.__version__ )) #niveau de gris if True: # Load an color image in grayscale img = cv2.imread('riz2.jpg',0) print("img.dtype : "+ str(img.dtype)) print("img.shape : "+ str(img.shape)) #le premier scalaire est la hauteur de l'image if img is None: print("Fichier image foireux") exit() print(img) ''' kernel = np.ones((5,5),np.float32)/25 img = cv2.filter2D(img,-1,kernel) img = cv2.filter2D(img,-1,kernel) img = cv2.filter2D(img,-1,kernel) ''' #kernel = np.ones((1,1),np.float32)/4 #img = cv2.filter2D(img,-1,kernel) #plt.hist(img.ravel(),256,[0,256]); plt.show() ret,thresh1 = cv2.threshold(img,200,255,cv2.THRESH_BINARY) # Otsu's thresholding ret2,thresh2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) print("ret2:"+str(ret2)) kernel = np.ones((3,3),np.uint8) erosion = cv2.erode(thresh2,kernel,iterations = 2) dilatation = cv2.dilate(erosion,kernel,iterations = 1) #imgxor = cv2.bitwise_xor(thresh2,erosion) imgxor = cv2.bitwise_xor(thresh2,dilatation) imcolor = cv2.cvtColor(dilatation,cv2.COLOR_GRAY2BGR) imcolor[4,2]=(255,0,0) contours, hierarchy = cv2.findContours(dilatation,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) compteur=0 for data in contours: print("The contours have this data "+str(data)) area = cv2.contourArea(data) hull = cv2.convexHull(data) hull_area = cv2.contourArea(hull) solidity = float(area)/hull_area (x,y),(MA,ma),angle = cv2.fitEllipse(data) if MA=20 and area<=200 and solidity>0.8 and aspect>2: #cv2.drawContours(imcolor,data,-1,(0,255,0),1) cv2.line(imcolor,(x,y-2),(x,y+2),(0,255,0),1) cv2.line(imcolor,(x-2,y),(x+2,y),(0,255,0),1) else: cv2.drawContours(imcolor,data,-1,(0,0,255),1) compteur=compteur+1 cv2.imwrite('imggray.png',img) cv2.imwrite('imgthresh.png',thresh2) cv2.imwrite('imgerosion.png',erosion) cv2.imwrite('imgdilatation.png',dilatation) cv2.imwrite('imgcolor.png',imcolor) cv2.imwrite('imgxor.png',imgxor) cv2.imshow('image',imcolor) cv2.waitKey(0) cv2.destroyAllWindows()