标签:hiera numpy holo win arch simple wait ons bad
运行环境:python3.6.9 opencv3.4.10
import cv2 import numpy as np font=cv2.FONT_HERSHEY_COMPLEX kernel = np.ones((7,7),np.uint8) img=cv2.imread(‘corn.jpg‘,1) # 1代表深度8,3通道 img_orgin=img cv2.imshow(‘orgin‘,img) cv2.waitKey(0) gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#灰度处理 #cv2.imshow(‘gray_img‘,gray_img) #cv2.waitKey(0) ret,th1=cv2.threshold(gray_img,120,255,cv2.THRESH_BINARY) #cv2.imshow(‘th1‘,th1) #cv2.waitKey(0) erosion = cv2.erode(th1,kernel,iterations = 1)#腐蚀 #cv2.imshow(‘erosion‘,erosion) #cv2.waitKey(0) dist_img = cv2.distanceTransform(erosion, cv2.DIST_L1, cv2.DIST_MASK_3)#距离变换 #cv2.imshow(‘距离变换‘,dist_img) #cv2.waitKey(0) dist_output = cv2.normalize(dist_img, 0, 1.0, cv2.NORM_MINMAX)#归一化 #cv2.imshow(‘dist_output‘,dist_output*80) #cv2.waitKey(0) ret,th2=cv2.threshold(dist_output*80,0.3,255,cv2.THRESH_BINARY) #cv2.imshow(‘th2‘,th2) #cv2.waitKey(0) kernel = np.ones((5,5),np.uint8) opening = cv2.morphologyEx(th2, cv2.MORPH_OPEN, kernel) #cv2.imshow(‘opening‘,opening) #cv2.waitKey(0) opening = np.array(opening,np.uint8) img,contours, hierarchy = cv2.findContours(opening,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)#轮廓提取 count_sum=count_1=count_2=count_3=0 for cnt in contours: (x,y),radius = cv2.minEnclosingCircle(cnt) center = (int(x),int(y)) radius = int(radius) circle_img = cv2.circle(opening,center,radius,(255,255,255),1) area = cv2.contourArea(cnt) area_circle=3.14*radius*radius #print(area/area_circle) if area/area_circle <=0.5: #img = cv2.drawContours(img_orgin, cnt, -1, (0,0,255), 5)#差(红色) img=cv2.putText(img_orgin,‘bad‘,center,font,0.5,(0,0,255)) count_1+=1 elif area/area_circle >=0.6: #img = cv2.drawContours(img_orgin, cnt, -1, (0,255,0), 5)#优(绿色) img=cv2.putText(img_orgin,‘good‘,center,font,0.5,(0,255,0)) count_2+=1 else: #img = cv2.drawContours(img_orgin, cnt, -1, (255,0,0), 5)#良(蓝色) img=cv2.putText(img_orgin,‘normal‘,center,font,0.5,(255,0,0)) count_3+=1 count_sum=count_1+count_2+count_3 img=cv2.putText(img,(‘sum=‘+str(count_sum)),(30,50),font,1,(0,0,0)) img=cv2.putText(img,(‘good=‘+str(count_2)),(30,80),font,1,(0,255,0)) img=cv2.putText(img,(‘normal=‘+str(count_3)),(30,110),font,1,(255,0,0)) img=cv2.putText(img,(‘bad=‘+str(count_1)),(30,140),font,1,(0,0,255)) cv2.imshow(‘circle_img‘,img) cv2.waitKey(0) cv2.destroyAllWindows() print(‘玉米粒共有:‘,count_sum)
运行结果:
标签:hiera numpy holo win arch simple wait ons bad
原文地址:https://www.cnblogs.com/pine-apple/p/13236810.html